coinley-test 0.0.21 → 0.0.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.umd.js CHANGED
@@ -1,2 +1,2 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("framer-motion"),require("lucide-react"),require("@coinley/wallet-connect-core"),require("axios")):"function"==typeof define&&define.amd?define(["exports","react","framer-motion","lucide-react","@coinley/wallet-connect-core","axios"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).CoinleyTest={},e.React,e.FramerMotion,e.LucideReact,e.CoinleyWalletCore,e.axios)}(this,function(e,t,s,a,r,n){"use strict";var o={exports:{}},l={},c=t,i=Symbol.for("react.element"),d=Symbol.for("react.fragment"),m=Object.prototype.hasOwnProperty,h=c.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,u={key:!0,ref:!0,__self:!0,__source:!0};function x(e,t,s){var a,r={},n=null,o=null;for(a in void 0!==s&&(n=""+s),void 0!==t.key&&(n=""+t.key),void 0!==t.ref&&(o=t.ref),t)m.call(t,a)&&!u.hasOwnProperty(a)&&(r[a]=t[a]);if(e&&e.defaultProps)for(a in t=e.defaultProps)void 0===r[a]&&(r[a]=t[a]);return{$$typeof:i,type:e,key:n,ref:o,props:r,_owner:h.current}}l.Fragment=d,l.jsx=x,l.jsxs=x,o.exports=l;var y=o.exports;class p{constructor(e,t,s){this.apiKey=t,this.apiSecret=s,this.api=n.create({baseURL:e.endsWith("/")?e.slice(0,-1):e,timeout:3e4,headers:{"Content-Type":"application/json"}}),this.api.interceptors.request.use(e=>{var t;e.headers["X-API-Key"]=this.apiKey,e.headers["X-API-Secret"]=this.apiSecret;const s=this.generateMerchantToken();return s&&(e.headers.Authorization=`Bearer ${s}`),console.log("API Request:",{method:null==(t=e.method)?void 0:t.toUpperCase(),url:e.url,data:e.data}),e},e=>(console.error("Request interceptor error:",e),Promise.reject(e))),this.api.interceptors.response.use(e=>(console.log("API Response:",{status:e.status,url:e.config.url,data:e.data}),e),e=>{var t,s,a,r,n;if(console.error("API Error:",{status:null==(t=e.response)?void 0:t.status,data:null==(s=e.response)?void 0:s.data,message:e.message}),401===(null==(a=e.response)?void 0:a.status))throw new Error("Authentication failed. Please check your API credentials.");if(404===(null==(r=e.response)?void 0:r.status))throw new Error("API endpoint not found. Please check your API URL.");if((null==(n=e.response)?void 0:n.status)>=500)throw new Error("Server error. Please try again later.");throw e})}generateMerchantToken(){try{const e=`${this.apiKey}:${this.apiSecret}`;return btoa(e)}catch(e){return console.error("Failed to generate token:",e),null}}async createPayment(e){var t,s;try{return(await this.api.post("/api/payments/create",e)).data}catch(a){if(null==(s=null==(t=a.response)?void 0:t.data)?void 0:s.error)throw new Error(a.response.data.error);throw new Error(a.message||"Failed to create payment")}}async getPayment(e){var t,s;try{return(await this.api.get(`/api/payments/${e}`)).data}catch(a){if(null==(s=null==(t=a.response)?void 0:t.data)?void 0:s.error)throw new Error(a.response.data.error);throw new Error(a.message||"Failed to get payment details")}}async getNetworks(){try{return(await this.api.get("/api/networks")).data}catch(e){return console.error("Get networks failed:",e),{networks:[{id:"ethereum",name:"Ethereum",shortName:"ethereum",chainId:"1",type:"ethereum",explorerUrl:"https://etherscan.io",isTestnet:!1},{id:"bsc",name:"Binance Smart Chain",shortName:"bsc",chainId:"56",type:"bsc",explorerUrl:"https://bscscan.com",isTestnet:!1},{id:"polygon",name:"Polygon",shortName:"polygon",chainId:"137",type:"ethereum",explorerUrl:"https://polygonscan.com",isTestnet:!1}]}}}async getStablecoins(){try{return(await this.api.get("/api/networks/stablecoins")).data}catch(e){return console.error("Get stablecoins failed:",e),{stablecoins:[{id:"usdt-eth",name:"Tether USD",symbol:"USDT",contractAddress:"0xdAC17F958D2ee523a2206206994597C13D831ec7",decimals:6,isStablecoin:!0,networkId:"ethereum",Network:{id:"ethereum",name:"Ethereum",shortName:"ethereum",type:"ethereum"}},{id:"usdc-eth",name:"USD Coin",symbol:"USDC",contractAddress:"0xA0b86a33E6441d81d0B93bF9EE0f74ca32F7e6f6",decimals:6,isStablecoin:!0,networkId:"ethereum",Network:{id:"ethereum",name:"Ethereum",shortName:"ethereum",type:"ethereum"}}]}}}async verifyQRPayment(e){var t,s;try{return(await this.api.post("/api/payments/verify-qr",{paymentId:e})).data}catch(a){if(null==(s=null==(t=a.response)?void 0:t.data)?void 0:s.error)throw new Error(a.response.data.error);throw new Error(a.message||"Failed to verify payment")}}async processPayment(e,t,s,a){var r,n;try{return(await this.api.post("/api/payments/process",{paymentId:e,transactionHash:t,network:s,senderAddress:a})).data}catch(o){if(null==(n=null==(r=o.response)?void 0:r.data)?void 0:n.error)throw new Error(o.response.data.error);throw new Error(o.message||"Failed to process payment")}}async healthCheck(){try{return 200===(await this.api.get("/api/health")).status}catch(e){return console.error("Health check failed:",e),!1}}}const g=({selectedNetwork:e,selectedToken:t,paymentData:s,config:n,onTransactionSent:o,onError:l,isConnecting:c,setIsConnecting:i})=>{const{isConnected:d,address:m,disconnect:h}=r.useWallet(),{connectWallet:u,isPending:x}=r.useWalletConnect(),{detectedWallets:p,hasWallets:g,walletCount:f}=r.useWalletDetection(),{sendTransaction:b}=r.useWalletTransaction(),{openModal:w}=r.useWalletModal();p.filter(e=>e.name.toLowerCase().includes("metamask")||"injected"===e.provider||e.name.toLowerCase().includes("coinbase")||e.name.toLowerCase().includes("wallet connect"));const j=async e=>{try{if(i(!0),d&&(await h(),await new Promise(e=>setTimeout(e,1e3))),"metamask"===e&&window.ethereum&&window.ethereum.isMetaMask)try{await window.ethereum.request({method:"eth_requestAccounts"}),console.log("✅ Connected directly to MetaMask")}catch(t){throw console.error("MetaMask connection failed:",t),t}else await u(e)}catch(t){console.error("Wallet connection failed:",t),l(t.message||"Failed to connect wallet")}finally{i(!1)}};return y.jsx("div",{className:"text-center space-y-6",children:y.jsxs("div",{className:"space-y-4",children:[y.jsx("div",{className:"w-16 h-16 bg-[#7042D2] bg-opacity-20 rounded-full flex items-center justify-center mx-auto",children:y.jsx(a.Wallet,{className:"w-8 h-8 text-[#7042D2]"})}),d?y.jsxs(y.Fragment,{children:[y.jsx("h3",{className:"text-lg font-semibold text-green-600",children:"Wallet Connected ✅"}),y.jsxs("div",{className:"bg-gray-50 dark:bg-gray-800 rounded-lg p-4 space-y-3",children:[y.jsxs("div",{className:"flex justify-between items-center",children:[y.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Address:"}),y.jsxs("div",{className:"flex items-center space-x-2",children:[y.jsxs("span",{className:"font-mono text-sm",children:[null==m?void 0:m.slice(0,6),"...",null==m?void 0:m.slice(-4)]}),y.jsx("button",{onClick:async()=>{try{await h()}catch(e){console.error("Disconnect error:",e)}},className:"text-xs text-red-600 hover:text-red-800",children:"Disconnect"})]})]}),s&&y.jsxs(y.Fragment,{children:[y.jsxs("div",{className:"flex justify-between items-center",children:[y.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Amount:"}),y.jsxs("span",{className:"font-medium",children:[s.totalAmount," ",null==t?void 0:t.symbol]})]}),y.jsxs("div",{className:"flex justify-between items-center",children:[y.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Network:"}),y.jsx("span",{className:"font-medium",children:null==e?void 0:e.name})]})]})]}),y.jsx("button",{onClick:async()=>{var a;if(d&&s&&t)try{i(!0),console.log("🔍 Transaction Debug:"),console.log("Connected wallet address:",m),console.log("Payment data:",s),console.log("Selected token:",t),console.log("Selected network:",e);let r,n=null==(a=s.metadata)?void 0:a.recipientWallet;if(console.log("Merchant recipient address:",n),!n||"string"!=typeof n)throw new Error("Merchant wallet address not found in payment data");if(!n.match(/^0x[a-fA-F0-9]{40}$/))throw new Error(`Invalid merchant address format: ${n}`);if(t.contractAddress){console.log("🔍 ERC-20 Transaction Details:"),console.log("Token contract:",t.contractAddress),console.log("Token decimals:",t.decimals),console.log("Payment amount:",s.totalAmount);const e=t.decimals||6,a=Math.floor(s.totalAmount*Math.pow(10,e));console.log("Calculated amount (with decimals):",a);const o="0xa9059cbb",l=n.slice(2).toLowerCase().padStart(64,"0"),c=a.toString(16).padStart(64,"0"),i=`${o}${l}${c}`;console.log("🔍 Transaction Data:"),console.log("Method ID:",o),console.log("Recipient (padded):",l),console.log("Amount (padded):",c),console.log("Full data:",i);const d={to:t.contractAddress,data:i,value:"0x0"};console.log("📤 Sending ERC-20 transaction:",d),r=await b(d)}else{const e=Math.floor(s.totalAmount*Math.pow(10,18)),t={to:n,value:`0x${e.toString(16)}`};console.log("📤 Sending native transaction:",t),r=await b(t)}r&&(console.log("✅ Transaction sent successfully:",r),o(r))}catch(r){console.error("❌ Transaction failed:",r),l(r.message||"Transaction failed")}finally{i(!1)}else l("Wallet not connected or payment data missing")},disabled:c,className:"w-full bg-[#7042D2] text-white py-4 rounded-lg font-semibold hover:bg-[#7042D2]/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center space-x-2",children:c?y.jsxs(y.Fragment,{children:[y.jsx(a.Loader2,{className:"w-5 h-5 animate-spin"}),y.jsx("span",{children:"Processing Payment..."})]}):y.jsxs(y.Fragment,{children:[y.jsx(a.Zap,{className:"w-5 h-5"}),y.jsx("span",{children:"Send Payment"})]})}),y.jsxs("p",{className:"text-xs text-gray-500",children:["Make sure you have enough ",null==t?void 0:t.symbol," and ETH for gas fees"]})]}):y.jsxs(y.Fragment,{children:[y.jsx("h3",{className:"text-lg font-semibold",children:"Connect Your Wallet"}),y.jsx("p",{className:"text-gray-600 dark:text-gray-400 text-sm",children:"Choose your preferred wallet to complete the payment"}),y.jsxs("div",{className:"space-y-3",children:[y.jsxs("button",{onClick:()=>j("metamask"),disabled:x||c,className:"w-full p-3 border border-gray-300 rounded-lg hover:border-[#7042D2] flex items-center space-x-3 transition-colors disabled:opacity-50",children:[y.jsx("span",{className:"text-xl",children:"🦊"}),y.jsxs("div",{className:"text-left flex-1",children:[y.jsx("div",{className:"font-medium",children:"MetaMask"}),y.jsx("div",{className:"text-xs text-gray-500",children:"Connect with MetaMask"})]})]}),y.jsxs("button",{onClick:()=>{try{console.log("Attempting to open wallet modal..."),w()}catch(e){console.error("Failed to open modal:",e),j("injected")}},disabled:x||c,className:"w-full p-3 border border-gray-300 rounded-lg hover:border-[#7042D2] flex items-center space-x-3 transition-colors disabled:opacity-50",children:[y.jsx("span",{className:"text-xl",children:"💼"}),y.jsxs("div",{className:"text-left flex-1",children:[y.jsx("div",{className:"font-medium",children:"Other Wallets"}),y.jsx("div",{className:"text-xs text-gray-500",children:"Choose from available wallets"})]})]}),y.jsx("button",{onClick:()=>j("injected"),disabled:x||c,className:"w-full p-2 text-sm border border-dashed border-gray-300 rounded-lg hover:border-[#7042D2] transition-colors disabled:opacity-50",children:"Try Direct Connection"})]}),c&&y.jsxs("div",{className:"flex items-center justify-center space-x-2 text-gray-600",children:[y.jsx(a.Loader2,{className:"w-4 h-4 animate-spin"}),y.jsx("span",{children:"Connecting..."})]})]})]})})},f=({apiKey:e,apiSecret:n,apiUrl:o="http://localhost:9000",onSuccess:l,onError:c,onClose:i,isOpen:d,config:m,theme:h="light",merchantName:u,debug:x=!1})=>{const[f,b]=t.useState("select-method"),[w,j]=t.useState([]),[v,N]=t.useState([]),[k,C]=t.useState(null),[S,P]=t.useState(null),[A,T]=t.useState(null),[E,D]=t.useState(""),[M,W]=t.useState(null),[I,F]=t.useState(!1),[$,U]=t.useState(""),[R,q]=t.useState(!1),[L,_]=t.useState(""),[O,H]=t.useState(!1),B=t.useRef(new p(o,e,n)),K=r.createCoinleyWalletConfig({appName:u||"Coinley Payment",appDescription:"Crypto payment processing",chains:[{id:1,name:"Ethereum",network:"ethereum",rpcUrls:{default:{http:["https://eth.llamarpc.com"]}},nativeCurrency:{name:"Ethereum",symbol:"ETH",decimals:18}},{id:56,name:"BNB Smart Chain",network:"bsc",rpcUrls:{default:{http:["https://bsc-dataseed1.binance.org"]}},nativeCurrency:{name:"BNB",symbol:"BNB",decimals:18}}]});t.useEffect(()=>{d&&Q()},[d]);const Q=async()=>{try{F(!0),U("");const[e,t]=await Promise.all([B.current.getNetworks(),B.current.getStablecoins()]);j(e.networks||[]),N(t.stablecoins||[]),x&&(console.log("Initialized networks:",e.networks),console.log("Initialized tokens:",t.stablecoins))}catch(e){console.error("Failed to initialize payment:",e),U("Failed to load payment options. Please try again.")}finally{F(!1)}},z=e=>{T(e),b("select-network")},X=async(e,t)=>{try{F(!0);const s={amount:m.amount,currency:t.symbol,network:e.shortName,customerEmail:m.customerEmail,callbackUrl:m.callbackUrl,metadata:{...m.metadata,paymentMethod:A,selectedNetwork:e.shortName,selectedToken:t.symbol,merchantWalletAddresses:m.merchantWalletAddresses}};console.log("🔍 Payment payload with merchant wallets:",s);const a=await B.current.createPayment(s);W(a.payment),"wallet"===A?b("wallet-connect"):(await Y(a.payment),b("qr-code"))}catch(s){console.error("Payment initiation failed:",s),U(s.message||"Failed to create payment"),b("error")}finally{F(!1)}},Y=async e=>{var t,s;try{const a=(null==(t=e.metadata)?void 0:t.recipientWallet)||(null==(s=m.merchantWalletAddresses)?void 0:s[(null==k?void 0:k.shortName)||""]);if(!a)throw new Error("Recipient wallet address not found");let r="";r="ethereum"===(null==k?void 0:k.type)||"bsc"===(null==k?void 0:k.type)?(null==S?void 0:S.contractAddress)?`ethereum:${S.contractAddress}/transfer?address=${a}&uint256=${e.totalAmount*Math.pow(10,S.decimals)}`:`ethereum:${a}?value=${e.totalAmount}e18`:"tron"===(null==k?void 0:k.type)?`tron:${a}?amount=${e.totalAmount}`:`${null==S?void 0:S.symbol}:${a}?amount=${e.totalAmount}`,D(a),Z(e.id)}catch(a){console.error("QR code generation failed:",a),U("Failed to generate QR code"),b("error")}},Z=async e=>{let t=0;const s=async()=>{var a;try{const r=await B.current.verifyQRPayment(e);return r.verified&&(null==(a=r.payment)?void 0:a.transactionHash)?(_(r.payment.transactionHash),await G(e,r.payment.transactionHash),!0):(t++,t<60?setTimeout(s,5e3):(U("Payment verification timeout. Please check your transaction."),b("error")),!1)}catch(r){return console.error("Payment verification error:",r),t++,t<60?setTimeout(s,5e3):(U("Payment verification failed"),b("error")),!1}};setTimeout(s,2e3)},G=async(e,t)=>{b("success"),l&&l(e,t,{network:null==k?void 0:k.name,token:null==S?void 0:S.symbol,amount:null==M?void 0:M.totalAmount,method:A})},V=()=>{b("select-method"),T(null),C(null),P(null),D(""),W(null),U(""),_(""),i&&i()};return d?y.jsxs(r.CoinleyWalletProvider,{config:K,walletConfig:{appName:u||"Coinley Payment"},children:[y.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50 backdrop-blur-sm",children:y.jsxs(s.motion.div,{initial:{scale:.9,opacity:0},animate:{scale:1,opacity:1},exit:{scale:.9,opacity:0},className:"relative w-full max-w-md mx-4 rounded-2xl shadow-2xl overflow-hidden "+("dark"===h?"bg-gray-900 text-white":"bg-white text-gray-900"),children:[y.jsxs("div",{className:"relative p-6 border-b border-gray-200 dark:border-gray-700",children:["select-method"!==f&&"success"!==f&&"error"!==f&&y.jsx("button",{onClick:()=>{if("select-network"===f)b("select-method");else if("select-token"===f)b("select-network");else if("wallet-connect"===f||"qr-code"===f){v.filter(e=>{var t;return(null==(t=e.Network)?void 0:t.shortName)===(null==k?void 0:k.shortName)||e.networkId===(null==k?void 0:k.id)}).length>1?b("select-token"):b("select-network")}},className:"absolute left-4 top-6 p-1 rounded-full hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors",children:y.jsx(a.ArrowLeft,{className:"w-5 h-5"})}),y.jsx("button",{onClick:V,className:"absolute right-4 top-6 p-1 rounded-full hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors",children:y.jsx(a.X,{className:"w-5 h-5"})}),y.jsxs("div",{className:"text-center",children:[y.jsxs("div",{className:"flex items-center justify-center space-x-2 mb-2",children:[y.jsx(a.Sparkles,{className:"w-5 h-5 text-[#7042D2]"}),y.jsx("h2",{className:"text-xl font-bold",children:"Pay with Crypto"}),y.jsx(a.Sparkles,{className:"w-5 h-5 text-[#7042D2]"})]}),u&&y.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 mt-1",children:u}),y.jsx("div",{className:"mt-2",children:y.jsxs("span",{className:"text-2xl font-bold text-[#7042D2]",children:["$",m.amount.toFixed(2)]})})]})]}),y.jsx("div",{className:"p-6 min-h-[400px]",children:y.jsxs(s.AnimatePresence,{mode:"wait",children:["select-method"===f&&y.jsxs(s.motion.div,{initial:{x:20,opacity:0},animate:{x:0,opacity:1},exit:{x:-20,opacity:0},className:"space-y-4",children:[y.jsx("h3",{className:"text-lg font-semibold text-center mb-6",children:"Choose Payment Method"}),y.jsx(s.motion.button,{whileHover:{scale:1.02},whileTap:{scale:.98},onClick:()=>z("wallet"),className:"w-full p-4 border-2 border-gray-200 dark:border-gray-700 rounded-xl hover:border-[#7042D2] transition-colors group",children:y.jsxs("div",{className:"flex items-center space-x-4",children:[y.jsx("div",{className:"p-3 bg-[#7042D2] bg-opacity-10 rounded-lg group-hover:bg-opacity-20 transition-colors",children:y.jsx(a.Wallet,{className:"w-6 h-6 text-[#7042D2]"})}),y.jsxs("div",{className:"text-left",children:[y.jsx("div",{className:"font-semibold",children:"Connect Wallet"}),y.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-400",children:"MetaMask, WalletConnect & more"})]}),y.jsx(a.Zap,{className:"w-5 h-5 text-[#7042D2] ml-auto"})]})}),y.jsx(s.motion.button,{whileHover:{scale:1.02},whileTap:{scale:.98},onClick:()=>z("qr"),className:"w-full p-4 border-2 border-gray-200 dark:border-gray-700 rounded-xl hover:border-[#7042D2] transition-colors group",children:y.jsxs("div",{className:"flex items-center space-x-4",children:[y.jsx("div",{className:"p-3 bg-[#7042D2] bg-opacity-10 rounded-lg group-hover:bg-opacity-20 transition-colors",children:y.jsx(a.QrCode,{className:"w-6 h-6 text-[#7042D2]"})}),y.jsxs("div",{className:"text-left",children:[y.jsx("div",{className:"font-semibold",children:"QR Code"}),y.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Scan with mobile wallet"})]})]})})]},"select-method"),"select-network"===f&&y.jsxs(s.motion.div,{initial:{x:20,opacity:0},animate:{x:0,opacity:1},exit:{x:-20,opacity:0},className:"space-y-4",children:[y.jsx("h3",{className:"text-lg font-semibold text-center mb-6",children:"Select Network"}),I?y.jsx("div",{className:"flex justify-center py-8",children:y.jsx(a.Loader2,{className:"w-8 h-8 animate-spin text-[#7042D2]"})}):y.jsx("div",{className:"space-y-3",children:w.map(e=>y.jsx(s.motion.button,{whileHover:{scale:1.02},whileTap:{scale:.98},onClick:()=>(async e=>{C(e);const t=v.filter(t=>{var s;return(null==(s=t.Network)?void 0:s.shortName)===e.shortName||t.networkId===e.id});if(t.length>1)b("select-token");else if(1===t.length){const s=t[0];P(s),await X(e,s)}else U(`No supported tokens found for ${e.name}`),b("error")})(e),className:"w-full p-4 border-2 border-gray-200 dark:border-gray-700 rounded-xl hover:border-[#7042D2] transition-colors group",children:y.jsxs("div",{className:"flex items-center space-x-4",children:[e.logo?y.jsx("img",{src:e.logo,alt:e.name,className:"w-8 h-8 rounded-full"}):y.jsx("div",{className:"w-8 h-8 bg-[#7042D2] bg-opacity-20 rounded-full flex items-center justify-center",children:y.jsx("span",{className:"text-sm font-bold text-[#7042D2]",children:e.shortName.charAt(0).toUpperCase()})}),y.jsxs("div",{className:"text-left flex-1",children:[y.jsx("div",{className:"font-semibold",children:e.name}),y.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-400",children:e.shortName.toUpperCase()})]}),y.jsx(a.ChevronDown,{className:"w-5 h-5 text-gray-400 transform -rotate-90"})]})},e.id))})]},"select-network"),"select-token"===f&&y.jsxs(s.motion.div,{initial:{x:20,opacity:0},animate:{x:0,opacity:1},exit:{x:-20,opacity:0},className:"space-y-4",children:[y.jsxs("h3",{className:"text-lg font-semibold text-center mb-6",children:["Select Token on ",null==k?void 0:k.name]}),I?y.jsx("div",{className:"flex justify-center py-8",children:y.jsx(a.Loader2,{className:"w-8 h-8 animate-spin text-[#7042D2]"})}):y.jsx("div",{className:"space-y-3",children:v.filter(e=>{var t;return(null==(t=e.Network)?void 0:t.shortName)===(null==k?void 0:k.shortName)||e.networkId===(null==k?void 0:k.id)}).map(e=>y.jsx(s.motion.button,{whileHover:{scale:1.02},whileTap:{scale:.98},onClick:()=>(async e=>{P(e),await X(k,e)})(e),className:"w-full p-4 border-2 border-gray-200 dark:border-gray-700 rounded-xl hover:border-[#7042D2] transition-colors group",children:y.jsxs("div",{className:"flex items-center space-x-4",children:[e.logo?y.jsx("img",{src:e.logo,alt:e.symbol,className:"w-8 h-8 rounded-full"}):y.jsx("div",{className:"w-8 h-8 bg-[#7042D2] bg-opacity-20 rounded-full flex items-center justify-center",children:y.jsx("span",{className:"text-sm font-bold text-[#7042D2]",children:e.symbol.charAt(0)})}),y.jsxs("div",{className:"text-left flex-1",children:[y.jsx("div",{className:"font-semibold",children:e.name}),y.jsxs("div",{className:"text-sm text-gray-600 dark:text-gray-400",children:[e.symbol,e.isStablecoin&&y.jsx("span",{className:"ml-2 px-2 py-0.5 bg-green-100 text-green-600 text-xs rounded-full",children:"Stablecoin"})]})]}),y.jsx(a.ChevronDown,{className:"w-5 h-5 text-gray-400 transform -rotate-90"})]})},e.id))})]},"select-token"),"wallet-connect"===f&&y.jsx(s.motion.div,{initial:{x:20,opacity:0},animate:{x:0,opacity:1},exit:{x:-20,opacity:0},children:y.jsx(g,{selectedNetwork:k,selectedToken:S,paymentData:M,config:m,onTransactionSent:async e=>{_(e),b("processing");try{await B.current.processPayment(M.id,e,(null==k?void 0:k.shortName)||"",""),await G(M.id,e)}catch(t){console.error("Payment processing failed:",t),await G(M.id,e)}},onError:U,isConnecting:O,setIsConnecting:H})},"wallet-connect"),"qr-code"===f&&y.jsxs(s.motion.div,{initial:{x:20,opacity:0},animate:{x:0,opacity:1},exit:{x:-20,opacity:0},className:"text-center space-y-6",children:[y.jsxs("div",{className:"space-y-4",children:[y.jsx("h3",{className:"text-lg font-semibold",children:"Scan QR Code"}),y.jsx("p",{className:"text-gray-600 dark:text-gray-400",children:"Use your mobile wallet to scan and pay"})]}),E&&y.jsx("div",{className:"bg-white p-4 rounded-xl mx-auto inline-block",children:y.jsxs("div",{className:"w-48 h-48 flex items-center justify-center text-gray-500",children:["QR Code: ",E.slice(0,10),"...",E.slice(-4)]})}),M&&y.jsxs("div",{className:"space-y-3",children:[y.jsxs("div",{className:"bg-gray-50 dark:bg-gray-800 rounded-lg p-4 space-y-2",children:[y.jsxs("div",{className:"flex justify-between items-center",children:[y.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Network:"}),y.jsx("span",{className:"font-medium",children:null==k?void 0:k.name})]}),y.jsxs("div",{className:"flex justify-between items-center",children:[y.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Amount:"}),y.jsxs("span",{className:"font-medium",children:[M.totalAmount," ",null==S?void 0:S.symbol]})]})]}),y.jsxs("div",{className:"flex items-center justify-center space-x-2 text-sm text-gray-600 dark:text-gray-400",children:[y.jsx(a.Loader2,{className:"w-4 h-4 animate-spin"}),y.jsx("span",{children:"Waiting for payment..."})]})]})]},"qr-code"),"processing"===f&&y.jsxs(s.motion.div,{initial:{scale:.8,opacity:0},animate:{scale:1,opacity:1},className:"text-center space-y-6",children:[y.jsx("div",{className:"w-16 h-16 bg-[#7042D2] bg-opacity-20 rounded-full flex items-center justify-center mx-auto",children:y.jsx(a.Loader2,{className:"w-8 h-8 animate-spin text-[#7042D2]"})}),y.jsxs("div",{children:[y.jsx("h3",{className:"text-lg font-semibold text-[#7042D2]",children:"Processing Payment..."}),y.jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-2",children:"Your transaction is being processed"})]})]},"processing"),"success"===f&&y.jsxs(s.motion.div,{initial:{scale:.8,opacity:0},animate:{scale:1,opacity:1},className:"text-center space-y-6",children:[y.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto",children:y.jsx(a.CheckCircle2,{className:"w-8 h-8 text-green-500"})}),y.jsxs("div",{children:[y.jsx("h3",{className:"text-lg font-semibold text-green-600",children:"Payment Successful!"}),y.jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-2",children:"Your payment has been processed successfully"})]}),L&&y.jsx("div",{className:"bg-gray-50 dark:bg-gray-800 rounded-lg p-4",children:y.jsxs("div",{className:"flex justify-between items-center",children:[y.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Transaction:"}),y.jsxs("div",{className:"flex items-center space-x-2",children:[y.jsxs("span",{className:"font-mono text-sm",children:[L.slice(0,6),"...",L.slice(-4)]}),y.jsx("button",{onClick:()=>(async e=>{try{await navigator.clipboard.writeText(e),q(!0),setTimeout(()=>q(!1),2e3)}catch(t){console.error("Failed to copy:",t)}})(L),className:"p-1 hover:bg-gray-200 dark:hover:bg-gray-700 rounded",children:y.jsx(a.Copy,{className:"w-4 h-4"})}),(null==k?void 0:k.explorerUrl)&&y.jsx("a",{href:`${k.explorerUrl}/tx/${L}`,target:"_blank",rel:"noopener noreferrer",className:"p-1 hover:bg-gray-200 dark:hover:bg-gray-700 rounded",children:y.jsx(a.ExternalLink,{className:"w-4 h-4"})})]})]})}),y.jsx("button",{onClick:V,className:"w-full bg-[#7042D2] text-white py-3 rounded-lg font-semibold hover:bg-[#7042D2]/90 transition-colors",children:"Close"})]},"success"),"error"===f&&y.jsxs(s.motion.div,{initial:{scale:.8,opacity:0},animate:{scale:1,opacity:1},className:"text-center space-y-6",children:[y.jsx("div",{className:"w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto",children:y.jsx(a.AlertCircle,{className:"w-8 h-8 text-red-500"})}),y.jsxs("div",{children:[y.jsx("h3",{className:"text-lg font-semibold text-red-600",children:"Payment Failed"}),y.jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-2",children:$||"Something went wrong. Please try again."})]}),y.jsxs("div",{className:"space-y-3",children:[y.jsx("button",{onClick:()=>{b("select-method"),U("")},className:"w-full bg-[#7042D2] text-white py-3 rounded-lg font-semibold hover:bg-[#7042D2]/90 transition-colors",children:"Try Again"}),y.jsx("button",{onClick:V,className:"w-full border border-gray-300 dark:border-gray-600 py-3 rounded-lg font-semibold hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors",children:"Close"})]})]},"error")]})}),y.jsx("div",{className:"px-6 py-4 border-t border-gray-200 dark:border-gray-700 text-center",children:y.jsxs("p",{className:"text-xs text-gray-500",children:["Powered by ",y.jsx("span",{className:"font-semibold text-[#7042D2]",children:"Coinley"})]})})]})}),y.jsx(r.WalletModal,{})]}):null},b=t.createContext(null),w=t.forwardRef(({customerEmail:e="",merchantName:s="",onSuccess:a,onError:r,onClose:n,theme:o="light",autoOpen:l=!1,testMode:c=!1,debug:i=!1,merchantWalletAddresses:d={}},m)=>{const h=t.useContext(b);if(!h)throw new Error("CoinleyCheckout must be used within a CoinleyProvider");const{openPayment:u,closePayment:x}=h,y=t=>{try{if(i&&console.log("Opening Coinley checkout with config:",t),!t.amount||t.amount<=0)throw new Error("Amount must be greater than 0");const s={...t,customerEmail:t.customerEmail||e,merchantWalletAddresses:{...d,...t.merchantWalletAddresses},metadata:{...t.metadata,testMode:c,checkoutVersion:"1.0.0"}};u(s,{onSuccess:a,onError:r,onClose:n})}catch(s){console.error("Failed to open Coinley checkout:",s),r&&r(s)}},p=()=>{x()};return t.useImperativeHandle(m,()=>({open:y,close:p})),null});w.displayName="CoinleyCheckout";class j{constructor(e,t,s){this.baseURL=e.endsWith("/")?e.slice(0,-1):e,this.apiKey=t,this.apiSecret=s}async request(e,t={}){const s=`${this.baseURL}${e}`,a={"Content-Type":"application/json","X-API-Key":this.apiKey,"X-API-Secret":this.apiSecret,...t.headers},r=await fetch(s,{...t,headers:a});if(!r.ok){const e=await r.json().catch(()=>({}));throw new Error(e.error||`HTTP ${r.status}`)}return r.json()}async getNetworks(){try{return await this.request("/api/networks")}catch(e){return console.error("Failed to fetch networks:",e),{networks:[{id:"1",name:"Ethereum",shortName:"ethereum",chainId:"0x1",type:"ethereum"},{id:"56",name:"BSC",shortName:"bsc",chainId:"0x38",type:"bsc"}]}}}async getTokens(){try{return await this.request("/api/networks/stablecoins")}catch(e){return console.error("Failed to fetch tokens:",e),{stablecoins:[{id:"1",name:"Tether USD",symbol:"USDT",contractAddress:"0xdAC17F958D2ee523a2206206994597C13D831ec7",decimals:6,networkId:"1",Network:{shortName:"ethereum",name:"Ethereum"}}]}}}async createPayment(e){return await this.request("/api/payments/create",{method:"POST",body:JSON.stringify(e)})}}class v{constructor(){this.account=null,this.chainId=null}async connect(){if(!window.ethereum)throw new Error("MetaMask not installed. Please install MetaMask extension.");try{const e=await window.ethereum.request({method:"eth_requestAccounts"}),t=await window.ethereum.request({method:"eth_chainId"});return this.account=e[0],this.chainId=t,console.log("✅ MetaMask connected:",this.account),{account:this.account,chainId:this.chainId}}catch(e){throw console.error("MetaMask connection failed:",e),new Error(e.message||"Failed to connect to MetaMask")}}async sendTransaction(e){if(!this.account)throw new Error("Wallet not connected");try{console.log("🦊 Sending MetaMask transaction:",e);const t=await window.ethereum.request({method:"eth_sendTransaction",params:[{...e,from:this.account}]});return console.log("✅ Transaction sent:",t),t}catch(t){throw console.error("Transaction failed:",t),4001===t.code?new Error("Transaction cancelled by user"):t.message.includes("insufficient funds")?new Error("Insufficient funds in wallet"):new Error(t.message||"Transaction failed")}}isConnected(){return!!this.account}}const N={formatAmount:(e,t=2)=>e.toFixed(t),truncateAddress:(e,t=6,s=4)=>e?e.length<=t+s?e:`${e.slice(0,t)}...${e.slice(-s)}`:"",isValidAddress:(e,t)=>{if(!e)return!1;switch(t.toLowerCase()){case"ethereum":case"bsc":case"polygon":return/^0x[a-fA-F0-9]{40}$/.test(e);case"tron":return/^T[a-zA-Z0-9]{33}$/.test(e);case"solana":return/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(e);default:return e.length>0}},copyToClipboard:async e=>{try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}};class k extends Error{constructor(e,t){super(e),this.name="CoinleyError",this.code=t}}e.CoinleyCheckout=w,e.CoinleyError=k,e.CoinleyPayment=f,e.CoinleyProvider=({apiKey:e,apiSecret:s,apiUrl:a,theme:r="light",debug:n=!1,children:o})=>{const[l,c]=t.useState(!1),[i,d]=t.useState(null),[m,h]=t.useState({}),[u,x]=t.useState(""),p=()=>{c(!1),d(null),m.onClose&&m.onClose()},g={openPayment:(e,t)=>{d(e),t&&h(t),c(!0)},closePayment:p};return y.jsxs(b.Provider,{value:g,children:[o,l&&i&&y.jsx(f,{apiKey:e,apiSecret:s,apiUrl:a,isOpen:l,config:i,theme:r,debug:n,merchantName:u,onSuccess:m.onSuccess,onError:m.onError,onClose:p})]})},e.DEFAULT_CONFIG={theme:"light",debug:!1,testMode:!1,autoOpen:!1},e.PaymentAPI=p,e.SimpleCoinleyPayment=({apiKey:e,apiSecret:s,apiUrl:a,config:r,onSuccess:n,onError:o,onClose:l,isOpen:c,theme:i="light"})=>{var d,m;const[h,u]=t.useState("method"),[x,p]=t.useState([]),[g,f]=t.useState([]),[b,w]=t.useState(null),[N,k]=t.useState(null),[C,S]=t.useState(null),[P,A]=t.useState(null),[T,E]=t.useState(!1),[D,M]=t.useState(""),[W,I]=t.useState(new v),[F,$]=t.useState(!1),[U,R]=t.useState(!1),q=t.useRef(new j(a,e,s));t.useEffect(()=>{c&&(_(),L())},[c]);const L=()=>{u("method"),w(null),k(null),S(null),A(null),M(""),$(!1),R(!1),I(new v)},_=async()=>{var e,t;try{E(!0),M(""),console.log("🔄 Loading networks and tokens...");const[s,a]=await Promise.all([q.current.getNetworks(),q.current.getTokens()]);p(s.networks||[]),f(a.stablecoins||[]),console.log("✅ Loaded networks:",null==(e=s.networks)?void 0:e.length),console.log("✅ Loaded tokens:",null==(t=a.stablecoins)?void 0:t.length)}catch(s){console.error("Failed to load data:",s),M("Failed to load payment options. Using fallback data.")}finally{E(!1)}};if(!c)return null;const O="dark"===i;return y.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:y.jsxs("div",{className:"rounded-lg shadow-xl max-w-md w-full mx-4 "+(O?"bg-gray-900 text-white":"bg-white text-gray-900"),children:[y.jsxs("div",{className:"p-4 border-b flex justify-between items-center "+(O?"border-gray-700":"border-gray-200"),children:[y.jsxs("div",{className:"text-center flex-1",children:[y.jsx("h2",{className:"text-lg font-semibold",children:"Pay with Crypto"}),r.amount&&y.jsxs("p",{className:"text-2xl font-bold text-purple-600",children:["$",r.amount.toFixed(2)]})]}),y.jsx("button",{onClick:l,className:"ml-4 text-gray-500 hover:text-gray-700 "+(O?"hover:text-gray-300":""),children:"✕"})]}),y.jsxs("div",{className:"p-4 min-h-[400px]",children:[D&&y.jsxs("div",{className:"mb-4 p-3 bg-red-100 text-red-700 rounded border border-red-200",children:[D,y.jsx("button",{onClick:()=>M(""),className:"ml-2 text-red-500 hover:text-red-700",children:"✕"})]}),"method"===h&&y.jsxs("div",{className:"space-y-4",children:[y.jsx("h3",{className:"font-medium text-center mb-6",children:"Choose Payment Method"}),y.jsxs("div",{className:"space-y-3",children:[y.jsxs("button",{onClick:()=>{S("wallet"),u("network")},className:"w-full p-4 border-2 rounded-lg hover:border-purple-500 text-left flex items-center space-x-3 transition-colors "+(O?"border-gray-600 hover:bg-gray-800":"border-gray-200 hover:bg-gray-50"),children:[y.jsx("span",{className:"text-2xl",children:"🦊"}),y.jsxs("div",{children:[y.jsx("div",{className:"font-medium",children:"MetaMask Wallet"}),y.jsx("div",{className:"text-sm "+(O?"text-gray-400":"text-gray-500"),children:"Connect and pay instantly"})]})]}),y.jsxs("button",{onClick:()=>{S("qr"),u("network")},className:"w-full p-4 border-2 rounded-lg hover:border-purple-500 text-left flex items-center space-x-3 transition-colors "+(O?"border-gray-600 hover:bg-gray-800":"border-gray-200 hover:bg-gray-50"),children:[y.jsx("span",{className:"text-2xl",children:"📱"}),y.jsxs("div",{children:[y.jsx("div",{className:"font-medium",children:"QR Code"}),y.jsx("div",{className:"text-sm "+(O?"text-gray-400":"text-gray-500"),children:"Scan with mobile wallet"})]})]})]})]}),"network"===h&&y.jsxs("div",{className:"space-y-4",children:[y.jsxs("div",{className:"flex items-center space-x-2",children:[y.jsx("button",{onClick:()=>u("method"),className:""+(O?"text-gray-400 hover:text-gray-200":"text-gray-500 hover:text-gray-700"),children:"←"}),y.jsx("h3",{className:"font-medium",children:"Select Network"})]}),y.jsx("div",{className:"space-y-2",children:x.map(e=>y.jsxs("button",{onClick:()=>{w(e),u("token")},className:"w-full p-3 border rounded-lg hover:border-purple-500 text-left transition-colors "+(O?"border-gray-600 hover:bg-gray-800":"border-gray-200 hover:bg-gray-50"),children:[y.jsx("div",{className:"font-medium",children:e.name}),y.jsx("div",{className:"text-sm "+(O?"text-gray-400":"text-gray-500"),children:e.shortName.toUpperCase()})]},e.id))})]}),"token"===h&&y.jsxs("div",{className:"space-y-4",children:[y.jsxs("div",{className:"flex items-center space-x-2",children:[y.jsx("button",{onClick:()=>u("network"),className:""+(O?"text-gray-400 hover:text-gray-200":"text-gray-500 hover:text-gray-700"),children:"←"}),y.jsxs("h3",{className:"font-medium",children:["Select Token on ",null==b?void 0:b.name]})]}),y.jsx("div",{className:"space-y-2",children:g.filter(e=>{var t;return(null==(t=e.Network)?void 0:t.shortName)===(null==b?void 0:b.shortName)}).map(e=>y.jsxs("button",{onClick:()=>{k(e),(async()=>{try{E(!0),M("");const e={amount:r.amount,currency:N.symbol,network:b.shortName,customerEmail:r.customerEmail,callbackUrl:r.callbackUrl,metadata:{...r.metadata,merchantWalletAddresses:r.merchantWalletAddresses,paymentMethod:C,selectedNetwork:b.shortName,selectedToken:N.symbol}};console.log("🔄 Creating payment:",e);const t=await q.current.createPayment(e);A(t.payment),console.log("✅ Payment created:",t.payment.id),u("wallet"===C?"wallet":"qr")}catch(e){console.error("Payment creation failed:",e),M(e.message)}finally{E(!1)}})()},disabled:T,className:"w-full p-3 border rounded-lg hover:border-purple-500 text-left flex justify-between transition-colors disabled:opacity-50 "+(O?"border-gray-600 hover:bg-gray-800":"border-gray-200 hover:bg-gray-50"),children:[y.jsxs("div",{children:[y.jsx("div",{className:"font-medium",children:e.name}),y.jsx("div",{className:"text-sm "+(O?"text-gray-400":"text-gray-500"),children:e.symbol})]}),e.isStablecoin&&y.jsx("span",{className:"px-2 py-1 bg-green-100 text-green-600 text-xs rounded",children:"Stablecoin"})]},e.id))})]}),"wallet"===h&&y.jsxs("div",{className:"space-y-4",children:[y.jsx("h3",{className:"font-medium text-center",children:"Connect & Pay"}),F?y.jsxs("div",{className:"space-y-4",children:[y.jsxs("div",{className:"p-3 bg-green-50 rounded-lg border border-green-200",children:[y.jsx("p",{className:"text-green-600 text-sm font-medium",children:"✅ Wallet Connected"}),y.jsxs("p",{className:"font-mono text-xs text-green-700 mt-1",children:[null==(d=W.account)?void 0:d.slice(0,6),"...",null==(m=W.account)?void 0:m.slice(-4)]})]}),y.jsxs("div",{className:"p-4 rounded-lg space-y-2 "+(O?"bg-gray-800":"bg-gray-50"),children:[y.jsxs("div",{className:"flex justify-between text-sm",children:[y.jsx("span",{children:"Amount:"}),y.jsxs("span",{className:"font-medium",children:[null==P?void 0:P.totalAmount," ",null==N?void 0:N.symbol]})]}),y.jsxs("div",{className:"flex justify-between text-sm",children:[y.jsx("span",{children:"Network:"}),y.jsx("span",{className:"font-medium",children:null==b?void 0:b.name})]}),y.jsxs("div",{className:"flex justify-between text-sm",children:[y.jsx("span",{children:"Token:"}),y.jsx("span",{className:"font-medium",children:null==N?void 0:N.name})]})]}),y.jsx("button",{onClick:async()=>{var e,t;try{R(!0),M("");const s=(null==(e=P.metadata)?void 0:e.recipientWallet)||(null==(t=r.merchantWalletAddresses)?void 0:t[b.shortName]);if(!s)throw new Error("Merchant wallet address not found");let a;if(console.log("🔄 Preparing transaction to:",s),N.contractAddress){const e=N.decimals||6,t=Math.floor(P.totalAmount*Math.pow(10,e)),r="0xa9059cbb",n=s.slice(2).toLowerCase().padStart(64,"0"),o=`${r}${n}${t.toString(16).padStart(64,"0")}`;a={to:N.contractAddress,data:o,value:"0x0"},console.log("🔄 ERC-20 Transaction:",{token:N.symbol,amount:P.totalAmount,amountWithDecimals:t,to:N.contractAddress,recipient:s})}else{a={to:s,value:`0x${Math.floor(P.totalAmount*Math.pow(10,18)).toString(16)}`},console.log("🔄 Native Transaction:",{amount:P.totalAmount,to:s})}const o=await W.sendTransaction(a);console.log("✅ Transaction successful:",o),u("success"),null==n||n(P.id,o,{network:b.name,token:N.symbol,amount:P.totalAmount,method:C})}catch(s){console.error("Transaction failed:",s),M(s.message)}finally{R(!1)}},disabled:U,className:"w-full bg-green-600 text-white py-3 px-4 rounded-lg hover:bg-green-700 disabled:opacity-50 font-medium flex items-center justify-center space-x-2",children:U?y.jsxs(y.Fragment,{children:[y.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-white"}),y.jsx("span",{children:"Sending Transaction..."})]}):y.jsxs("span",{children:["Send ",null==P?void 0:P.totalAmount," ",null==N?void 0:N.symbol]})})]}):y.jsxs("div",{className:"text-center space-y-4",children:[y.jsx("div",{className:"w-16 h-16 bg-purple-100 rounded-full flex items-center justify-center mx-auto",children:y.jsx("span",{className:"text-2xl",children:"🦊"})}),y.jsx("p",{className:""+(O?"text-gray-300":"text-gray-600"),children:"Connect MetaMask to continue"}),y.jsx("button",{onClick:async()=>{try{E(!0),M("");const e=await W.connect();$(!0),console.log("✅ Wallet connected successfully:",e.account)}catch(e){console.error("Wallet connection failed:",e),M(e.message)}finally{E(!1)}},disabled:T,className:"w-full bg-purple-600 text-white py-3 px-4 rounded-lg hover:bg-purple-700 disabled:opacity-50 font-medium",children:T?"Connecting...":"Connect MetaMask"})]})]}),"qr"===h&&y.jsxs("div",{className:"text-center space-y-4",children:[y.jsx("h3",{className:"font-medium",children:"Scan QR Code"}),y.jsxs("div",{className:"p-8 rounded-lg "+(O?"bg-gray-800":"bg-gray-100"),children:[y.jsx("p",{className:""+(O?"text-gray-400":"text-gray-500"),children:"QR Code will appear here"}),y.jsxs("p",{className:"text-xs mt-2",children:["Send ",null==P?void 0:P.totalAmount," ",null==N?void 0:N.symbol]}),y.jsx("p",{className:"text-xs",children:"to merchant wallet"})]}),y.jsx("p",{className:"text-xs "+(O?"text-gray-400":"text-gray-500"),children:"Waiting for payment confirmation..."})]}),"success"===h&&y.jsxs("div",{className:"text-center space-y-4",children:[y.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto",children:y.jsx("span",{className:"text-2xl",children:"✅"})}),y.jsx("h3",{className:"font-medium text-green-600",children:"Payment Successful!"}),y.jsx("p",{className:"text-sm "+(O?"text-gray-300":"text-gray-600"),children:"Your transaction has been sent successfully"}),y.jsx("button",{onClick:l,className:"w-full bg-purple-600 text-white py-3 px-4 rounded-lg hover:bg-purple-700 font-medium",children:"Close"})]}),T&&"wallet"!==h&&y.jsx("div",{className:"flex items-center justify-center py-8",children:y.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600"})})]})]})})},e.SimpleCoinleyProvider=({children:e,...t})=>e,e.ThemeProvider=({initialTheme:e="light",children:s})=>{const[a,r]=t.useState(e);return t.useEffect(()=>{document.documentElement.setAttribute("data-coinley-theme",a)},[a]),y.jsx("div",{className:`coinley-theme-${a}`,children:s})},e.VERSION="0.0.1",e.useCoinley=()=>{const e=t.useContext(b);if(!e)throw new Error("useCoinley must be used within a CoinleyProvider");return e},e.utils=N,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react"),require("framer-motion"),require("lucide-react"),require("@coinley/wallet-connect-core"),require("axios")):"function"==typeof define&&define.amd?define(["exports","react","framer-motion","lucide-react","@coinley/wallet-connect-core","axios"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).CoinleyTest={},e.React,e.FramerMotion,e.LucideReact,e.CoinleyWalletCore,e.axios)}(this,function(e,t,s,a,n,r){"use strict";var o={exports:{}},l={},c=t,i=Symbol.for("react.element"),d=Symbol.for("react.fragment"),m=Object.prototype.hasOwnProperty,h=c.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,u={key:!0,ref:!0,__self:!0,__source:!0};function x(e,t,s){var a,n={},r=null,o=null;for(a in void 0!==s&&(r=""+s),void 0!==t.key&&(r=""+t.key),void 0!==t.ref&&(o=t.ref),t)m.call(t,a)&&!u.hasOwnProperty(a)&&(n[a]=t[a]);if(e&&e.defaultProps)for(a in t=e.defaultProps)void 0===n[a]&&(n[a]=t[a]);return{$$typeof:i,type:e,key:r,ref:o,props:n,_owner:h.current}}l.Fragment=d,l.jsx=x,l.jsxs=x,o.exports=l;var p=o.exports;class y{constructor(e,t,s){this.apiKey=t,this.apiSecret=s,this.api=r.create({baseURL:e.endsWith("/")?e.slice(0,-1):e,timeout:3e4,headers:{"Content-Type":"application/json"}}),this.api.interceptors.request.use(e=>{var t;e.headers["X-API-Key"]=this.apiKey,e.headers["X-API-Secret"]=this.apiSecret;const s=this.generateMerchantToken();return s&&(e.headers.Authorization=`Bearer ${s}`),console.log("API Request:",{method:null==(t=e.method)?void 0:t.toUpperCase(),url:e.url,data:e.data}),e},e=>(console.error("Request interceptor error:",e),Promise.reject(e))),this.api.interceptors.response.use(e=>(console.log("API Response:",{status:e.status,url:e.config.url,data:e.data}),e),e=>{var t,s,a,n,r;if(console.error("API Error:",{status:null==(t=e.response)?void 0:t.status,data:null==(s=e.response)?void 0:s.data,message:e.message}),401===(null==(a=e.response)?void 0:a.status))throw new Error("Authentication failed. Please check your API credentials.");if(404===(null==(n=e.response)?void 0:n.status))throw new Error("API endpoint not found. Please check your API URL.");if((null==(r=e.response)?void 0:r.status)>=500)throw new Error("Server error. Please try again later.");throw e})}generateMerchantToken(){try{const e=`${this.apiKey}:${this.apiSecret}`;return btoa(e)}catch(e){return console.error("Failed to generate token:",e),null}}async createPayment(e){var t,s;try{return(await this.api.post("/api/payments/create",e)).data}catch(a){if(null==(s=null==(t=a.response)?void 0:t.data)?void 0:s.error)throw new Error(a.response.data.error);throw new Error(a.message||"Failed to create payment")}}async getPayment(e){var t,s;try{return(await this.api.get(`/api/payments/${e}`)).data}catch(a){if(null==(s=null==(t=a.response)?void 0:t.data)?void 0:s.error)throw new Error(a.response.data.error);throw new Error(a.message||"Failed to get payment details")}}async getNetworks(){try{return(await this.api.get("/api/networks")).data}catch(e){return console.error("Get networks failed:",e),{networks:[{id:"ethereum",name:"Ethereum",shortName:"ethereum",chainId:"1",type:"ethereum",explorerUrl:"https://etherscan.io",isTestnet:!1},{id:"bsc",name:"Binance Smart Chain",shortName:"bsc",chainId:"56",type:"bsc",explorerUrl:"https://bscscan.com",isTestnet:!1},{id:"polygon",name:"Polygon",shortName:"polygon",chainId:"137",type:"ethereum",explorerUrl:"https://polygonscan.com",isTestnet:!1}]}}}async getStablecoins(){try{return(await this.api.get("/api/networks/stablecoins")).data}catch(e){return console.error("Get stablecoins failed:",e),{stablecoins:[{id:"usdt-eth",name:"Tether USD",symbol:"USDT",contractAddress:"0xdAC17F958D2ee523a2206206994597C13D831ec7",decimals:6,isStablecoin:!0,networkId:"ethereum",Network:{id:"ethereum",name:"Ethereum",shortName:"ethereum",type:"ethereum"}},{id:"usdc-eth",name:"USD Coin",symbol:"USDC",contractAddress:"0xA0b86a33E6441d81d0B93bF9EE0f74ca32F7e6f6",decimals:6,isStablecoin:!0,networkId:"ethereum",Network:{id:"ethereum",name:"Ethereum",shortName:"ethereum",type:"ethereum"}}]}}}async verifyQRPayment(e){var t,s;try{return(await this.api.post("/api/payments/verify-qr",{paymentId:e})).data}catch(a){if(null==(s=null==(t=a.response)?void 0:t.data)?void 0:s.error)throw new Error(a.response.data.error);throw new Error(a.message||"Failed to verify payment")}}async processPayment(e,t,s,a){var n,r;try{return(await this.api.post("/api/payments/process",{paymentId:e,transactionHash:t,network:s,senderAddress:a})).data}catch(o){if(null==(r=null==(n=o.response)?void 0:n.data)?void 0:r.error)throw new Error(o.response.data.error);throw new Error(o.message||"Failed to process payment")}}async healthCheck(){try{return 200===(await this.api.get("/api/health")).status}catch(e){return console.error("Health check failed:",e),!1}}}const g=({selectedNetwork:e,selectedToken:t,paymentData:s,config:r,onTransactionSent:o,onError:l,isConnecting:c,setIsConnecting:i})=>{const{isConnected:d,address:m,disconnect:h}=n.useWallet(),{connectWallet:u,isPending:x}=n.useWalletConnect(),{detectedWallets:y,hasWallets:g,walletCount:f}=n.useWalletDetection(),{sendTransaction:w}=n.useWalletTransaction(),{openModal:b}=n.useWalletModal();y.filter(e=>e.name.toLowerCase().includes("metamask")||"injected"===e.provider||e.name.toLowerCase().includes("coinbase")||e.name.toLowerCase().includes("wallet connect"));const j=async e=>{try{if(i(!0),d&&(await h(),await new Promise(e=>setTimeout(e,1e3))),"metamask"===e&&window.ethereum&&window.ethereum.isMetaMask)try{await window.ethereum.request({method:"eth_requestAccounts"}),console.log("✅ Connected directly to MetaMask")}catch(t){throw console.error("MetaMask connection failed:",t),t}else await u(e)}catch(t){console.error("Wallet connection failed:",t),l(t.message||"Failed to connect wallet")}finally{i(!1)}};return p.jsx("div",{className:"text-center space-y-6",children:p.jsxs("div",{className:"space-y-4",children:[p.jsx("div",{className:"w-16 h-16 bg-[#7042D2] bg-opacity-20 rounded-full flex items-center justify-center mx-auto",children:p.jsx(a.Wallet,{className:"w-8 h-8 text-[#7042D2]"})}),d?p.jsxs(p.Fragment,{children:[p.jsx("h3",{className:"text-lg font-semibold text-green-600",children:"Wallet Connected ✅"}),p.jsxs("div",{className:"bg-gray-50 dark:bg-gray-800 rounded-lg p-4 space-y-3",children:[p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Address:"}),p.jsxs("div",{className:"flex items-center space-x-2",children:[p.jsxs("span",{className:"font-mono text-sm",children:[null==m?void 0:m.slice(0,6),"...",null==m?void 0:m.slice(-4)]}),p.jsx("button",{onClick:async()=>{try{await h()}catch(e){console.error("Disconnect error:",e)}},className:"text-xs text-red-600 hover:text-red-800",children:"Disconnect"})]})]}),s&&p.jsxs(p.Fragment,{children:[p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Amount:"}),p.jsxs("span",{className:"font-medium",children:[s.totalAmount," ",null==t?void 0:t.symbol]})]}),p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Network:"}),p.jsx("span",{className:"font-medium",children:null==e?void 0:e.name})]})]})]}),p.jsx("button",{onClick:async()=>{var a;if(d&&s&&t)try{i(!0),console.log("🔍 Transaction Debug:"),console.log("Connected wallet address:",m),console.log("Payment data:",s),console.log("Selected token:",t),console.log("Selected network:",e);let n,r=null==(a=s.metadata)?void 0:a.recipientWallet;if(console.log("Merchant recipient address:",r),!r||"string"!=typeof r)throw new Error("Merchant wallet address not found in payment data");if(!r.match(/^0x[a-fA-F0-9]{40}$/))throw new Error(`Invalid merchant address format: ${r}`);if(t.contractAddress){console.log("🔍 ERC-20 Transaction Details:"),console.log("Token contract:",t.contractAddress),console.log("Token decimals:",t.decimals),console.log("Payment amount:",s.totalAmount);const e=t.decimals||6,a=Math.floor(s.totalAmount*Math.pow(10,e));console.log("Calculated amount (with decimals):",a);const o="0xa9059cbb",l=r.slice(2).toLowerCase().padStart(64,"0"),c=a.toString(16).padStart(64,"0"),i=`${o}${l}${c}`;console.log("🔍 Transaction Data:"),console.log("Method ID:",o),console.log("Recipient (padded):",l),console.log("Amount (padded):",c),console.log("Full data:",i);const d={to:t.contractAddress,data:i,value:"0x0"};console.log("📤 Sending ERC-20 transaction:",d),n=await w(d)}else{const e=Math.floor(s.totalAmount*Math.pow(10,18)),t={to:r,value:`0x${e.toString(16)}`};console.log("📤 Sending native transaction:",t),n=await w(t)}n&&(console.log("✅ Transaction sent successfully:",n),o(n))}catch(n){console.error("❌ Transaction failed:",n),l(n.message||"Transaction failed")}finally{i(!1)}else l("Wallet not connected or payment data missing")},disabled:c,className:"w-full bg-[#7042D2] text-white py-4 rounded-lg font-semibold hover:bg-[#7042D2]/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center space-x-2",children:c?p.jsxs(p.Fragment,{children:[p.jsx(a.Loader2,{className:"w-5 h-5 animate-spin"}),p.jsx("span",{children:"Processing Payment..."})]}):p.jsxs(p.Fragment,{children:[p.jsx(a.Zap,{className:"w-5 h-5"}),p.jsx("span",{children:"Send Payment"})]})}),p.jsxs("p",{className:"text-xs text-gray-500",children:["Make sure you have enough ",null==t?void 0:t.symbol," and ETH for gas fees"]})]}):p.jsxs(p.Fragment,{children:[p.jsx("h3",{className:"text-lg font-semibold",children:"Connect Your Wallet"}),p.jsx("p",{className:"text-gray-600 dark:text-gray-400 text-sm",children:"Choose your preferred wallet to complete the payment"}),p.jsxs("div",{className:"space-y-3",children:[p.jsxs("button",{onClick:()=>j("metamask"),disabled:x||c,className:"w-full p-3 border border-gray-300 rounded-lg hover:border-[#7042D2] flex items-center space-x-3 transition-colors disabled:opacity-50",children:[p.jsx("span",{className:"text-xl",children:"🦊"}),p.jsxs("div",{className:"text-left flex-1",children:[p.jsx("div",{className:"font-medium",children:"MetaMask"}),p.jsx("div",{className:"text-xs text-gray-500",children:"Connect with MetaMask"})]})]}),p.jsxs("button",{onClick:()=>{try{console.log("Attempting to open wallet modal..."),b()}catch(e){console.error("Failed to open modal:",e),j("injected")}},disabled:x||c,className:"w-full p-3 border border-gray-300 rounded-lg hover:border-[#7042D2] flex items-center space-x-3 transition-colors disabled:opacity-50",children:[p.jsx("span",{className:"text-xl",children:"💼"}),p.jsxs("div",{className:"text-left flex-1",children:[p.jsx("div",{className:"font-medium",children:"Other Wallets"}),p.jsx("div",{className:"text-xs text-gray-500",children:"Choose from available wallets"})]})]}),p.jsx("button",{onClick:()=>j("injected"),disabled:x||c,className:"w-full p-2 text-sm border border-dashed border-gray-300 rounded-lg hover:border-[#7042D2] transition-colors disabled:opacity-50",children:"Try Direct Connection"})]}),c&&p.jsxs("div",{className:"flex items-center justify-center space-x-2 text-gray-600",children:[p.jsx(a.Loader2,{className:"w-4 h-4 animate-spin"}),p.jsx("span",{children:"Connecting..."})]})]})]})})},f=({apiKey:e,apiSecret:r,apiUrl:o="http://localhost:9000",onSuccess:l,onError:c,onClose:i,isOpen:d,config:m,theme:h="light",merchantName:u,debug:x=!1})=>{const[f,w]=t.useState("select-method"),[b,j]=t.useState([]),[v,N]=t.useState([]),[k,C]=t.useState(null),[S,M]=t.useState(null),[P,E]=t.useState(null),[T,A]=t.useState(""),[D,I]=t.useState(null),[W,$]=t.useState(!1),[F,L]=t.useState(""),[U,R]=t.useState(!1),[q,H]=t.useState(""),[O,_]=t.useState(!1),B=t.useRef(new y(o,e,r)),Q=n.createCoinleyWalletConfig({appName:u||"Coinley Payment",appDescription:"Crypto payment processing",chains:[{id:1,name:"Ethereum",network:"ethereum",rpcUrls:{default:{http:["https://eth.llamarpc.com"]}},nativeCurrency:{name:"Ethereum",symbol:"ETH",decimals:18}},{id:56,name:"BNB Smart Chain",network:"bsc",rpcUrls:{default:{http:["https://bsc-dataseed1.binance.org"]}},nativeCurrency:{name:"BNB",symbol:"BNB",decimals:18}}]});t.useEffect(()=>{d&&K()},[d]);const K=async()=>{try{$(!0),L("");const[e,t]=await Promise.all([B.current.getNetworks(),B.current.getStablecoins()]);j(e.networks||[]),N(t.stablecoins||[]),x&&(console.log("Initialized networks:",e.networks),console.log("Initialized tokens:",t.stablecoins))}catch(e){console.error("Failed to initialize payment:",e),L("Failed to load payment options. Please try again.")}finally{$(!1)}},G=e=>{E(e),w("select-network")},V=async(e,t)=>{try{$(!0);const s={amount:m.amount,currency:t.symbol,network:e.shortName,customerEmail:m.customerEmail,callbackUrl:m.callbackUrl,metadata:{...m.metadata,paymentMethod:P,selectedNetwork:e.shortName,selectedToken:t.symbol,merchantWalletAddresses:m.merchantWalletAddresses}};console.log("🔍 Payment payload with merchant wallets:",s);const a=await B.current.createPayment(s);I(a.payment),"wallet"===P?w("wallet-connect"):(await Y(a.payment),w("qr-code"))}catch(s){console.error("Payment initiation failed:",s),L(s.message||"Failed to create payment"),w("error")}finally{$(!1)}},Y=async e=>{var t,s;try{const a=(null==(t=e.metadata)?void 0:t.recipientWallet)||(null==(s=m.merchantWalletAddresses)?void 0:s[(null==k?void 0:k.shortName)||""]);if(!a)throw new Error("Recipient wallet address not found");let n="";n="ethereum"===(null==k?void 0:k.type)||"bsc"===(null==k?void 0:k.type)?(null==S?void 0:S.contractAddress)?`ethereum:${S.contractAddress}/transfer?address=${a}&uint256=${e.totalAmount*Math.pow(10,S.decimals)}`:`ethereum:${a}?value=${e.totalAmount}e18`:"tron"===(null==k?void 0:k.type)?`tron:${a}?amount=${e.totalAmount}`:`${null==S?void 0:S.symbol}:${a}?amount=${e.totalAmount}`,A(a),z(e.id)}catch(a){console.error("QR code generation failed:",a),L("Failed to generate QR code"),w("error")}},z=async e=>{let t=0;const s=async()=>{var a;try{const n=await B.current.verifyQRPayment(e);return n.verified&&(null==(a=n.payment)?void 0:a.transactionHash)?(H(n.payment.transactionHash),await X(e,n.payment.transactionHash),!0):(t++,t<60?setTimeout(s,5e3):(L("Payment verification timeout. Please check your transaction."),w("error")),!1)}catch(n){return console.error("Payment verification error:",n),t++,t<60?setTimeout(s,5e3):(L("Payment verification failed"),w("error")),!1}};setTimeout(s,2e3)},X=async(e,t)=>{w("success"),l&&l(e,t,{network:null==k?void 0:k.name,token:null==S?void 0:S.symbol,amount:null==D?void 0:D.totalAmount,method:P})},Z=()=>{w("select-method"),E(null),C(null),M(null),A(""),I(null),L(""),H(""),i&&i()};return d?p.jsxs(n.CoinleyWalletProvider,{config:Q,walletConfig:{appName:u||"Coinley Payment"},children:[p.jsx("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black bg-opacity-50 backdrop-blur-sm",children:p.jsxs(s.motion.div,{initial:{scale:.9,opacity:0},animate:{scale:1,opacity:1},exit:{scale:.9,opacity:0},className:"relative w-full max-w-md mx-4 rounded-2xl shadow-2xl overflow-hidden "+("dark"===h?"bg-gray-900 text-white":"bg-white text-gray-900"),children:[p.jsxs("div",{className:"relative p-6 border-b border-gray-200 dark:border-gray-700",children:["select-method"!==f&&"success"!==f&&"error"!==f&&p.jsx("button",{onClick:()=>{if("select-network"===f)w("select-method");else if("select-token"===f)w("select-network");else if("wallet-connect"===f||"qr-code"===f){v.filter(e=>{var t;return(null==(t=e.Network)?void 0:t.shortName)===(null==k?void 0:k.shortName)||e.networkId===(null==k?void 0:k.id)}).length>1?w("select-token"):w("select-network")}},className:"absolute left-4 top-6 p-1 rounded-full hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors",children:p.jsx(a.ArrowLeft,{className:"w-5 h-5"})}),p.jsx("button",{onClick:Z,className:"absolute right-4 top-6 p-1 rounded-full hover:bg-gray-100 dark:hover:bg-gray-800 transition-colors",children:p.jsx(a.X,{className:"w-5 h-5"})}),p.jsxs("div",{className:"text-center",children:[p.jsxs("div",{className:"flex items-center justify-center space-x-2 mb-2",children:[p.jsx(a.Sparkles,{className:"w-5 h-5 text-[#7042D2]"}),p.jsx("h2",{className:"text-xl font-bold",children:"Pay with Crypto"}),p.jsx(a.Sparkles,{className:"w-5 h-5 text-[#7042D2]"})]}),u&&p.jsx("p",{className:"text-sm text-gray-600 dark:text-gray-400 mt-1",children:u}),p.jsx("div",{className:"mt-2",children:p.jsxs("span",{className:"text-2xl font-bold text-[#7042D2]",children:["$",m.amount.toFixed(2)]})})]})]}),p.jsx("div",{className:"p-6 min-h-[400px]",children:p.jsxs(s.AnimatePresence,{mode:"wait",children:["select-method"===f&&p.jsxs(s.motion.div,{initial:{x:20,opacity:0},animate:{x:0,opacity:1},exit:{x:-20,opacity:0},className:"space-y-4",children:[p.jsx("h3",{className:"text-lg font-semibold text-center mb-6",children:"Choose Payment Method"}),p.jsx(s.motion.button,{whileHover:{scale:1.02},whileTap:{scale:.98},onClick:()=>G("wallet"),className:"w-full p-4 border-2 border-gray-200 dark:border-gray-700 rounded-xl hover:border-[#7042D2] transition-colors group",children:p.jsxs("div",{className:"flex items-center space-x-4",children:[p.jsx("div",{className:"p-3 bg-[#7042D2] bg-opacity-10 rounded-lg group-hover:bg-opacity-20 transition-colors",children:p.jsx(a.Wallet,{className:"w-6 h-6 text-[#7042D2]"})}),p.jsxs("div",{className:"text-left",children:[p.jsx("div",{className:"font-semibold",children:"Connect Wallet"}),p.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-400",children:"MetaMask, WalletConnect & more"})]}),p.jsx(a.Zap,{className:"w-5 h-5 text-[#7042D2] ml-auto"})]})}),p.jsx(s.motion.button,{whileHover:{scale:1.02},whileTap:{scale:.98},onClick:()=>G("qr"),className:"w-full p-4 border-2 border-gray-200 dark:border-gray-700 rounded-xl hover:border-[#7042D2] transition-colors group",children:p.jsxs("div",{className:"flex items-center space-x-4",children:[p.jsx("div",{className:"p-3 bg-[#7042D2] bg-opacity-10 rounded-lg group-hover:bg-opacity-20 transition-colors",children:p.jsx(a.QrCode,{className:"w-6 h-6 text-[#7042D2]"})}),p.jsxs("div",{className:"text-left",children:[p.jsx("div",{className:"font-semibold",children:"QR Code"}),p.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Scan with mobile wallet"})]})]})})]},"select-method"),"select-network"===f&&p.jsxs(s.motion.div,{initial:{x:20,opacity:0},animate:{x:0,opacity:1},exit:{x:-20,opacity:0},className:"space-y-4",children:[p.jsx("h3",{className:"text-lg font-semibold text-center mb-6",children:"Select Network"}),W?p.jsx("div",{className:"flex justify-center py-8",children:p.jsx(a.Loader2,{className:"w-8 h-8 animate-spin text-[#7042D2]"})}):p.jsx("div",{className:"space-y-3",children:b.map(e=>p.jsx(s.motion.button,{whileHover:{scale:1.02},whileTap:{scale:.98},onClick:()=>(async e=>{C(e);const t=v.filter(t=>{var s;return(null==(s=t.Network)?void 0:s.shortName)===e.shortName||t.networkId===e.id});if(t.length>1)w("select-token");else if(1===t.length){const s=t[0];M(s),await V(e,s)}else L(`No supported tokens found for ${e.name}`),w("error")})(e),className:"w-full p-4 border-2 border-gray-200 dark:border-gray-700 rounded-xl hover:border-[#7042D2] transition-colors group",children:p.jsxs("div",{className:"flex items-center space-x-4",children:[e.logo?p.jsx("img",{src:e.logo,alt:e.name,className:"w-8 h-8 rounded-full"}):p.jsx("div",{className:"w-8 h-8 bg-[#7042D2] bg-opacity-20 rounded-full flex items-center justify-center",children:p.jsx("span",{className:"text-sm font-bold text-[#7042D2]",children:e.shortName.charAt(0).toUpperCase()})}),p.jsxs("div",{className:"text-left flex-1",children:[p.jsx("div",{className:"font-semibold",children:e.name}),p.jsx("div",{className:"text-sm text-gray-600 dark:text-gray-400",children:e.shortName.toUpperCase()})]}),p.jsx(a.ChevronDown,{className:"w-5 h-5 text-gray-400 transform -rotate-90"})]})},e.id))})]},"select-network"),"select-token"===f&&p.jsxs(s.motion.div,{initial:{x:20,opacity:0},animate:{x:0,opacity:1},exit:{x:-20,opacity:0},className:"space-y-4",children:[p.jsxs("h3",{className:"text-lg font-semibold text-center mb-6",children:["Select Token on ",null==k?void 0:k.name]}),W?p.jsx("div",{className:"flex justify-center py-8",children:p.jsx(a.Loader2,{className:"w-8 h-8 animate-spin text-[#7042D2]"})}):p.jsx("div",{className:"space-y-3",children:v.filter(e=>{var t;return(null==(t=e.Network)?void 0:t.shortName)===(null==k?void 0:k.shortName)||e.networkId===(null==k?void 0:k.id)}).map(e=>p.jsx(s.motion.button,{whileHover:{scale:1.02},whileTap:{scale:.98},onClick:()=>(async e=>{M(e),await V(k,e)})(e),className:"w-full p-4 border-2 border-gray-200 dark:border-gray-700 rounded-xl hover:border-[#7042D2] transition-colors group",children:p.jsxs("div",{className:"flex items-center space-x-4",children:[e.logo?p.jsx("img",{src:e.logo,alt:e.symbol,className:"w-8 h-8 rounded-full"}):p.jsx("div",{className:"w-8 h-8 bg-[#7042D2] bg-opacity-20 rounded-full flex items-center justify-center",children:p.jsx("span",{className:"text-sm font-bold text-[#7042D2]",children:e.symbol.charAt(0)})}),p.jsxs("div",{className:"text-left flex-1",children:[p.jsx("div",{className:"font-semibold",children:e.name}),p.jsxs("div",{className:"text-sm text-gray-600 dark:text-gray-400",children:[e.symbol,e.isStablecoin&&p.jsx("span",{className:"ml-2 px-2 py-0.5 bg-green-100 text-green-600 text-xs rounded-full",children:"Stablecoin"})]})]}),p.jsx(a.ChevronDown,{className:"w-5 h-5 text-gray-400 transform -rotate-90"})]})},e.id))})]},"select-token"),"wallet-connect"===f&&p.jsx(s.motion.div,{initial:{x:20,opacity:0},animate:{x:0,opacity:1},exit:{x:-20,opacity:0},children:p.jsx(g,{selectedNetwork:k,selectedToken:S,paymentData:D,config:m,onTransactionSent:async e=>{H(e),w("processing");try{await B.current.processPayment(D.id,e,(null==k?void 0:k.shortName)||"",""),await X(D.id,e)}catch(t){console.error("Payment processing failed:",t),await X(D.id,e)}},onError:L,isConnecting:O,setIsConnecting:_})},"wallet-connect"),"qr-code"===f&&p.jsxs(s.motion.div,{initial:{x:20,opacity:0},animate:{x:0,opacity:1},exit:{x:-20,opacity:0},className:"text-center space-y-6",children:[p.jsxs("div",{className:"space-y-4",children:[p.jsx("h3",{className:"text-lg font-semibold",children:"Scan QR Code"}),p.jsx("p",{className:"text-gray-600 dark:text-gray-400",children:"Use your mobile wallet to scan and pay"})]}),T&&p.jsx("div",{className:"bg-white p-4 rounded-xl mx-auto inline-block",children:p.jsxs("div",{className:"w-48 h-48 flex items-center justify-center text-gray-500",children:["QR Code: ",T.slice(0,10),"...",T.slice(-4)]})}),D&&p.jsxs("div",{className:"space-y-3",children:[p.jsxs("div",{className:"bg-gray-50 dark:bg-gray-800 rounded-lg p-4 space-y-2",children:[p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Network:"}),p.jsx("span",{className:"font-medium",children:null==k?void 0:k.name})]}),p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Amount:"}),p.jsxs("span",{className:"font-medium",children:[D.totalAmount," ",null==S?void 0:S.symbol]})]})]}),p.jsxs("div",{className:"flex items-center justify-center space-x-2 text-sm text-gray-600 dark:text-gray-400",children:[p.jsx(a.Loader2,{className:"w-4 h-4 animate-spin"}),p.jsx("span",{children:"Waiting for payment..."})]})]})]},"qr-code"),"processing"===f&&p.jsxs(s.motion.div,{initial:{scale:.8,opacity:0},animate:{scale:1,opacity:1},className:"text-center space-y-6",children:[p.jsx("div",{className:"w-16 h-16 bg-[#7042D2] bg-opacity-20 rounded-full flex items-center justify-center mx-auto",children:p.jsx(a.Loader2,{className:"w-8 h-8 animate-spin text-[#7042D2]"})}),p.jsxs("div",{children:[p.jsx("h3",{className:"text-lg font-semibold text-[#7042D2]",children:"Processing Payment..."}),p.jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-2",children:"Your transaction is being processed"})]})]},"processing"),"success"===f&&p.jsxs(s.motion.div,{initial:{scale:.8,opacity:0},animate:{scale:1,opacity:1},className:"text-center space-y-6",children:[p.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto",children:p.jsx(a.CheckCircle2,{className:"w-8 h-8 text-green-500"})}),p.jsxs("div",{children:[p.jsx("h3",{className:"text-lg font-semibold text-green-600",children:"Payment Successful!"}),p.jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-2",children:"Your payment has been processed successfully"})]}),q&&p.jsx("div",{className:"bg-gray-50 dark:bg-gray-800 rounded-lg p-4",children:p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-sm text-gray-600 dark:text-gray-400",children:"Transaction:"}),p.jsxs("div",{className:"flex items-center space-x-2",children:[p.jsxs("span",{className:"font-mono text-sm",children:[q.slice(0,6),"...",q.slice(-4)]}),p.jsx("button",{onClick:()=>(async e=>{try{await navigator.clipboard.writeText(e),R(!0),setTimeout(()=>R(!1),2e3)}catch(t){console.error("Failed to copy:",t)}})(q),className:"p-1 hover:bg-gray-200 dark:hover:bg-gray-700 rounded",children:p.jsx(a.Copy,{className:"w-4 h-4"})}),(null==k?void 0:k.explorerUrl)&&p.jsx("a",{href:`${k.explorerUrl}/tx/${q}`,target:"_blank",rel:"noopener noreferrer",className:"p-1 hover:bg-gray-200 dark:hover:bg-gray-700 rounded",children:p.jsx(a.ExternalLink,{className:"w-4 h-4"})})]})]})}),p.jsx("button",{onClick:Z,className:"w-full bg-[#7042D2] text-white py-3 rounded-lg font-semibold hover:bg-[#7042D2]/90 transition-colors",children:"Close"})]},"success"),"error"===f&&p.jsxs(s.motion.div,{initial:{scale:.8,opacity:0},animate:{scale:1,opacity:1},className:"text-center space-y-6",children:[p.jsx("div",{className:"w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto",children:p.jsx(a.AlertCircle,{className:"w-8 h-8 text-red-500"})}),p.jsxs("div",{children:[p.jsx("h3",{className:"text-lg font-semibold text-red-600",children:"Payment Failed"}),p.jsx("p",{className:"text-gray-600 dark:text-gray-400 mt-2",children:F||"Something went wrong. Please try again."})]}),p.jsxs("div",{className:"space-y-3",children:[p.jsx("button",{onClick:()=>{w("select-method"),L("")},className:"w-full bg-[#7042D2] text-white py-3 rounded-lg font-semibold hover:bg-[#7042D2]/90 transition-colors",children:"Try Again"}),p.jsx("button",{onClick:Z,className:"w-full border border-gray-300 dark:border-gray-600 py-3 rounded-lg font-semibold hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors",children:"Close"})]})]},"error")]})}),p.jsx("div",{className:"px-6 py-4 border-t border-gray-200 dark:border-gray-700 text-center",children:p.jsxs("p",{className:"text-xs text-gray-500",children:["Powered by ",p.jsx("span",{className:"font-semibold text-[#7042D2]",children:"Coinley"})]})})]})}),p.jsx(n.WalletModal,{})]}):null},w=t.createContext(null),b=t.forwardRef(({customerEmail:e="",merchantName:s="",onSuccess:a,onError:n,onClose:r,theme:o="light",autoOpen:l=!1,testMode:c=!1,debug:i=!1,merchantWalletAddresses:d={}},m)=>{const h=t.useContext(w);if(!h)throw new Error("CoinleyCheckout must be used within a CoinleyProvider");const{openPayment:u,closePayment:x}=h,p=t=>{try{if(i&&console.log("Opening Coinley checkout with config:",t),!t.amount||t.amount<=0)throw new Error("Amount must be greater than 0");const s={...t,customerEmail:t.customerEmail||e,merchantWalletAddresses:{...d,...t.merchantWalletAddresses},metadata:{...t.metadata,testMode:c,checkoutVersion:"1.0.0"}};u(s,{onSuccess:a,onError:n,onClose:r})}catch(s){console.error("Failed to open Coinley checkout:",s),n&&n(s)}},y=()=>{x()};return t.useImperativeHandle(m,()=>({open:p,close:y})),null});b.displayName="CoinleyCheckout";let j=class{constructor(e,t,s){this.baseURL=e.endsWith("/")?e.slice(0,-1):e,this.apiKey=t,this.apiSecret=s}async request(e,t={}){const s=`${this.baseURL}${e}`,a={"Content-Type":"application/json","X-API-Key":this.apiKey,"X-API-Secret":this.apiSecret,...t.headers},n=await fetch(s,{...t,headers:a});if(!n.ok){const e=await n.json().catch(()=>({}));throw new Error(e.error||`HTTP ${n.status}`)}return n.json()}async getNetworks(){try{return await this.request("/api/networks")}catch(e){return console.error("Failed to fetch networks:",e),{networks:[{id:"1",name:"Ethereum",shortName:"ethereum",chainId:"0x1",type:"ethereum"},{id:"56",name:"BSC",shortName:"bsc",chainId:"0x38",type:"bsc"}]}}}async getTokens(){try{return await this.request("/api/networks/stablecoins")}catch(e){return console.error("Failed to fetch tokens:",e),{stablecoins:[{id:"1",name:"Tether USD",symbol:"USDT",contractAddress:"0xdAC17F958D2ee523a2206206994597C13D831ec7",decimals:6,networkId:"1",Network:{shortName:"ethereum",name:"Ethereum"}}]}}}async createPayment(e){return await this.request("/api/payments/create",{method:"POST",body:JSON.stringify(e)})}},v=class{constructor(){this.account=null,this.chainId=null}async connect(){if(!window.ethereum)throw new Error("MetaMask not installed. Please install MetaMask extension.");if(window.ethereum.providers){console.log("🔍 Multiple wallets detected:",window.ethereum.providers.length);const e=window.ethereum.providers.find(e=>e.isMetaMask);if(!e)throw new Error("MetaMask not found among installed wallets");console.log("🦊 Using MetaMask provider specifically"),window.ethereum=e}else if(!window.ethereum.isMetaMask)throw new Error("Please use MetaMask wallet");try{console.log("🦊 Requesting MetaMask account access...");const e=await window.ethereum.request({method:"eth_requestAccounts"});if(!e||0===e.length)throw new Error("No accounts found in MetaMask");const t=await window.ethereum.request({method:"eth_chainId"});if(this.account=e[0],this.chainId=t,console.log("✅ MetaMask connected successfully:"),console.log(" Account:",this.account),console.log(" Chain ID:",this.chainId),"0xa0419a048a1469b34a5245f08c0697ba956a56ab"!==this.account.toLowerCase())throw console.warn("⚠️ Connected to different account than expected"),console.warn(" Expected: 0xa0419a048A1469B34a5245f08C0697Ba956a56Ab"),console.warn(" Connected:",this.account),new Error(`Please switch MetaMask to account 0xa041...56Ab. Currently connected to ${this.account.slice(0,6)}...${this.account.slice(-4)}`);return{account:this.account,chainId:this.chainId}}catch(e){throw console.error("MetaMask connection failed:",e),new Error(e.message||"Failed to connect to MetaMask")}}async sendTransaction(e){if(!this.account)throw new Error("Wallet not connected");try{if(console.log("🦊 Sending MetaMask transaction:",e),!window.ethereum.isMetaMask)throw new Error("Not using MetaMask provider");if(e.data&&e.data.includes("a9059cbb")){console.log("🔍 Checking USDT balance...");try{const t=await window.ethereum.request({method:"eth_call",params:[{to:e.to,data:`0x70a08231000000000000000000000000${this.account.slice(2)}`},"latest"]}),s=parseInt(t,16),a=s/1e6;console.log("💰 USDT Balance:",a);const n=e.data.slice(-64),r=parseInt(n,16),o=r/1e6;if(console.log("💸 Transaction Amount:",o),s<r)throw new Error(`Insufficient USDT balance. You have ${a} USDT but need ${o} USDT`)}catch(t){console.warn("Could not check balance:",t)}}try{const e=await window.ethereum.request({method:"eth_getBalance",params:[this.account,"latest"]}),t=parseInt(e,16)/Math.pow(10,18);if(console.log("⛽ ETH Balance for gas:",t),t<.001)throw new Error(`Insufficient ETH for gas fees. You have ${t.toFixed(4)} ETH but need at least 0.001 ETH`)}catch(s){console.warn("Could not check ETH balance:",s)}const a={...e,from:this.account};try{const e=await window.ethereum.request({method:"eth_estimateGas",params:[a]}),t=Math.floor(1.2*parseInt(e,16));a.gas=`0x${t.toString(16)}`,console.log("⛽ Gas estimate:",parseInt(e,16)),console.log("⛽ Gas limit (with buffer):",t)}catch(s){console.warn("Gas estimation failed:",s),a.gas="0x15F90"}console.log("📤 Final transaction params:",a);const n=await window.ethereum.request({method:"eth_sendTransaction",params:[a]});return console.log("✅ Transaction sent successfully:",n),n}catch(a){throw console.error("Transaction failed:",a),4001===a.code?new Error("Transaction cancelled by user"):a.message.includes("insufficient funds")?new Error("Insufficient funds in wallet"):a.message.includes("gas")?new Error("Gas estimation failed. You may not have enough ETH for gas fees."):a.message.includes("invalid opcode")?new Error("Transaction failed - invalid operation. This usually means insufficient token balance or contract interaction failed."):new Error(a.message||"Transaction failed")}}isConnected(){return!!this.account}};class N{constructor(e,t,s){this.baseURL=e.endsWith("/")?e.slice(0,-1):e,this.apiKey=t,this.apiSecret=s}async request(e,t={}){const s=`${this.baseURL}${e}`,a={"Content-Type":"application/json","X-API-Key":this.apiKey,"X-API-Secret":this.apiSecret,...t.headers},n=await fetch(s,{...t,headers:a});if(!n.ok){const e=await n.json().catch(()=>({}));throw new Error(e.error||`HTTP ${n.status}`)}return n.json()}async getNetworks(){try{return await this.request("/api/networks")}catch(e){return console.error("Failed to fetch networks:",e),{networks:[{id:"1",name:"Ethereum",shortName:"ethereum",chainId:"0x1",type:"ethereum"},{id:"56",name:"BSC",shortName:"bsc",chainId:"0x38",type:"bsc"}]}}}async getTokens(){try{return await this.request("/api/networks/stablecoins")}catch(e){return console.error("Failed to fetch tokens:",e),{stablecoins:[{id:"1",name:"Tether USD",symbol:"USDT",contractAddress:"0xdAC17F958D2ee523a2206206994597C13D831ec7",decimals:6,networkId:"1",Network:{shortName:"ethereum",name:"Ethereum"}}]}}}async createPayment(e){return await this.request("/api/payments/create",{method:"POST",body:JSON.stringify(e)})}async verifyQRPayment(e){return await this.request("/api/payments/verify-qr",{method:"POST",body:JSON.stringify({paymentId:e})})}}class k{constructor(){this.account=null,this.chainId=null}async connect(){if(!window.ethereum)throw new Error("MetaMask not installed. Please install MetaMask extension.");if(window.ethereum.providers){console.log("🔍 Multiple wallets detected:",window.ethereum.providers.length);const e=window.ethereum.providers.find(e=>e.isMetaMask);if(!e)throw new Error("MetaMask not found among installed wallets");console.log("🦊 Using MetaMask provider specifically"),window.ethereum=e}else if(!window.ethereum.isMetaMask)throw new Error("Please use MetaMask wallet");try{console.log("🦊 Requesting MetaMask account access...");const e=await window.ethereum.request({method:"eth_requestAccounts"});if(!e||0===e.length)throw new Error("No accounts found in MetaMask");const t=await window.ethereum.request({method:"eth_chainId"});return this.account=e[0],this.chainId=t,console.log("✅ MetaMask connected successfully:"),console.log(" Account:",this.account),console.log(" Chain ID:",this.chainId),{account:this.account,chainId:this.chainId}}catch(e){throw console.error("MetaMask connection failed:",e),new Error(e.message||"Failed to connect to MetaMask")}}async sendTransaction(e){if(!this.account)throw new Error("Wallet not connected");try{if(console.log("🦊 Sending MetaMask transaction:",e),!window.ethereum.isMetaMask)throw new Error("Not using MetaMask provider");const s={...e,from:this.account};try{const e=await window.ethereum.request({method:"eth_estimateGas",params:[s]}),t=Math.floor(1.2*parseInt(e,16));s.gas=`0x${t.toString(16)}`,console.log("⛽ Gas estimate:",parseInt(e,16)),console.log("⛽ Gas limit (with buffer):",t)}catch(t){console.warn("Gas estimation failed:",t),s.gas="0x15F90"}console.log("📤 Final transaction params:",s);const a=await window.ethereum.request({method:"eth_sendTransaction",params:[s]});return console.log("✅ Transaction sent successfully:",a),a}catch(s){throw console.error("Transaction failed:",s),4001===s.code?new Error("Transaction cancelled by user"):s.message.includes("insufficient funds")?new Error("Insufficient funds in wallet"):s.message.includes("gas")?new Error("Gas estimation failed. You may not have enough ETH for gas fees."):new Error(s.message||"Transaction failed")}}isConnected(){return!!this.account}}const C=({walletAddress:e,amount:s,currency:a,network:n,theme:r="light"})=>{const[o,l]=t.useState(""),[c,i]=t.useState(!0);t.useEffect(()=>{e&&(i(!0),setTimeout(()=>{l(`${e}?amount=${s}&currency=${a}&network=${n}`),i(!1)},1e3))},[e,s,a,n]);return p.jsxs("div",{className:"flex flex-col items-center",children:[p.jsx("div",{className:"p-4 rounded-lg bg-white mb-3 shadow-sm border",children:c?p.jsx("div",{className:"flex items-center justify-center",style:{width:200,height:200},children:p.jsxs("div",{className:"text-center",children:[p.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600 mx-auto mb-2"}),p.jsx("div",{className:"text-sm text-gray-600",children:"Generating QR Code..."})]})}):p.jsx("div",{className:"flex items-center justify-center bg-gray-100 rounded-lg",style:{width:200,height:200},children:p.jsxs("div",{className:"text-center p-4",children:[p.jsx("div",{className:"text-2xl mb-2",children:"📱"}),p.jsx("div",{className:"text-sm text-gray-600",children:"QR Code"}),p.jsx("div",{className:"text-xs text-gray-500 mt-1",children:"Scan to pay"})]})})}),p.jsxs("div",{className:"text-center text-sm text-gray-700 mb-4",children:[p.jsxs("p",{className:"font-semibold text-gray-800 flex items-center justify-center",children:[p.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-4 w-4 mr-1",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:p.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v1m6 11h2m-6 0h-2v4m0-11v3m0 0h.01M12 12h4.01M12 12h-4.01M12 12V8.01"})}),"Scan to Pay with ",a]}),p.jsxs("p",{className:"text-xs text-gray-500 mt-1",children:["Scan with your ",n," wallet app"]})]}),p.jsxs("div",{className:"w-full mb-4 p-3 bg-gray-50 rounded-lg",children:[p.jsxs("div",{className:"flex justify-between items-center",children:[p.jsx("span",{className:"text-sm font-medium text-gray-700",children:"Amount to Pay:"}),p.jsxs("span",{className:"text-lg font-bold text-[#7042D2]",children:[s," ",a]})]}),p.jsxs("div",{className:"flex justify-between items-center mt-1",children:[p.jsx("span",{className:"text-xs text-gray-500",children:"Network:"}),p.jsx("span",{className:"text-xs font-medium text-gray-700",children:n})]}),p.jsxs("div",{className:"flex justify-between items-center mt-1",children:[p.jsx("span",{className:"text-xs text-gray-500",children:"Recipient:"}),p.jsx("span",{className:"text-xs font-mono text-gray-700",children:(d=e,!d||d.length<=16?d:`${d.slice(0,6)}...${d.slice(-4)}`)})]})]}),p.jsx("div",{className:"w-full",children:p.jsxs("div",{className:"p-3 rounded bg-blue-50 border border-blue-200",children:[p.jsxs("h4",{className:"text-sm font-medium mb-2 text-blue-800 flex items-center",children:[p.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-4 w-4 mr-1",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:p.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),"Payment Instructions"]}),p.jsxs("ol",{className:"text-xs space-y-1 text-blue-700",children:[p.jsx("li",{children:"1. Open your crypto wallet app"}),p.jsx("li",{children:"2. Scan the QR code above"}),p.jsxs("li",{children:["3. Send exactly ",p.jsxs("strong",{children:[s," ",a]})]}),p.jsx("li",{children:'4. Click "I have sent the payment" button below'})]})]})})]});var d},S=({status:e,message:s,theme:a="light",payment:n=null,transactionHash:r=null,selectedPaymentMethod:o=null,merchantName:l="Merchant",onClose:c=null})=>{const[i,d]=t.useState(!1),m=async()=>{if(r)try{await navigator.clipboard.writeText(r),d(!0),setTimeout(()=>d(!1),2e3)}catch(e){console.error("Failed to copy transaction hash:",e)}},h=()=>{switch(e){case"processing":return p.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-4 border-t-purple-600 border-blue-500/20"});case"success":return p.jsx("div",{className:"rounded-full h-16 w-16 bg-green-500 flex items-center justify-center",children:p.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-10 w-10 text-white",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:3,children:p.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})})});case"error":return p.jsx("div",{className:"rounded-full h-12 w-12 bg-red-100 flex items-center justify-center",children:p.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-8 w-8 text-red-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:p.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})})});default:return null}};return"success"===e?p.jsxs("div",{className:"flex flex-col items-center justify-center py-6 px-4",children:[p.jsx("div",{className:"mb-6",children:h()}),p.jsx("h3",{className:"text-2xl font-bold mb-3 text-gray-900",children:"Payment Successful!"}),n&&o&&p.jsxs("p",{className:"text-center max-w-[235px] mb-6 text-gray-600",children:["Your payment of ",p.jsxs("span",{className:"text-[#7042D2] font-semibold",children:[n.totalAmount||n.amount," ",o.currency]})," has been completed."]}),r&&p.jsxs("div",{className:"w-full mb-6 px-4",children:[p.jsx("p",{className:"text-sm font-medium mb-2 text-gray-700",children:"Transaction Hash:"}),p.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border cursor-pointer transition-colors bg-gray-50 border-gray-200 hover:bg-gray-100",onClick:m,children:[p.jsx("span",{className:"font-mono text-sm text-gray-700",children:(u=r,u?u.length<=16?u:`${u.slice(0,8)}...${u.slice(-8)}`:"")}),p.jsxs("div",{className:"flex items-center",children:[i?p.jsx("span",{className:"text-green-500 text-xs font-medium mr-2",children:"Copied!"}):null,p.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-4 w-4 text-gray-500",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:p.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"})})]})]})]}),c&&p.jsx("button",{onClick:c,className:"w-full py-3 px-4 bg-[#7042D2] text-white font-medium rounded-2xl text-lg shadow-md hover:bg-[#5b34b1] transition-colors",children:"Close"})]}):p.jsxs("div",{className:"flex flex-col items-center justify-center py-6",children:[p.jsx("div",{className:"mb-4",children:h()}),p.jsx("h3",{className:"text-xl font-bold mb-2 text-gray-900",children:"processing"===e?"Processing Payment":"error"===e?"Payment Failed":"Unknown Status"}),p.jsx("p",{className:"text-center text-gray-600",children:s})]});var u},M=({currentStep:e,targetStep:s,children:a,className:n="",duration:r=300})=>{const[o,l]=t.useState(e===s),[c,i]=t.useState(e===s);return t.useEffect(()=>{e===s?(i(!0),setTimeout(()=>l(!0),10)):(l(!1),setTimeout(()=>i(!1),r))},[e,s,r]),c?p.jsx("div",{className:`\n transition-all duration-300 ease-out\n ${o?"transform translate-y-0 opacity-100":"transform translate-y-full opacity-0"}\n ${n}\n `,style:{transitionDuration:`${r}ms`},children:a}):null},P={formatAmount:(e,t=2)=>e.toFixed(t),truncateAddress:(e,t=6,s=4)=>e?e.length<=t+s?e:`${e.slice(0,t)}...${e.slice(-s)}`:"",isValidAddress:(e,t)=>{if(!e)return!1;switch(t.toLowerCase()){case"ethereum":case"bsc":case"polygon":return/^0x[a-fA-F0-9]{40}$/.test(e);case"tron":return/^T[a-zA-Z0-9]{33}$/.test(e);case"solana":return/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(e);default:return e.length>0}},copyToClipboard:async e=>{try{return await navigator.clipboard.writeText(e),!0}catch{return!1}}};class E extends Error{constructor(e,t){super(e),this.name="CoinleyError",this.code=t}}const T={simple:'\nimport { SimpleCoinleyPayment } from \'coinley-test\';\n\n<SimpleCoinleyPayment\n apiKey="your-api-key"\n apiSecret="your-api-secret"\n apiUrl="https://your-api-url.com"\n isOpen={isOpen}\n config={{\n amount: 100,\n customerEmail: "customer@example.com",\n merchantWalletAddresses: {\n ethereum: "0x...",\n bsc: "0x..."\n }\n }}\n onSuccess={(paymentId, txHash, details) => console.log(\'Success!\')}\n onError={(error) => console.error(\'Error:\', error)}\n onClose={() => setIsOpen(false)}\n/>\n ',enhanced:'\nimport { EnhancedSimpleCoinleyPayment } from \'coinley-test\';\n\n<EnhancedSimpleCoinleyPayment\n apiKey="your-api-key"\n apiSecret="your-api-secret"\n apiUrl="https://your-api-url.com"\n isOpen={isOpen}\n config={{\n amount: 100,\n customerEmail: "customer@example.com",\n merchantName: "Your Store",\n merchantWalletAddresses: {\n ethereum: "0x...",\n bsc: "0x..."\n }\n }}\n onSuccess={(paymentId, txHash, details) => console.log(\'Success!\')}\n onError={(error) => console.error(\'Error:\', error)}\n onClose={() => setIsOpen(false)}\n theme="light" // or "dark"\n/>\n '};e.CoinleyCheckout=b,e.CoinleyError=E,e.CoinleyPayment=f,e.CoinleyProvider=({apiKey:e,apiSecret:s,apiUrl:a,theme:n="light",debug:r=!1,children:o})=>{const[l,c]=t.useState(!1),[i,d]=t.useState(null),[m,h]=t.useState({}),[u,x]=t.useState(""),y=()=>{c(!1),d(null),m.onClose&&m.onClose()},g={openPayment:(e,t)=>{d(e),t&&h(t),c(!0)},closePayment:y};return p.jsxs(w.Provider,{value:g,children:[o,l&&i&&p.jsx(f,{apiKey:e,apiSecret:s,apiUrl:a,isOpen:l,config:i,theme:n,debug:r,merchantName:u,onSuccess:m.onSuccess,onError:m.onError,onClose:y})]})},e.DEFAULT_CONFIG={theme:"light",debug:!1,testMode:!1,autoOpen:!1},e.EnhancedSimpleCoinleyPayment=({apiKey:e,apiSecret:s,apiUrl:a,config:n,onSuccess:r,onError:o,onClose:l,isOpen:c,theme:i="light"})=>{var d,m;const[h,u]=t.useState("method"),[x,y]=t.useState([]),[g,f]=t.useState([]),[w,b]=t.useState(null),[j,v]=t.useState(null),[P,E]=t.useState(null),[T,A]=t.useState(null),[D,I]=t.useState(!1),[W,$]=t.useState(""),[F,L]=t.useState(new k),[U,R]=t.useState(!1),[q,H]=t.useState(!1),[O,_]=t.useState("wallet"),B=t.useRef(new N(a,e,s));t.useEffect(()=>{c&&(K(),Q())},[c]);const Q=()=>{u("method"),b(null),v(null),E(null),A(null),$(""),R(!1),H(!1),L(new k),_("wallet")},K=async()=>{var e,t;try{I(!0),$(""),console.log("🔄 Loading networks and tokens...");const[s,a]=await Promise.all([B.current.getNetworks(),B.current.getTokens()]);y(s.networks||[]),f(a.stablecoins||[]),console.log("✅ Loaded networks:",null==(e=s.networks)?void 0:e.length),console.log("✅ Loaded tokens:",null==(t=a.stablecoins)?void 0:t.length)}catch(s){console.error("Failed to load data:",s),$("Failed to load payment options. Using fallback data.")}finally{I(!1)}},G=e=>parseFloat(e).toFixed(2);return c?p.jsxs("div",{className:"fixed inset-0 z-50",children:[p.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 transition-opacity",onClick:l,"aria-hidden":"true"}),p.jsx("div",{className:"fixed inset-0 overflow-y-auto",children:p.jsx("div",{className:"flex min-h-screen items-center justify-center p-4",children:p.jsxs("div",{className:"relative pt-6 w-full max-w-md mx-auto shadow-xl bg-gray-100 rounded-3xl overflow-hidden",children:[p.jsxs("div",{className:"bg-white flex justify-between items-center mb-6 mr-3 ml-3 py-4 px-2 rounded-full",children:[p.jsxs("div",{className:"flex-1 flex items-center gap-2 px-4",children:[p.jsx("div",{className:"w-8 h-8 bg-purple-600 rounded-full flex items-center justify-center",children:p.jsx("span",{className:"text-white font-bold text-sm",children:"C"})}),p.jsx("span",{className:"text-lg font-semibold text-gray-800",children:"Payment Details"})]}),"success"!==h&&"processing"!==h&&p.jsx("button",{onClick:l,className:"text-gray-500 hover:text-gray-700 focus:outline-none",children:p.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-6 w-6 mr-2",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:p.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),T&&"success"!==h&&p.jsx("div",{className:"mb-6",children:p.jsxs("div",{className:"text-center",children:[p.jsx("div",{className:"text-sm text-gray-600",children:"Total Amount"}),p.jsxs("div",{className:"text-3xl md:text-9xl lg:text-9xl font-bold text-[#7042D2] mt-2 leading-tight tracking-tight",children:["$",G(T.totalAmount||T.amount)]}),"customer"===T.feeChargedTo&&T.feeAmount>0&&p.jsx("div",{className:"mt-2 text-sm text-gray-500",children:"Processing fee included"}),"merchant"===T.feeChargedTo&&p.jsx("div",{className:"mt-2 text-sm text-gray-500",children:"No additional fees"}),p.jsx("div",{className:"text-sm text-gray-600 mt-4",children:"Payment to:"}),p.jsxs("div",{className:"text-base font-semibold mt-1 flex gap-2 items-center justify-center",children:[p.jsx("svg",{width:"20",height:"20",viewBox:"0 0 20 20",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:p.jsx("path",{d:"M15.3 7.50065L15.8 10.0007H4.2L4.7 7.50065H15.3ZM16.6667 3.33398H3.33333V5.00065H16.6667V3.33398ZM16.6667 5.83398H3.33333L2.5 10.0007V11.6673H3.33333V16.6673H11.6667V11.6673H15V16.6673H16.6667V11.6673H17.5V10.0007L16.6667 5.83398ZM5 15.0007V11.6673H10V15.0007H5Z",fill:"#7042D2"})}),n.merchantName||"Merchant"]})]})}),p.jsxs("div",{className:"relative",children:[p.jsx(M,{currentStep:h,targetStep:"method",children:p.jsxs("div",{className:"pb-6 pt-6 px-6 bg-white rounded-t-2xl",children:[p.jsx("h3",{className:"font-medium text-center mb-6",children:"Choose Payment Method"}),p.jsxs("div",{className:"space-y-4 mb-6",children:[p.jsx("label",{className:"block text-sm font-medium text-gray-700",children:"Select Network"}),p.jsx("div",{className:"space-y-2",children:x.map(e=>p.jsxs("button",{onClick:()=>b(e),className:"w-full p-3 border rounded-lg text-left transition-colors "+((null==w?void 0:w.id)===e.id?"border-purple-500 bg-purple-50":"border-gray-200 hover:bg-gray-50"),children:[p.jsx("div",{className:"font-medium",children:e.name}),p.jsx("div",{className:"text-sm text-gray-500",children:e.shortName.toUpperCase()})]},e.id))})]}),w&&p.jsxs("div",{className:"space-y-4 mb-6",children:[p.jsx("label",{className:"block text-sm font-medium text-gray-700",children:"Select Token"}),p.jsx("div",{className:"space-y-2",children:g.filter(e=>{var t;return(null==(t=e.Network)?void 0:t.shortName)===(null==w?void 0:w.shortName)}).map(e=>p.jsxs("button",{onClick:()=>v(e),className:"w-full p-3 border rounded-lg text-left flex justify-between transition-colors "+((null==j?void 0:j.id)===e.id?"border-purple-500 bg-purple-50":"border-gray-200 hover:bg-gray-50"),children:[p.jsxs("div",{children:[p.jsx("div",{className:"font-medium",children:e.name}),p.jsx("div",{className:"text-sm text-gray-500",children:e.symbol})]}),e.isStablecoin&&p.jsx("span",{className:"px-2 py-1 bg-green-100 text-green-600 text-xs rounded",children:"Stablecoin"})]},e.id))})]}),w&&j&&p.jsx("button",{onClick:async()=>{try{I(!0),$("");const e={amount:n.amount,currency:j.symbol,network:w.shortName,customerEmail:n.customerEmail,callbackUrl:n.callbackUrl,metadata:{...n.metadata,merchantWalletAddresses:n.merchantWalletAddresses,paymentMethod:P,selectedNetwork:w.shortName,selectedToken:j.symbol}};console.log("🔄 Creating payment:",e);const t=await B.current.createPayment(e);A(t.payment),console.log("✅ Payment created:",t.payment.id),u("confirm")}catch(e){console.error("Payment creation failed:",e),$(e.message)}finally{I(!1)}},disabled:D,className:"w-full bg-purple-600 text-white py-3 px-4 rounded-lg hover:bg-purple-700 disabled:opacity-50 font-medium",children:D?"Creating Payment...":"Continue"})]})}),p.jsx(M,{currentStep:h,targetStep:"confirm",children:w&&j&&T&&p.jsxs("div",{children:[p.jsx("div",{className:"mb-4 px-4",children:p.jsxs("div",{className:"flex border-b border-gray-200",children:[p.jsx("button",{onClick:()=>_("wallet"),className:"py-2 px-4 text-sm font-medium "+("wallet"===O?"border-b-2 border-purple-600 text-purple-600":"text-gray-500 hover:text-gray-700"),children:"Connect Wallet"}),p.jsx("button",{onClick:()=>_("qrcode"),className:"py-2 px-4 text-sm font-medium "+("qrcode"===O?"border-b-2 border-purple-600 text-purple-600":"text-gray-500 hover:text-gray-700"),children:"QR Code"})]})}),"wallet"===O&&p.jsxs("div",{className:"p-4 rounded-2xl mb-4 bg-white",children:[p.jsx("h3",{className:"text-lg font-medium mb-2 text-gray-800",children:"Payment Details"}),p.jsxs("div",{className:"space-y-2 bg-[#EDE4FF] p-3 rounded-xl",children:[p.jsxs("div",{className:"flex justify-between",children:[p.jsx("span",{className:"font-medium",children:"Currency:"}),p.jsx("span",{className:"font-medium",children:j.symbol})]}),p.jsx("div",{className:"border border-b border-gray-400"}),p.jsxs("div",{className:"flex justify-between",children:[p.jsx("span",{className:"font-medium",children:"Network:"}),p.jsx("span",{className:"font-medium",children:(V=w.shortName,{ethereum:"Ethereum",bsc:"BSC",tron:"Tron",algorand:"Algorand",solana:"Solana"}[V]||V)})]}),p.jsx("div",{className:"border border-b border-gray-400"}),p.jsxs("div",{className:"flex justify-between border-t pt-2 mt-1",children:[p.jsx("span",{className:"font-bold",children:"Total:"}),p.jsxs("span",{className:"font-bold text-lg",children:["$",G(T.totalAmount)]})]})]})]}),"qrcode"===O?p.jsx("div",{className:"mb-4",children:p.jsx(C,{walletAddress:(()=>{var e;if(!w)return"No network selected";const t=null==(e=n.merchantWalletAddresses)?void 0:e[w.shortName];return t||((null==T?void 0:T.recipientWallet)?T.recipientWallet:"No wallet address configured for this network")})(),amount:T.totalAmount||T.amount,currency:j.symbol,network:w.shortName,theme:i})}):p.jsx("div",{className:"space-y-3 mb-4 px-4",children:U?p.jsx("div",{className:"space-y-4",children:p.jsxs("div",{className:"p-3 bg-green-50 rounded-lg border border-green-200",children:[p.jsx("p",{className:"text-green-600 text-sm font-medium",children:"✅ Wallet Connected"}),p.jsxs("p",{className:"font-mono text-xs text-green-700 mt-1",children:[null==(d=F.account)?void 0:d.slice(0,6),"...",null==(m=F.account)?void 0:m.slice(-4)]})]})}):p.jsxs("div",{className:"text-center space-y-4",children:[p.jsx("div",{className:"w-16 h-16 bg-purple-100 rounded-full flex items-center justify-center mx-auto",children:p.jsx("span",{className:"text-2xl",children:"🦊"})}),p.jsx("p",{className:"text-gray-600",children:"Connect MetaMask to continue"}),p.jsx("button",{onClick:async()=>{try{I(!0),$("");const e=await F.connect();R(!0),console.log("✅ Wallet connected successfully:",e.account)}catch(e){console.error("Wallet connection failed:",e),$(e.message)}finally{I(!1)}},disabled:D,className:"w-full bg-purple-600 text-white py-3 px-4 rounded-lg hover:bg-purple-700 disabled:opacity-50 font-medium",children:D?"Connecting...":"Connect MetaMask"})]})}),W&&p.jsx("div",{className:"p-3 rounded-lg bg-red-50 mb-4 text-red-600 text-sm",children:W}),p.jsxs("div",{className:"grid grid-cols-2 gap-3 mb-3 px-4",children:[p.jsx("button",{type:"button",onClick:()=>u("method"),className:"w-full py-2 px-4 bg-gray-200 hover:bg-gray-300 text-purple-600 font-medium rounded-md",children:"Back"}),p.jsx("button",{type:"button",onClick:"qrcode"===O?async()=>{if(T){u("processing"),$(null);try{console.log("🔄 Starting QR payment verification...");const e=await B.current.verifyQRPayment(T.id);e.verified?(console.log("✅ QR payment verified successfully:",e),u("success"),r&&r(T.id,e.payment.transactionHash,{network:w.name,currency:j.symbol,amount:e.payment.amount,verificationType:"QR_PAYMENT"})):($(e.message||"Transaction not detected yet. Please wait a moment and try again."),u("confirm"))}catch(e){console.error("QR payment verification error:",e);const t=e.message||"Failed to verify payment. Please try again.";$(t),u("confirm"),o&&o(t)}}else $("Payment information is missing")}:async()=>{var e,t;try{H(!0),$("");const s=(null==(e=T.metadata)?void 0:e.recipientWallet)||(null==(t=n.merchantWalletAddresses)?void 0:t[w.shortName]);if(!s)throw new Error("Merchant wallet address not found");let a;if(console.log("🔄 Preparing transaction to:",s),j.contractAddress){const e=j.decimals||6,t=Math.floor(T.totalAmount*Math.pow(10,e)),n="0xa9059cbb",r=s.slice(2).toLowerCase().padStart(64,"0"),o=`${n}${r}${t.toString(16).padStart(64,"0")}`;a={to:j.contractAddress,data:o,value:"0x0"},console.log("🔄 ERC-20 Transaction:",{token:j.symbol,amount:T.totalAmount,amountWithDecimals:t,to:j.contractAddress,recipient:s})}else{a={to:s,value:`0x${Math.floor(T.totalAmount*Math.pow(10,18)).toString(16)}`},console.log("🔄 Native Transaction:",{amount:T.totalAmount,to:s})}const o=await F.sendTransaction(a);console.log("✅ Transaction successful:",o),u("success"),null==r||r(T.id,o,{network:w.name,currency:j.symbol,amount:T.totalAmount,method:P})}catch(s){console.error("Transaction failed:",s),$(s.message),null==o||o(s.message)}finally{H(!1)}},className:"bg-green-600 text-white w-full py-2 px-4 font-medium rounded-md",disabled:"wallet"===O&&!U,children:"qrcode"===O?"I have sent the payment":"Pay Now"})]})]})}),p.jsx(M,{currentStep:h,targetStep:"processing",children:p.jsx(S,{status:"processing",theme:i,message:"Processing your payment..."})}),p.jsx(M,{currentStep:h,targetStep:"success",children:p.jsx(S,{status:"success",theme:i,message:"Payment successful!",payment:T,transactionHash:"0x123...abc",selectedPaymentMethod:{currency:null==j?void 0:j.symbol},merchantName:n.merchantName||"Merchant",onClose:l})})]}),"success"!==h&&p.jsxs("div",{className:"text-center text-xs text-gray-500 flex items-center justify-center gap-1 py-6 bg-white rounded-b-3xl",children:[p.jsxs("p",{children:["Powered by ",p.jsx("span",{className:"text-purple-600",children:"Coinley"})," - Secure Cryptocurrency Payments"]}),p.jsxs("svg",{className:"inline w-4 h-4 text-green-500 ml-1",fill:"none",stroke:"currentColor",strokeWidth:"2",viewBox:"0 0 24 24",children:[p.jsx("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"2",fill:"none"}),p.jsx("path",{d:"M9 12l2 2 4-4",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})]})]})]})})})]}):null;var V},e.PaymentAPI=y,e.SimpleCoinleyPayment=({apiKey:e,apiSecret:s,apiUrl:a,config:n,onSuccess:r,onError:o,onClose:l,isOpen:c,theme:i="light"})=>{var d,m;const[h,u]=t.useState("method"),[x,y]=t.useState([]),[g,f]=t.useState([]),[w,b]=t.useState(null),[N,k]=t.useState(null),[C,S]=t.useState(null),[M,P]=t.useState(null),[E,T]=t.useState(!1),[A,D]=t.useState(""),[I,W]=t.useState(new v),[$,F]=t.useState(!1),[L,U]=t.useState(!1),R=t.useRef(new j(a,e,s));t.useEffect(()=>{c&&(H(),q())},[c]);const q=()=>{u("method"),b(null),k(null),S(null),P(null),D(""),F(!1),U(!1),W(new v)},H=async()=>{var e,t;try{T(!0),D(""),console.log("🔄 Loading networks and tokens...");const[s,a]=await Promise.all([R.current.getNetworks(),R.current.getTokens()]);y(s.networks||[]),f(a.stablecoins||[]),console.log("✅ Loaded networks:",null==(e=s.networks)?void 0:e.length),console.log("✅ Loaded tokens:",null==(t=a.stablecoins)?void 0:t.length)}catch(s){console.error("Failed to load data:",s),D("Failed to load payment options. Using fallback data.")}finally{T(!1)}};if(!c)return null;const O="dark"===i;return p.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:p.jsxs("div",{className:"rounded-lg shadow-xl max-w-md w-full mx-4 "+(O?"bg-gray-900 text-white":"bg-white text-gray-900"),children:[p.jsxs("div",{className:"p-4 border-b flex justify-between items-center "+(O?"border-gray-700":"border-gray-200"),children:[p.jsxs("div",{className:"text-center flex-1",children:[p.jsx("h2",{className:"text-lg font-semibold",children:"Pay with Crypto"}),n.amount&&p.jsxs("p",{className:"text-2xl font-bold text-purple-600",children:["$",n.amount.toFixed(2)]})]}),p.jsx("button",{onClick:l,className:"ml-4 text-gray-500 hover:text-gray-700 "+(O?"hover:text-gray-300":""),children:"✕"})]}),p.jsxs("div",{className:"p-4 min-h-[400px]",children:[A&&p.jsxs("div",{className:"mb-4 p-3 bg-red-100 text-red-700 rounded border border-red-200",children:[A,p.jsx("button",{onClick:()=>D(""),className:"ml-2 text-red-500 hover:text-red-700",children:"✕"})]}),"method"===h&&p.jsxs("div",{className:"space-y-4",children:[p.jsx("h3",{className:"font-medium text-center mb-6",children:"Choose Payment Method"}),p.jsxs("div",{className:"space-y-3",children:[p.jsxs("button",{onClick:()=>{S("wallet"),u("network")},className:"w-full p-4 border-2 rounded-lg hover:border-purple-500 text-left flex items-center space-x-3 transition-colors "+(O?"border-gray-600 hover:bg-gray-800":"border-gray-200 hover:bg-gray-50"),children:[p.jsx("span",{className:"text-2xl",children:"🦊"}),p.jsxs("div",{children:[p.jsx("div",{className:"font-medium",children:"MetaMask Wallet"}),p.jsx("div",{className:"text-sm "+(O?"text-gray-400":"text-gray-500"),children:"Connect and pay instantly"})]})]}),p.jsxs("button",{onClick:()=>{S("qr"),u("network")},className:"w-full p-4 border-2 rounded-lg hover:border-purple-500 text-left flex items-center space-x-3 transition-colors "+(O?"border-gray-600 hover:bg-gray-800":"border-gray-200 hover:bg-gray-50"),children:[p.jsx("span",{className:"text-2xl",children:"📱"}),p.jsxs("div",{children:[p.jsx("div",{className:"font-medium",children:"QR Code"}),p.jsx("div",{className:"text-sm "+(O?"text-gray-400":"text-gray-500"),children:"Scan with mobile wallet"})]})]})]})]}),"network"===h&&p.jsxs("div",{className:"space-y-4",children:[p.jsxs("div",{className:"flex items-center space-x-2",children:[p.jsx("button",{onClick:()=>u("method"),className:""+(O?"text-gray-400 hover:text-gray-200":"text-gray-500 hover:text-gray-700"),children:"←"}),p.jsx("h3",{className:"font-medium",children:"Select Network"})]}),p.jsx("div",{className:"space-y-2",children:x.map(e=>p.jsxs("button",{onClick:()=>{b(e),u("token")},className:"w-full p-3 border rounded-lg hover:border-purple-500 text-left transition-colors "+(O?"border-gray-600 hover:bg-gray-800":"border-gray-200 hover:bg-gray-50"),children:[p.jsx("div",{className:"font-medium",children:e.name}),p.jsx("div",{className:"text-sm "+(O?"text-gray-400":"text-gray-500"),children:e.shortName.toUpperCase()})]},e.id))})]}),"token"===h&&p.jsxs("div",{className:"space-y-4",children:[p.jsxs("div",{className:"flex items-center space-x-2",children:[p.jsx("button",{onClick:()=>u("network"),className:""+(O?"text-gray-400 hover:text-gray-200":"text-gray-500 hover:text-gray-700"),children:"←"}),p.jsxs("h3",{className:"font-medium",children:["Select Token on ",null==w?void 0:w.name]})]}),p.jsx("div",{className:"space-y-2",children:g.filter(e=>{var t;return(null==(t=e.Network)?void 0:t.shortName)===(null==w?void 0:w.shortName)}).map(e=>p.jsxs("button",{onClick:()=>{k(e),(async()=>{try{T(!0),D("");const e={amount:n.amount,currency:N.symbol,network:w.shortName,customerEmail:n.customerEmail,callbackUrl:n.callbackUrl,metadata:{...n.metadata,merchantWalletAddresses:n.merchantWalletAddresses,paymentMethod:C,selectedNetwork:w.shortName,selectedToken:N.symbol}};console.log("🔄 Creating payment:",e);const t=await R.current.createPayment(e);P(t.payment),console.log("✅ Payment created:",t.payment.id),u("wallet"===C?"wallet":"qr")}catch(e){console.error("Payment creation failed:",e),D(e.message)}finally{T(!1)}})()},disabled:E,className:"w-full p-3 border rounded-lg hover:border-purple-500 text-left flex justify-between transition-colors disabled:opacity-50 "+(O?"border-gray-600 hover:bg-gray-800":"border-gray-200 hover:bg-gray-50"),children:[p.jsxs("div",{children:[p.jsx("div",{className:"font-medium",children:e.name}),p.jsx("div",{className:"text-sm "+(O?"text-gray-400":"text-gray-500"),children:e.symbol})]}),e.isStablecoin&&p.jsx("span",{className:"px-2 py-1 bg-green-100 text-green-600 text-xs rounded",children:"Stablecoin"})]},e.id))})]}),"wallet"===h&&p.jsxs("div",{className:"space-y-4",children:[p.jsx("h3",{className:"font-medium text-center",children:"Connect & Pay"}),$?p.jsxs("div",{className:"space-y-4",children:[p.jsxs("div",{className:"p-3 bg-green-50 rounded-lg border border-green-200",children:[p.jsx("p",{className:"text-green-600 text-sm font-medium",children:"✅ Wallet Connected"}),p.jsxs("p",{className:"font-mono text-xs text-green-700 mt-1",children:[null==(d=I.account)?void 0:d.slice(0,6),"...",null==(m=I.account)?void 0:m.slice(-4)]})]}),p.jsxs("div",{className:"p-4 rounded-lg space-y-2 "+(O?"bg-gray-800":"bg-gray-50"),children:[p.jsxs("div",{className:"flex justify-between text-sm",children:[p.jsx("span",{children:"Amount:"}),p.jsxs("span",{className:"font-medium",children:[null==M?void 0:M.totalAmount," ",null==N?void 0:N.symbol]})]}),p.jsxs("div",{className:"flex justify-between text-sm",children:[p.jsx("span",{children:"Network:"}),p.jsx("span",{className:"font-medium",children:null==w?void 0:w.name})]}),p.jsxs("div",{className:"flex justify-between text-sm",children:[p.jsx("span",{children:"Token:"}),p.jsx("span",{className:"font-medium",children:null==N?void 0:N.name})]})]}),p.jsx("button",{onClick:async()=>{var e,t;try{U(!0),D("");const s=(null==(e=M.metadata)?void 0:e.recipientWallet)||(null==(t=n.merchantWalletAddresses)?void 0:t[w.shortName]);if(!s)throw new Error("Merchant wallet address not found");let a;if(console.log("🔄 Preparing transaction to:",s),N.contractAddress){const e=N.decimals||6,t=Math.floor(M.totalAmount*Math.pow(10,e)),n="0xa9059cbb",r=s.slice(2).toLowerCase().padStart(64,"0"),o=`${n}${r}${t.toString(16).padStart(64,"0")}`;a={to:N.contractAddress,data:o,value:"0x0"},console.log("🔄 ERC-20 Transaction:",{token:N.symbol,amount:M.totalAmount,amountWithDecimals:t,to:N.contractAddress,recipient:s})}else{a={to:s,value:`0x${Math.floor(M.totalAmount*Math.pow(10,18)).toString(16)}`},console.log("🔄 Native Transaction:",{amount:M.totalAmount,to:s})}const o=await I.sendTransaction(a);console.log("✅ Transaction successful:",o),u("success"),null==r||r(M.id,o,{network:w.name,token:N.symbol,amount:M.totalAmount,method:C})}catch(s){console.error("Transaction failed:",s),D(s.message)}finally{U(!1)}},disabled:L,className:"w-full bg-green-600 text-white py-3 px-4 rounded-lg hover:bg-green-700 disabled:opacity-50 font-medium flex items-center justify-center space-x-2",children:L?p.jsxs(p.Fragment,{children:[p.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-b-2 border-white"}),p.jsx("span",{children:"Sending Transaction..."})]}):p.jsxs("span",{children:["Send ",null==M?void 0:M.totalAmount," ",null==N?void 0:N.symbol]})})]}):p.jsxs("div",{className:"text-center space-y-4",children:[p.jsx("div",{className:"w-16 h-16 bg-purple-100 rounded-full flex items-center justify-center mx-auto",children:p.jsx("span",{className:"text-2xl",children:"🦊"})}),p.jsx("p",{className:""+(O?"text-gray-300":"text-gray-600"),children:"Connect MetaMask to continue"}),p.jsx("button",{onClick:async()=>{try{T(!0),D("");const e=await I.connect();F(!0),console.log("✅ Wallet connected successfully:",e.account)}catch(e){console.error("Wallet connection failed:",e),D(e.message)}finally{T(!1)}},disabled:E,className:"w-full bg-purple-600 text-white py-3 px-4 rounded-lg hover:bg-purple-700 disabled:opacity-50 font-medium",children:E?"Connecting...":"Connect MetaMask"})]})]}),"qr"===h&&p.jsxs("div",{className:"text-center space-y-4",children:[p.jsx("h3",{className:"font-medium",children:"Scan QR Code"}),p.jsxs("div",{className:"p-8 rounded-lg "+(O?"bg-gray-800":"bg-gray-100"),children:[p.jsx("p",{className:""+(O?"text-gray-400":"text-gray-500"),children:"QR Code will appear here"}),p.jsxs("p",{className:"text-xs mt-2",children:["Send ",null==M?void 0:M.totalAmount," ",null==N?void 0:N.symbol]}),p.jsx("p",{className:"text-xs",children:"to merchant wallet"})]}),p.jsx("p",{className:"text-xs "+(O?"text-gray-400":"text-gray-500"),children:"Waiting for payment confirmation..."})]}),"success"===h&&p.jsxs("div",{className:"text-center space-y-4",children:[p.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto",children:p.jsx("span",{className:"text-2xl",children:"✅"})}),p.jsx("h3",{className:"font-medium text-green-600",children:"Payment Successful!"}),p.jsx("p",{className:"text-sm "+(O?"text-gray-300":"text-gray-600"),children:"Your transaction has been sent successfully"}),p.jsx("button",{onClick:l,className:"w-full bg-purple-600 text-white py-3 px-4 rounded-lg hover:bg-purple-700 font-medium",children:"Close"})]}),E&&"wallet"!==h&&p.jsx("div",{className:"flex items-center justify-center py-8",children:p.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-purple-600"})})]})]})})},e.SimpleCoinleyProvider=({children:e,...t})=>e,e.ThemeProvider=({initialTheme:e="light",children:s})=>{const[a,n]=t.useState(e);return t.useEffect(()=>{document.documentElement.setAttribute("data-coinley-theme",a)},[a]),p.jsx("div",{className:`coinley-theme-${a}`,children:s})},e.USAGE_EXAMPLES=T,e.VERSION="0.0.2",e.useCoinley=()=>{const e=t.useContext(w);if(!e)throw new Error("useCoinley must be used within a CoinleyProvider");return e},e.utils=P,Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})});
2
2
  //# sourceMappingURL=index.umd.js.map