@ic-pay/icpay-widget 1.2.117 → 1.2.122

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.
@@ -1,4 +1,4 @@
1
- import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
1
+ import{a as c}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
2
2
  :host {
3
3
  /* Light mode defaults (from COLOR_PALETTE.md) */
4
4
  --icpay-background: #ffffff;
@@ -143,9 +143,9 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
143
143
  0%, 100% { opacity: 1; }
144
144
  50% { opacity: 0.7; }
145
145
  }
146
- `;function Yt(r){return typeof r=="string"?r:r&&typeof r=="object"&&r.mode?r.mode:"light"}function ge(r,l){if(!r)return;let e=null,t="light";if(typeof l=="string")t=l,e={mode:t};else if(l&&typeof l=="object")e=l,t=l.mode||"light";else if(typeof document<"u"){let a=document.documentElement.getAttribute("data-icpay-theme")||document.documentElement.getAttribute("data-theme");(a==="light"||a==="dark")&&(t=a)}if(r instanceof HTMLElement&&r.setAttribute("data-theme",t),typeof document<"u"&&document.documentElement&&(document.documentElement.setAttribute("data-icpay-theme",t),document.documentElement.style.setProperty("--icpay-theme-mode",t)),!e)return;let n=(a,i)=>{i&&r.style.setProperty(a,i)};e.primaryColor&&n("--icpay-primary",e.primaryColor),e.secondaryColor&&n("--icpay-secondary",e.secondaryColor),e.accentColor&&n("--icpay-accent",e.accentColor),e.textColor&&n("--icpay-foreground",e.textColor),e.mutedTextColor&&n("--icpay-muted-foreground",e.mutedTextColor),e.surfaceColor&&n("--icpay-background",e.surfaceColor),e.surfaceAltColor&&n("--icpay-secondary",e.surfaceAltColor),e.borderColor&&n("--icpay-border",e.borderColor),e.fontFamily&&n("--icpay-font",e.fontFamily),e.textColor&&n("--icpay-text",e.textColor),e.mutedTextColor&&n("--icpay-muted",e.mutedTextColor),e.surfaceAltColor&&n("--icpay-surface-alt",e.surfaceAltColor)}import{Icpay as $e}from"@ic-pay/icpay-sdk";var Be=typeof window<"u";function me(r,l,e){r&&(e!==void 0?console.log(`[ICPay Widget] ${l}`,e):console.log(`[ICPay Widget] ${l}`))}function E(r){if(!Be)return{client:{},quoteUsd:async()=>({tokenAmountDecimals:"0"}),sendUsd:async()=>({transactionId:"0",status:"pending"}),startOnrampUsd:async()=>({transactionId:"0",status:"pending",metadata:{icpay_onramp:{sessionId:null}}}),notifyIntentUntilComplete:()=>({stop:()=>{}})};me(r.debug||!1,"Creating SDK with config:",r);let l={publishableKey:r.publishableKey};r.enableEvents!==void 0?l.enableEvents=r.enableEvents:l.enableEvents=!0,r.apiUrl&&(l.apiUrl=r.apiUrl),r.icHost&&(l.icHost=r.icHost),r.actorProvider&&(l.actorProvider=r.actorProvider),r.connectedWallet&&(l.connectedWallet=r.connectedWallet),r.evmProvider&&(l.evmProvider=r.evmProvider),r.solanaProvider&&(l.solanaProvider=r.solanaProvider),r.onrampDisabled!==void 0&&(l.onrampDisabled=r.onrampDisabled),r.debug!==void 0&&(l.debug=r.debug),r.fiat_currency!=null&&r.fiat_currency!==""&&(l.fiat_currency=r.fiat_currency),r.paymentIntent!=null&&typeof r.paymentIntent=="object"&&(l.paymentIntent=r.paymentIntent),r.paymentIntentId!=null&&typeof r.paymentIntentId=="string"&&(l.paymentIntentId=r.paymentIntentId),me(r.debug||!1,"Filtered SDK config:",l);try{let o=function(c,d,p){return t.notifyPaymentIntentOnRamp({paymentIntentId:c,intervalMs:d,orderId:p})};var e=o;me(r.debug||!1,"typeof Icpay:",typeof $e);let t=new $e(l);if(Be){let c=t,d=p=>{c.addEventListener(p,y=>{window.dispatchEvent(new CustomEvent(p,{detail:y?.detail??y}))})};["icpay-sdk-error","icpay-sdk-transaction-created","icpay-sdk-transaction-updated","icpay-sdk-transaction-completed","icpay-sdk-transaction-failed","icpay-sdk-method-start","icpay-sdk-method-success","icpay-sdk-method-error"].forEach(d)}async function n(c,d,p){if(typeof d=="string"&&d.trim().length>0)return t.calculateTokenAmountFromUSD({usdAmount:c,tokenShortcode:d.toLowerCase()});if(typeof p=="string"&&p.trim().length>0)return t.calculateTokenAmountFromUSD({usdAmount:c,ledgerCanisterId:p});throw new Error("quoteUsd requires tokenShortcode or ledgerCanisterId")}async function a(c,d,p,y){let h={...r.metadata,...p||{}};r.externalCostAmount!=null&&h.externalCostAmount==null&&(h.externalCostAmount=r.externalCostAmount);let u=`Pay ${c} with crypto`,m=r.description||h.__description||h.description||u,j={usdAmount:c,metadata:h,description:m,recipientAddresses:r.recipientAddresses,recipientAddress:r.recipientAddress};if(r.fiat_currency!=null&&r.fiat_currency!==""&&(j.fiat_currency=r.fiat_currency),typeof d=="string"&&d.trim().length>0&&(j.tokenShortcode=d.toLowerCase()),typeof y=="string"&&y.trim().length>0&&(j.ledgerCanisterId=y),!j.tokenShortcode&&!j.ledgerCanisterId)throw new Error("sendUsd requires tokenShortcode or ledgerCanisterId");return me(!!r.debug,"Calling createPaymentUsd (flow decision handled by components)",j),t.createPaymentUsd(j)}async function i(c,d,p){let y={...r.metadata,...p||{}},h=`Pay ${c} with crypto`,u=r.description||y.__description||y.description||h;me(!!r.debug,"Calling onramp createPaymentUsd",{usdAmount:c,ledgerCanisterId:d,description:u});let m={usdAmount:c,ledgerCanisterId:d,metadata:y,onrampPayment:!0,description:u,recipientAddresses:r.recipientAddresses,recipientAddress:""};return r.fiat_currency!=null&&r.fiat_currency!==""&&(m.fiat_currency=r.fiat_currency),t.createPaymentUsd(m)}return{client:t,quoteUsd:n,sendUsd:a,startOnrampUsd:i,notifyIntentUntilComplete:o}}catch(t){throw me(r.debug||!1,"Error creating SDK:",t),t}}import{LitElement as tt,html as D,css as nt}from"lit";import{customElement as at,property as le,state as z}from"lit/decorators.js";import{IcpayError as Re}from"@ic-pay/icpay-sdk";var te={WALLET_NOT_CONNECTED:"WALLET_NOT_CONNECTED",WALLET_USER_CANCELLED:"WALLET_USER_CANCELLED",WALLET_SIGNATURE_REJECTED:"WALLET_SIGNATURE_REJECTED",INSUFFICIENT_BALANCE:"INSUFFICIENT_BALANCE",NETWORK_ERROR:"NETWORK_ERROR",API_ERROR:"API_ERROR",LEDGER_NOT_FOUND:"LEDGER_NOT_FOUND",TRANSACTION_FAILED:"TRANSACTION_FAILED",TRANSACTION_TIMEOUT:"TRANSACTION_TIMEOUT",UNKNOWN_ERROR:"UNKNOWN_ERROR"},Je={onError:r=>{console.error("[ICPay Widget] Error:",r)},onUserCancelled:()=>{console.log("[ICPay Widget] User cancelled the action")},onInsufficientBalance:r=>{console.warn("[ICPay Widget] Insufficient balance:",r.message)},onWalletError:r=>{console.warn("[ICPay Widget] Wallet error:",r.message)},onNetworkError:r=>{console.error("[ICPay Widget] Network error:",r.message)}};function f(r,l=Je){r instanceof Re?(l.onError(r),r.isUserCancelled()?l.onUserCancelled?.():r.isBalanceError()?l.onInsufficientBalance?.(r):r.isWalletError()?l.onWalletError?.(r):r.isNetworkError()&&l.onNetworkError?.(r)):(console.error("[ICPay Widget] Unknown error:",r),l.onError(new Re({code:te.UNKNOWN_ERROR,message:r instanceof Error?r.message:"An unknown error occurred",details:r})))}var et={[te.WALLET_NOT_CONNECTED]:"Please connect your wallet to continue",[te.WALLET_USER_CANCELLED]:"User have rejected the transfer",[te.WALLET_SIGNATURE_REJECTED]:"User have rejected the transfer",[te.INSUFFICIENT_BALANCE]:"Insufficient balance for this transaction",[te.NETWORK_ERROR]:"Network error. Please try again",[te.API_ERROR]:"Service temporarily unavailable",[te.LEDGER_NOT_FOUND]:"Selected token is not supported",[te.TRANSACTION_FAILED]:"Transaction failed. Please try again",[te.TRANSACTION_TIMEOUT]:"Transaction timed out. Please try again",[te.UNKNOWN_ERROR]:"Something went wrong. Please try again"};function g(r){let l=r?.details||{},e=typeof l?.data?.message=="string"?l.data.message:void 0,t=typeof l?.message=="string"?l.message:void 0,n=e||t;if(n&&n.length>0){if(n.startsWith("missing_required_fields:")){let o=(n.split(":")[1]||"").split(",").map(c=>c.trim()).filter(Boolean);return o.length?`Missing required: ${o.join(", ")}`:"Missing required fields"}let a=n.match(/^Missing required fields:\s*(.+)$/i);if(a&&a[1]){let i=a[1].split(",").map(o=>o.trim()).filter(Boolean);return i.length?`Missing required: ${i.join(", ")}`:"Missing required fields"}return n}return et[r.code]||r.message||"An error occurred"}function v(r){return!r.isUserCancelled()}function w(r){return null}function b(r){return r.isUserCancelled()?"info":r.isBalanceError()||r.isWalletError()?"warning":"error"}function M(r,l,e){r&&(e!==void 0?console.log(l,e):console.log(l))}var it=[{key:"wallet",label:"Connect wallet",tooltip:"Awaiting wallet connection",status:"pending"},{key:"await",label:"Awaiting confirmation",tooltip:"Awaiting wallet signature",status:"pending"},{key:"transfer",label:"Transferring funds",tooltip:"Awaiting transfer to merchant",status:"pending"},{key:"verify",label:"Verifying payment",tooltip:"Please wait while we verify",status:"pending"}],S=class extends tt{constructor(){super(...arguments);this.open=!1;this.suspended=!1;this.steps=it;this.amount=0;this.currency="";this.ledgerSymbol="";this.debug=!1;this.activeIndex=0;this.completed=!1;this.failed=!1;this.errorMessage=null;this.showSuccess=!1;this.showConfetti=!1;this.currentSteps=[];this.currentAmount=0;this.currentCurrency="";this.currentLedgerSymbol="";this.currentFiatCode="";this.currentFiatSymbol=null;this.confirmLoadingStartedAt=null;this.progressionTimer=null;this.currentWalletType=null;this.showWalletSelector=!1;this.isTransitioning=!1;this.isOnrampFlow=!1;this.onPaymentReset=()=>{this.stopAutomaticProgression(),this.open=!1,this.showWalletSelector=!1,this.isTransitioning=!1,this.activeIndex=0,this.completed=!1,this.failed=!1,this.errorMessage=null,this.showSuccess=!1,this.showConfetti=!1,this.isOnrampFlow=!1,this.currentSteps=[...this.steps].map(e=>({...e,status:"pending"})),this.requestUpdate()};this.onMethodStart=e=>{let t=e?.detail?.name||"",n=e?.detail?.type||"";if(M(this.debug,"ICPay Progress: Method start event received:",e.detail),t==="createPayment"||t==="createPaymentUsd"||t==="sendUsd"||t==="pay"||t==="unlock"||t==="tip"||t==="donate"||t==="order"){if(this.open=!0,this.activeIndex=0,this.completed=!1,this.failed=!1,this.errorMessage=null,this.showSuccess=!1,this.showConfetti=!1,this.showWalletSelector=!1,this.isTransitioning=!1,this.currentSteps=this.currentSteps.map(a=>({...a,status:"pending"})),n==="onramp"){this.isOnrampFlow=!0;let a={wallet:{label:"Payment initiated",tooltip:"Please pay in the new tab"},await:{label:"Onramp process started",tooltip:"Verifying funds with provider"},transfer:{label:"Funds received",tooltip:"Payment in progress"},verify:{label:"Payment completed",tooltip:"Finalizing your payment"}};this.currentSteps=this.currentSteps.map(i=>a[i.key]?{...i,label:a[i.key].label,tooltip:a[i.key].tooltip}:i)}this.setLoadingByKey("wallet"),e?.detail?.amount!==void 0&&(this.currentAmount=e.detail.amount,this.amount=e.detail.amount,M(this.debug,"ICPay Progress: Amount updated to:",e.detail.amount)),e?.detail?.currency&&(this.currentCurrency=e.detail.currency,this.currency=e.detail.currency,M(this.debug,"ICPay Progress: Currency updated to:",e.detail.currency)),e?.detail?.ledgerSymbol&&(this.currentLedgerSymbol=e.detail.ledgerSymbol,this.ledgerSymbol=e.detail.ledgerSymbol,M(this.debug,"ICPay Progress: Current state after method start:",{activeIndex:this.activeIndex,currentAmount:this.currentAmount,currentCurrency:this.currentCurrency,currentLedgerSymbol:this.currentLedgerSymbol})),M(this.debug,"ICPay Progress: Waiting for wallet confirmation before starting progression"),this.requestUpdate()}!this.failed&&!this.completed&&(t==="createPaymentX402Usd"?(this.completeByKey("wallet"),this.setLoadingByKey("await")):t==="sendFundsToLedger"?(this.completeByKey("wallet"),this.completeByKey("await"),this.setLoadingByKey("transfer")):t==="notifyLedgerTransaction"?(this.completeByKey("wallet"),this.completeByKey("await"),this.setLoadingByKey("transfer")):t==="settleX402"&&(this.completeByKey("wallet"),this.completeByKey("await"),this.setLoadingByKey("transfer")))};this.onMethodSuccess=e=>{let t=e?.detail?.name||"";if((t==="createPayment"||t==="createPaymentUsd"||t==="sendUsd"||t==="pay"||t==="unlock"||t==="tip"||t==="donate"||t==="order")&&this.dispatchEvent(new CustomEvent("icpay-progress-method-success",{detail:{methodName:t,step:this.activeIndex},bubbles:!0})),!this.failed&&!this.completed){if(this.isOnrampFlow)return;t==="getLedgerBalance"?(this.completeByKey("wallet"),this.setLoadingByKey("await")):t==="sendFundsToLedger"?(this.completeByKey("wallet"),this.completeByKey("await"),this.completeByKey("transfer"),this.setLoadingByKey("verify")):t==="notifyLedgerTransaction"?(this.completeByKey("wallet"),this.completeByKey("await"),this.completeByKey("transfer"),this.setLoadingByKey("verify")):t==="createPaymentX402Usd"&&(this.completeByKey("wallet"),this.completeByKey("await"),this.completeByKey("transfer"),this.setLoadingByKey("verify"))}};this.onTransactionCreated=e=>{let t=e?.detail?.transactionId||e?.detail?.id;if(M(this.debug,"ICPay Progress: Transaction created event received:",e.detail),!this.failed&&!this.completed){if(this.isOnrampFlow)return;this.completeByKey("wallet"),this.completeByKey("await"),this.setLoadingByKey("transfer")}this.dispatchEvent(new CustomEvent("icpay-progress-transaction-created",{detail:{transactionId:t,step:this.activeIndex},bubbles:!0}))};this.onTransactionUpdated=e=>{let t=e?.detail?.status||"pending",n=e?.detail?.transactionId||e?.detail?.id,a=e?.detail?.metadata||e?.detail?.intent?.metadata||{};if(M(this.debug,"ICPay Progress: Transaction updated event received:",e.detail),!this.failed&&!this.completed&&this.isOnrampFlow){let i=a?.onramp_order_completed===!0||a?.icpay_onramp?.status==="completed"||a?.onrampCompleted===!0;t==="requires_payment"&&!i?(this.completeByKey("wallet"),this.setLoadingByKey("await")):(t==="pending"||t==="processing"||i)&&(this.completeByKey("wallet"),this.completeByKey("await"),this.setLoadingByKey("transfer"))}this.dispatchEvent(new CustomEvent("icpay-progress-transaction-updated",{detail:{status:t,transactionId:n,step:this.activeIndex},bubbles:!0}))};this.onTransactionCompleted=e=>{let t=e?.detail?.transactionId||e?.detail?.id,n=e?.detail?.status||"completed",a=e?.detail?.paymentIntent??e?.detail?.payment?.paymentIntent;a&&typeof a=="object"&&(a.fiatCurrencyCode!=null&&a.fiatCurrencyCode!==""&&(this.currentFiatCode=String(a.fiatCurrencyCode)),a.fiatCurrencySymbol!=null&&a.fiatCurrencySymbol!==""&&(this.currentFiatSymbol=String(a.fiatCurrencySymbol))),M(this.debug,"ICPay Progress: Transaction completed event received:",e.detail),M(this.debug,"ICPay Progress: Current state when transaction completed:",{activeIndex:this.activeIndex,completed:this.completed,failed:this.failed,showSuccess:this.showSuccess}),this.completeByKey("transfer"),this.completeByKey("await"),this.completeByKey("verify"),this.completed=!0,this.showSuccess=!0,this.showConfetti=!0,this.isOnrampFlow=!1,this.dispatchEvent(new CustomEvent("icpay-progress-completed",{detail:{transactionId:t,status:n,amount:this.currentAmount||this.amount,currency:this.currentCurrency||this.currency,ledgerSymbol:this.currentLedgerSymbol||this.ledgerSymbol},bubbles:!0})),setTimeout(()=>{this.showConfetti=!1},3e3)};this.onTransactionFailed=e=>{let t=e?.detail?.error,n=e?.detail?.message||e?.detail?.error?.message||"Transaction failed",a=t?g(t):this.transformErrorMessage(n),i=e?.detail?.error?.code||e?.detail?.code||"UNKNOWN_ERROR",o=e?.detail?.transactionId||e?.detail?.id;M(this.debug,"ICPay Progress: Transaction failed event received:",e.detail),this.failed=!0,this.errorMessage=this.preferSpecificError(this.errorMessage,a),this.showSuccess=!1,this.updateStepStatus(this.activeIndex,"error",this.errorMessage),this.stopAutomaticProgression(),this.open=!0,this.isOnrampFlow=!1,this.dispatchEvent(new CustomEvent("icpay-progress-failed",{detail:{errorMessage:this.errorMessage,errorCode:i,transactionId:o,step:this.activeIndex},bubbles:!0}))};this.onTransactionMismatched=e=>{let t=e?.detail?.requestedAmount,n=e?.detail?.paidAmount,a=e?.detail?.transactionId||e?.detail?.id;this.failed=!0;let i=t!=null?String(t):"unknown",o=n!=null?String(n):"unknown";this.errorMessage=`Amount mismatch. Requested ${i}, paid ${o}.`,this.showSuccess=!1,this.updateStepStatus(this.activeIndex,"error",this.errorMessage),this.stopAutomaticProgression(),this.open=!0,this.isOnrampFlow=!1,this.dispatchEvent(new CustomEvent("icpay-progress-failed",{detail:{errorMessage:this.errorMessage,errorCode:"MISMATCHED_AMOUNT",transactionId:a,step:this.activeIndex,requestedAmount:t,paidAmount:n},bubbles:!0}))};this.onMethodError=e=>{let t=e?.detail?.name||"",n=e?.detail?.error,a=e?.detail?.message||n&&n.message||"An error occurred",i=n?g(n):this.transformErrorMessage(a),o=e?.detail?.error?.code||e?.detail?.code||"METHOD_ERROR";M(this.debug,"ICPay Progress: Method error event received:",e.detail),(t?.startsWith("createPayment")||t==="sendUsd"||t==="pay"||t==="unlock"||t==="tip"||t==="donate"||t==="order")&&(this.failed=!0,this.errorMessage=this.preferSpecificError(this.errorMessage,i),this.showSuccess=!1,this.updateStepStatus(this.activeIndex,"error",this.errorMessage),this.stopAutomaticProgression(),this.open=!0,this.isOnrampFlow=!1,this.dispatchEvent(new CustomEvent("icpay-progress-error",{detail:{methodName:t,errorMessage:this.errorMessage,errorCode:o,step:this.activeIndex},bubbles:!0})))};this.onSDKError=e=>{let t=e?.detail?.error,n=e?.detail?.message||t&&t.message||"SDK error occurred",a=t?g(t):this.transformErrorMessage(n),i=e?.detail?.code||"SDK_ERROR";M(this.debug,"ICPay Progress: SDK error event received:",e.detail),this.failed=!0,this.errorMessage=this.preferSpecificError(this.errorMessage,a),this.showSuccess=!1,this.updateStepStatus(this.activeIndex,"error",this.errorMessage),this.stopAutomaticProgression(),this.open=!0,this.isOnrampFlow=!1,this.dispatchEvent(new CustomEvent("icpay-progress-sdk-error",{detail:{errorMessage:this.errorMessage,errorCode:i,step:this.activeIndex},bubbles:!0}))};this.onWalletConnected=e=>{let t=e?.detail?.walletType||"unknown";M(this.debug,"ICPay Progress: Wallet connected event received:",e.detail),this.completeByKey("wallet"),this.setLoadingByKey("await"),this.startTransitionToProgress(),this.dispatchEvent(new CustomEvent("icpay-progress-wallet-connected",{detail:{walletType:t,step:this.activeIndex},bubbles:!0})),this.currentWalletType=t};this.onOnrampOpened=e=>{!this.isOnrampFlow||this.failed||this.completed||(this.completeByKey("wallet"),this.setLoadingByKey("await"))};this.onWalletDisconnected=e=>{let t=e?.detail?.walletType||"unknown";M(this.debug,"ICPay Progress: Wallet disconnected event received:",e.detail),this.dispatchEvent(new CustomEvent("icpay-progress-wallet-disconnected",{detail:{walletType:t,step:this.activeIndex},bubbles:!0})),this.currentWalletType=null};this.onBalanceCheck=e=>{let t=e?.detail?.hasBalance||!1,n=e?.detail?.balance||0;M(this.debug,"ICPay Progress: Balance check event received:",e.detail),t||(this.failed=!0,this.errorMessage="Insufficient balance for transaction",this.updateStepStatus(this.activeIndex,"error","Insufficient balance for transaction"),this.stopAutomaticProgression(),this.showWalletSelector=!1,this.dispatchEvent(new CustomEvent("icpay-progress-insufficient-balance",{detail:{balance:n,required:this.currentAmount||this.amount,step:this.activeIndex},bubbles:!0})))};this.onLedgerVerified=e=>{let t=e?.detail?.ledgerId||e?.detail?.canisterId,n=e?.detail?.symbol||"unknown";M(this.debug,"ICPay Progress: Ledger verified event received:",e.detail),n&&n!=="unknown"&&(this.currentLedgerSymbol=n,this.ledgerSymbol=n),this.dispatchEvent(new CustomEvent("icpay-progress-ledger-verified",{detail:{ledgerId:t,symbol:n,step:this.activeIndex},bubbles:!0}))};this.onWidgetPayment=e=>{let t=e?.detail?.amount,n=e?.detail?.currency,a=e?.detail?.ledgerSymbol;if(M(this.debug,"ICPay Progress: Widget payment event received:",e.detail),t!==void 0&&(this.currentAmount=t,this.amount=t),n&&(this.currentCurrency=n,this.currency=n),a&&(this.currentLedgerSymbol=a,this.ledgerSymbol=a),!this.failed){for(let i=this.activeIndex;i<this.currentSteps.length;i++)this.updateStepStatus(i,"completed");this.activeIndex=this.currentSteps.length-1,this.completed=!0,this.showSuccess=!0,this.showConfetti=!0}this.dispatchEvent(new CustomEvent("icpay-progress-widget-payment",{detail:{amount:t,currency:n,ledgerSymbol:a,step:this.activeIndex},bubbles:!0}))};this.onWidgetError=e=>{let t=e?.detail?.error||e?.detail,n=t&&t.message||e?.detail?.message||"Widget error occurred",a=t?g(t):this.transformErrorMessage(n),i=t&&t.code||e?.detail?.code||"WIDGET_ERROR";M(this.debug,"ICPay Progress: Widget error event received:",e.detail),this.failed=!0,this.errorMessage=this.preferSpecificError(this.errorMessage,a),this.showSuccess=!1,this.updateStepStatus(this.activeIndex,"error",this.errorMessage),this.stopAutomaticProgression(),this.open=!0,this.dispatchEvent(new CustomEvent("icpay-progress-widget-error",{detail:{errorMessage:this.errorMessage,errorCode:i,step:this.activeIndex},bubbles:!0}))};this.onWidgetUnlock=e=>{let t=e?.detail?.amount,n=e?.detail?.currency;if(M(this.debug,"ICPay Progress: Widget unlock event received:",e.detail),!this.failed){for(let a=this.activeIndex;a<this.currentSteps.length;a++)this.updateStepStatus(a,"completed");this.activeIndex=this.currentSteps.length-1,this.completed=!0,this.showSuccess=!0,this.showConfetti=!0}this.dispatchEvent(new CustomEvent("icpay-progress-widget-unlock",{detail:{amount:t,currency:n,step:this.activeIndex},bubbles:!0}))};this.onWidgetTip=e=>{let t=e?.detail?.amount,n=e?.detail?.currency;if(M(this.debug,"ICPay Progress: Widget tip event received:",e.detail),!this.failed){for(let a=this.activeIndex;a<this.currentSteps.length;a++)this.updateStepStatus(a,"completed");this.activeIndex=this.currentSteps.length-1,this.completed=!0,this.showSuccess=!0,this.showConfetti=!0}this.dispatchEvent(new CustomEvent("icpay-progress-widget-tip",{detail:{amount:t,currency:n,step:this.activeIndex},bubbles:!0}))};this.onWidgetDonation=e=>{let t=e?.detail?.amount,n=e?.detail?.currency;if(M(this.debug,"ICPay Progress: Widget donation event received:",e.detail),!this.failed){for(let a=this.activeIndex;a<this.currentSteps.length;a++)this.updateStepStatus(a,"completed");this.activeIndex=this.currentSteps.length-1,this.completed=!0,this.showSuccess=!0,this.showConfetti=!0}this.dispatchEvent(new CustomEvent("icpay-progress-widget-donation",{detail:{amount:t,currency:n,step:this.activeIndex},bubbles:!0}))};this.onWidgetCoffee=e=>{let t=e?.detail?.amount,n=e?.detail?.currency;if(M(this.debug,"ICPay Progress: Widget coffee event received:",e.detail),!this.failed){for(let a=this.activeIndex;a<this.currentSteps.length;a++)this.updateStepStatus(a,"completed");this.activeIndex=this.currentSteps.length-1,this.completed=!0,this.showSuccess=!0,this.showConfetti=!0}this.dispatchEvent(new CustomEvent("icpay-progress-widget-coffee",{detail:{amount:t,currency:n,step:this.activeIndex},bubbles:!0}))};this.onWalletCancelled=e=>{try{let t=this.getStepIndexByKey("wallet"),n=this.getStepIndexByKey("await"),a=this.getStepIndexByKey("transfer"),i=this.getStepIndexByKey("verify"),o=this.currentSteps&&this.currentSteps.length>0&&this.currentSteps.some((p,y)=>t>=0&&y>t?p.status==="loading"||p.status==="completed":!1),d=(t>=0?this.currentSteps[t]:null)?.status==="completed";if(!o&&!d){this.open=!1,this.activeIndex=0,this.currentSteps=this.currentSteps.map(p=>({...p,status:"pending"})),this.requestUpdate();return}this.open=!0,t>=0&&(this.activeIndex=t,this.currentSteps[t]={...this.currentSteps[t],tooltip:"Wallet connection cancelled",status:"error"},this.requestUpdate())}catch{}};this.onWalletError=e=>{try{let t=e?.detail?.message||"Wallet error",n=this.transformErrorMessage(t);this.open=!0;let a=this.getStepIndexByKey("wallet");a>=0&&(this.activeIndex=a,this.currentSteps[a]={...this.currentSteps[a],tooltip:"Wallet connection failed",status:"error",errorMessage:n},this.requestUpdate())}catch{}}}connectedCallback(){super.connectedCallback();try{ge(this,this.theme);let e="light";if(typeof this.theme=="string")e=this.theme;else if(this.theme&&typeof this.theme=="object"&&this.theme.mode)e=this.theme.mode;else if(typeof document<"u"){let t=document.documentElement.getAttribute("data-icpay-theme")||document.documentElement.getAttribute("data-theme");(t==="light"||t==="dark")&&(e=t)}this.setAttribute("data-theme",e)}catch{}this.currentSteps=[...this.steps],this.currentAmount=this.amount,this.currentCurrency=this.currency,this.currentLedgerSymbol=this.ledgerSymbol,this.attachSDKEventListeners()}disconnectedCallback(){super.disconnectedCallback(),this.detachSDKEventListeners(),this.stopAutomaticProgression()}updated(e){if(e.has("theme"))try{ge(this,this.theme);let t="light";if(typeof this.theme=="string")t=this.theme;else if(this.theme&&typeof this.theme=="object"&&this.theme.mode)t=this.theme.mode;else if(typeof document<"u"){let n=document.documentElement.getAttribute("data-icpay-theme")||document.documentElement.getAttribute("data-theme");(n==="light"||n==="dark")&&(t=n)}this.setAttribute("data-theme",t)}catch{}}attachSDKEventListeners(){window.addEventListener("icpay-sdk-method-start",this.onMethodStart),window.addEventListener("icpay-sdk-method-success",this.onMethodSuccess),window.addEventListener("icpay-sdk-method-error",this.onMethodError),window.addEventListener("icpay-sdk-wallet-cancelled",this.onWalletCancelled),window.addEventListener("icpay-sdk-wallet-error",this.onWalletError),window.addEventListener("icpay-sdk-transaction-created",this.onTransactionCreated),window.addEventListener("icpay-sdk-transaction-updated",this.onTransactionUpdated),window.addEventListener("icpay-sdk-transaction-completed",this.onTransactionCompleted),window.addEventListener("icpay-sdk-transaction-failed",this.onTransactionFailed),window.addEventListener("icpay-sdk-transaction-mismatched",this.onTransactionMismatched),window.addEventListener("icpay-onramp-opened",this.onOnrampOpened),window.addEventListener("icpay-sdk-error",this.onSDKError),window.addEventListener("icpay-sdk-wallet-connected",this.onWalletConnected),window.addEventListener("icpay-sdk-wallet-disconnected",this.onWalletDisconnected),window.addEventListener("icpay-sdk-balance-check",this.onBalanceCheck),window.addEventListener("icpay-sdk-ledger-verified",this.onLedgerVerified),window.addEventListener("icpay-pay",this.onWidgetPayment),window.addEventListener("icpay-error",this.onWidgetError),window.addEventListener("icpay-unlock",this.onWidgetUnlock),window.addEventListener("icpay-tip",this.onWidgetTip),window.addEventListener("icpay-donation",this.onWidgetDonation),window.addEventListener("icpay-coffee",this.onWidgetCoffee),window.addEventListener("icpay-payment-reset",this.onPaymentReset)}detachSDKEventListeners(){window.removeEventListener("icpay-sdk-method-start",this.onMethodStart),window.removeEventListener("icpay-sdk-method-success",this.onMethodSuccess),window.removeEventListener("icpay-sdk-method-error",this.onMethodError),window.removeEventListener("icpay-sdk-wallet-cancelled",this.onWalletCancelled),window.removeEventListener("icpay-sdk-wallet-error",this.onWalletError),window.removeEventListener("icpay-sdk-transaction-created",this.onTransactionCreated),window.removeEventListener("icpay-sdk-transaction-updated",this.onTransactionUpdated),window.removeEventListener("icpay-sdk-transaction-completed",this.onTransactionCompleted),window.removeEventListener("icpay-sdk-transaction-failed",this.onTransactionFailed),window.removeEventListener("icpay-sdk-transaction-mismatched",this.onTransactionMismatched),window.removeEventListener("icpay-onramp-opened",this.onOnrampOpened),window.removeEventListener("icpay-sdk-error",this.onSDKError),window.removeEventListener("icpay-sdk-wallet-connected",this.onWalletConnected),window.removeEventListener("icpay-sdk-wallet-disconnected",this.onWalletDisconnected),window.removeEventListener("icpay-sdk-balance-check",this.onBalanceCheck),window.removeEventListener("icpay-sdk-ledger-verified",this.onLedgerVerified),window.removeEventListener("icpay-pay",this.onWidgetPayment),window.removeEventListener("icpay-error",this.onWidgetError),window.removeEventListener("icpay-unlock",this.onWidgetUnlock),window.removeEventListener("icpay-tip",this.onWidgetTip),window.removeEventListener("icpay-donation",this.onWidgetDonation),window.removeEventListener("icpay-coffee",this.onWidgetCoffee),window.removeEventListener("icpay-payment-reset",this.onPaymentReset)}startAutomaticProgression(){this.progressionTimer&&clearInterval(this.progressionTimer),this.activeIndex=1,this.updateStepStatus(this.activeIndex,"loading"),M(this.debug,"ICPay Progress: Starting automatic progression from step:",this.activeIndex),this.progressionTimer=setInterval(()=>{if(this.failed||this.completed){this.stopAutomaticProgression();return}M(this.debug,"ICPay Progress: Processing step:",this.activeIndex),this.updateStepStatus(this.activeIndex,"completed"),this.activeIndex<this.currentSteps.length-1?(this.activeIndex++,this.updateStepStatus(this.activeIndex,"loading"),M(this.debug,"ICPay Progress: Auto-progressed to step:",this.activeIndex)):(this.stopAutomaticProgression(),M(this.debug,"ICPay Progress: All steps completed, waiting for transaction completion")),this.requestUpdate()},3e3)}stopAutomaticProgression(){this.progressionTimer&&(clearInterval(this.progressionTimer),this.progressionTimer=null)}updateStepStatus(e,t,n){if(e>=0&&e<this.currentSteps.length){let a=this.currentSteps[e],i=a.status;a.status=t,t==="completed"&&(a.timestamp=this.getCurrentTime()),t==="error"&&n&&(a.errorMessage=this.transformErrorMessage(n)),i!==t&&M(this.debug,`ICPay Progress: Step ${e} (${a.label}) status changed from ${i} to ${t}`),this.requestUpdate()}}getCurrentTime(){return new Date().toLocaleTimeString("en-US",{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"})}getStepIcon(e){return e.status==="error"?D`<div class="error-x">✕</div>`:D`<div class="spinner"></div>`}getStepIndexByKey(e){return this.currentSteps.findIndex(t=>t.key===e)}setLoadingByKey(e){let t=this.getStepIndexByKey(e);t>=0&&(this.activeIndex=t,this.updateStepStatus(t,"loading"),e==="verify"&&(this.confirmLoadingStartedAt=Date.now()))}completeByKey(e){let t=this.getStepIndexByKey(e);t>=0&&(this.updateStepStatus(t,"completed"),this.activeIndex=t)}transformErrorMessage(e){let t=String(e||"").toLowerCase();return t.includes("user rejected")||t.includes("user cancelled")||t.includes("user canceled")||t.includes("signature rejected")?"User have rejected the transfer":e}isGenericErrorText(e){if(!e)return!0;let t=e.toLowerCase();return t==="an error occurred"||t==="sdk error occurred"||t==="transaction failed"||t.includes("failed to create payment")||t.includes("wallet error")||t.includes("network error")}preferSpecificError(e,t){let n=this.transformErrorMessage(t||"");return e&&!this.isGenericErrorText(e)&&this.isGenericErrorText(n)?e:n}renderConfetti(){if(!this.showConfetti)return"";let e=Array.from({length:50},(n,a)=>a),t=["#0066FF","#ef4444","#10b981","#f59e0b","#8b5cf6"];return D`
146
+ `;function Yt(r){return typeof r=="string"?r:r&&typeof r=="object"&&r.mode?r.mode:"light"}function fe(r,l){if(!r)return;let e=null,t="light";if(typeof l=="string")t=l,e={mode:t};else if(l&&typeof l=="object")e=l,t=l.mode||"light";else if(typeof document<"u"){let n=document.documentElement.getAttribute("data-icpay-theme")||document.documentElement.getAttribute("data-theme");(n==="light"||n==="dark")&&(t=n)}if(r instanceof HTMLElement&&r.setAttribute("data-theme",t),typeof document<"u"&&document.documentElement&&(document.documentElement.setAttribute("data-icpay-theme",t),document.documentElement.style.setProperty("--icpay-theme-mode",t)),!e)return;let a=(n,i)=>{i&&r.style.setProperty(n,i)};e.primaryColor&&a("--icpay-primary",e.primaryColor),e.secondaryColor&&a("--icpay-secondary",e.secondaryColor),e.accentColor&&a("--icpay-accent",e.accentColor),e.textColor&&a("--icpay-foreground",e.textColor),e.mutedTextColor&&a("--icpay-muted-foreground",e.mutedTextColor),e.surfaceColor&&a("--icpay-background",e.surfaceColor),e.surfaceAltColor&&a("--icpay-secondary",e.surfaceAltColor),e.borderColor&&a("--icpay-border",e.borderColor),e.fontFamily&&a("--icpay-font",e.fontFamily),e.textColor&&a("--icpay-text",e.textColor),e.mutedTextColor&&a("--icpay-muted",e.mutedTextColor),e.surfaceAltColor&&a("--icpay-surface-alt",e.surfaceAltColor)}import{Icpay as Re}from"@ic-pay/icpay-sdk";var Fe=typeof window<"u";function ve(r,l,e){r&&(e!==void 0?console.log(`[ICPay Widget] ${l}`,e):console.log(`[ICPay Widget] ${l}`))}function E(r){if(!Fe)return{client:{},quoteUsd:async()=>({tokenAmountDecimals:"0"}),sendUsd:async()=>({transactionId:"0",status:"pending"}),startOnrampUsd:async()=>({transactionId:"0",status:"pending",metadata:{icpay_onramp:{sessionId:null}}}),notifyIntentUntilComplete:()=>({stop:()=>{}})};ve(r.debug||!1,"Creating SDK with config:",r);let l={publishableKey:r.publishableKey};r.enableEvents!==void 0?l.enableEvents=r.enableEvents:l.enableEvents=!0,r.apiUrl&&(l.apiUrl=r.apiUrl),r.icHost&&(l.icHost=r.icHost),r.actorProvider&&(l.actorProvider=r.actorProvider),r.connectedWallet&&(l.connectedWallet=r.connectedWallet),r.evmProvider&&(l.evmProvider=r.evmProvider),r.solanaProvider&&(l.solanaProvider=r.solanaProvider),r.onrampDisabled!==void 0&&(l.onrampDisabled=r.onrampDisabled),r.debug!==void 0&&(l.debug=r.debug),r.fiat_currency!=null&&r.fiat_currency!==""&&(l.fiat_currency=r.fiat_currency),r.paymentIntent!=null&&typeof r.paymentIntent=="object"&&(l.paymentIntent=r.paymentIntent),r.paymentIntentId!=null&&typeof r.paymentIntentId=="string"&&(l.paymentIntentId=r.paymentIntentId),ve(r.debug||!1,"Filtered SDK config:",l);try{let s=function(o,d,p){return t.notifyPaymentIntentOnRamp({paymentIntentId:o,intervalMs:d,orderId:p})};var e=s;ve(r.debug||!1,"typeof Icpay:",typeof Re);let t=new Re(l);if(Fe){let o=t,d=p=>{o.addEventListener(p,y=>{window.dispatchEvent(new CustomEvent(p,{detail:y?.detail??y}))})};["icpay-sdk-error","icpay-sdk-transaction-created","icpay-sdk-transaction-updated","icpay-sdk-transaction-completed","icpay-sdk-transaction-failed","icpay-sdk-method-start","icpay-sdk-method-success","icpay-sdk-method-error"].forEach(d)}async function a(o,d,p){if(typeof d=="string"&&d.trim().length>0)return t.calculateTokenAmountFromUSD({usdAmount:o,tokenShortcode:d.toLowerCase()});if(typeof p=="string"&&p.trim().length>0)return t.calculateTokenAmountFromUSD({usdAmount:o,ledgerCanisterId:p});throw new Error("quoteUsd requires tokenShortcode or ledgerCanisterId")}async function n(o,d,p,y){let h={...r.metadata,...p||{}};r.externalCostAmount!=null&&h.externalCostAmount==null&&(h.externalCostAmount=r.externalCostAmount);let u=`Pay ${o} with crypto`,g=r.description||h.__description||h.description||u,M={usdAmount:o,metadata:h,description:g,recipientAddresses:r.recipientAddresses,recipientAddress:r.recipientAddress};if(r.fiat_currency!=null&&r.fiat_currency!==""&&(M.fiat_currency=r.fiat_currency),typeof d=="string"&&d.trim().length>0&&(M.tokenShortcode=d.toLowerCase()),typeof y=="string"&&y.trim().length>0&&(M.ledgerCanisterId=y),!M.tokenShortcode&&!M.ledgerCanisterId)throw new Error("sendUsd requires tokenShortcode or ledgerCanisterId");return ve(!!r.debug,"Calling createPaymentUsd (flow decision handled by components)",M),t.createPaymentUsd(M)}async function i(o,d,p){let y={...r.metadata,...p||{}},h=`Pay ${o} with crypto`,u=r.description||y.__description||y.description||h;ve(!!r.debug,"Calling onramp createPaymentUsd",{usdAmount:o,ledgerCanisterId:d,description:u});let g={usdAmount:o,ledgerCanisterId:d,metadata:y,onrampPayment:!0,description:u,recipientAddresses:r.recipientAddresses,recipientAddress:""};return r.fiat_currency!=null&&r.fiat_currency!==""&&(g.fiat_currency=r.fiat_currency),t.createPaymentUsd(g)}return{client:t,quoteUsd:a,sendUsd:n,startOnrampUsd:i,notifyIntentUntilComplete:s}}catch(t){throw ve(r.debug||!1,"Error creating SDK:",t),t}}import{LitElement as tt,html as z,css as nt}from"lit";import{customElement as at,property as pe,state as q}from"lit/decorators.js";import{IcpayError as De}from"@ic-pay/icpay-sdk";var ne={WALLET_NOT_CONNECTED:"WALLET_NOT_CONNECTED",WALLET_USER_CANCELLED:"WALLET_USER_CANCELLED",WALLET_SIGNATURE_REJECTED:"WALLET_SIGNATURE_REJECTED",INSUFFICIENT_BALANCE:"INSUFFICIENT_BALANCE",NETWORK_ERROR:"NETWORK_ERROR",API_ERROR:"API_ERROR",LEDGER_NOT_FOUND:"LEDGER_NOT_FOUND",TRANSACTION_FAILED:"TRANSACTION_FAILED",TRANSACTION_TIMEOUT:"TRANSACTION_TIMEOUT",UNKNOWN_ERROR:"UNKNOWN_ERROR"},Je={onError:r=>{console.error("[ICPay Widget] Error:",r)},onUserCancelled:()=>{console.log("[ICPay Widget] User cancelled the action")},onInsufficientBalance:r=>{console.warn("[ICPay Widget] Insufficient balance:",r.message)},onWalletError:r=>{console.warn("[ICPay Widget] Wallet error:",r.message)},onNetworkError:r=>{console.error("[ICPay Widget] Network error:",r.message)}};function f(r,l=Je){r instanceof De?(l.onError(r),r.isUserCancelled()?l.onUserCancelled?.():r.isBalanceError()?l.onInsufficientBalance?.(r):r.isWalletError()?l.onWalletError?.(r):r.isNetworkError()&&l.onNetworkError?.(r)):(console.error("[ICPay Widget] Unknown error:",r),l.onError(new De({code:ne.UNKNOWN_ERROR,message:r instanceof Error?r.message:"An unknown error occurred",details:r})))}var et={[ne.WALLET_NOT_CONNECTED]:"Please connect your wallet to continue",[ne.WALLET_USER_CANCELLED]:"User have rejected the transfer",[ne.WALLET_SIGNATURE_REJECTED]:"User have rejected the transfer",[ne.INSUFFICIENT_BALANCE]:"Insufficient balance for this transaction",[ne.NETWORK_ERROR]:"Network error. Please try again",[ne.API_ERROR]:"Service temporarily unavailable",[ne.LEDGER_NOT_FOUND]:"Selected token is not supported",[ne.TRANSACTION_FAILED]:"Transaction failed. Please try again",[ne.TRANSACTION_TIMEOUT]:"Transaction timed out. Please try again",[ne.UNKNOWN_ERROR]:"Something went wrong. Please try again"};function m(r){let l=r?.details||{},e=typeof l?.data?.message=="string"?l.data.message:void 0,t=typeof l?.message=="string"?l.message:void 0,a=e||t;if(a&&a.length>0){if(a.startsWith("missing_required_fields:")){let s=(a.split(":")[1]||"").split(",").map(o=>o.trim()).filter(Boolean);return s.length?`Missing required: ${s.join(", ")}`:"Missing required fields"}let n=a.match(/^Missing required fields:\s*(.+)$/i);if(n&&n[1]){let i=n[1].split(",").map(s=>s.trim()).filter(Boolean);return i.length?`Missing required: ${i.join(", ")}`:"Missing required fields"}return a}return et[r.code]||r.message||"An error occurred"}function w(r){return!r.isUserCancelled()}function b(r){return null}function v(r){return r.isUserCancelled()?"info":r.isBalanceError()||r.isWalletError()?"warning":"error"}function W(r,l,e){r&&(e!==void 0?console.log(l,e):console.log(l))}var it=[{key:"wallet",label:"Connect wallet",tooltip:"Awaiting wallet connection",status:"pending"},{key:"await",label:"Awaiting confirmation",tooltip:"Awaiting wallet signature",status:"pending"},{key:"transfer",label:"Transferring funds",tooltip:"Awaiting transfer to merchant",status:"pending"},{key:"verify",label:"Verifying payment",tooltip:"Please wait while we verify",status:"pending"}],S=class extends tt{constructor(){super(...arguments);this.open=!1;this.suspended=!1;this.steps=it;this.amount=0;this.currency="";this.ledgerSymbol="";this.debug=!1;this.activeIndex=0;this.completed=!1;this.failed=!1;this.errorMessage=null;this.showSuccess=!1;this.showConfetti=!1;this.currentSteps=[];this.currentAmount=0;this.currentCurrency="";this.currentLedgerSymbol="";this.currentFiatCode="";this.currentFiatSymbol=null;this.confirmLoadingStartedAt=null;this.progressionTimer=null;this.currentWalletType=null;this.showWalletSelector=!1;this.isTransitioning=!1;this.isOnrampFlow=!1;this.onPaymentReset=()=>{this.stopAutomaticProgression(),this.open=!1,this.showWalletSelector=!1,this.isTransitioning=!1,this.activeIndex=0,this.completed=!1,this.failed=!1,this.errorMessage=null,this.showSuccess=!1,this.showConfetti=!1,this.isOnrampFlow=!1,this.currentSteps=[...this.steps].map(e=>({...e,status:"pending"})),this.requestUpdate()};this.onMethodStart=e=>{let t=e?.detail?.name||"",a=e?.detail?.type||"";if(W(this.debug,"ICPay Progress: Method start event received:",e.detail),t==="createPayment"||t==="createPaymentUsd"||t==="sendUsd"||t==="pay"||t==="unlock"||t==="tip"||t==="donate"||t==="order"){if(this.open=!0,this.activeIndex=0,this.completed=!1,this.failed=!1,this.errorMessage=null,this.showSuccess=!1,this.showConfetti=!1,this.showWalletSelector=!1,this.isTransitioning=!1,this.currentSteps=this.currentSteps.map(n=>({...n,status:"pending"})),a==="onramp"){this.isOnrampFlow=!0;let n={wallet:{label:"Payment initiated",tooltip:"Please pay in the new tab"},await:{label:"Onramp process started",tooltip:"Verifying funds with provider"},transfer:{label:"Funds received",tooltip:"Payment in progress"},verify:{label:"Payment completed",tooltip:"Finalizing your payment"}};this.currentSteps=this.currentSteps.map(i=>n[i.key]?{...i,label:n[i.key].label,tooltip:n[i.key].tooltip}:i)}this.setLoadingByKey("wallet"),e?.detail?.amount!==void 0&&(this.currentAmount=e.detail.amount,this.amount=e.detail.amount,W(this.debug,"ICPay Progress: Amount updated to:",e.detail.amount)),e?.detail?.currency&&(this.currentCurrency=e.detail.currency,this.currency=e.detail.currency,W(this.debug,"ICPay Progress: Currency updated to:",e.detail.currency)),e?.detail?.ledgerSymbol&&(this.currentLedgerSymbol=e.detail.ledgerSymbol,this.ledgerSymbol=e.detail.ledgerSymbol,W(this.debug,"ICPay Progress: Current state after method start:",{activeIndex:this.activeIndex,currentAmount:this.currentAmount,currentCurrency:this.currentCurrency,currentLedgerSymbol:this.currentLedgerSymbol})),W(this.debug,"ICPay Progress: Waiting for wallet confirmation before starting progression"),this.requestUpdate()}!this.failed&&!this.completed&&(t==="createPaymentX402Usd"?(this.completeByKey("wallet"),this.setLoadingByKey("await")):t==="sendFundsToLedger"?(this.completeByKey("wallet"),this.completeByKey("await"),this.setLoadingByKey("transfer")):t==="notifyLedgerTransaction"?(this.completeByKey("wallet"),this.completeByKey("await"),this.setLoadingByKey("transfer")):t==="settleX402"&&(this.completeByKey("wallet"),this.completeByKey("await"),this.setLoadingByKey("transfer")))};this.onMethodSuccess=e=>{let t=e?.detail?.name||"";if((t==="createPayment"||t==="createPaymentUsd"||t==="sendUsd"||t==="pay"||t==="unlock"||t==="tip"||t==="donate"||t==="order")&&this.dispatchEvent(new CustomEvent("icpay-progress-method-success",{detail:{methodName:t,step:this.activeIndex},bubbles:!0})),!this.failed&&!this.completed){if(this.isOnrampFlow)return;t==="getLedgerBalance"?(this.completeByKey("wallet"),this.setLoadingByKey("await")):t==="sendFundsToLedger"?(this.completeByKey("wallet"),this.completeByKey("await"),this.completeByKey("transfer"),this.setLoadingByKey("verify")):t==="notifyLedgerTransaction"?(this.completeByKey("wallet"),this.completeByKey("await"),this.completeByKey("transfer"),this.setLoadingByKey("verify")):t==="createPaymentX402Usd"&&(this.completeByKey("wallet"),this.completeByKey("await"),this.completeByKey("transfer"),this.setLoadingByKey("verify"))}};this.onTransactionCreated=e=>{let t=e?.detail?.transactionId||e?.detail?.id;if(W(this.debug,"ICPay Progress: Transaction created event received:",e.detail),!this.failed&&!this.completed){if(this.isOnrampFlow)return;this.completeByKey("wallet"),this.completeByKey("await"),this.setLoadingByKey("transfer")}this.dispatchEvent(new CustomEvent("icpay-progress-transaction-created",{detail:{transactionId:t,step:this.activeIndex},bubbles:!0}))};this.onTransactionUpdated=e=>{let t=e?.detail?.status||"pending",a=e?.detail?.transactionId||e?.detail?.id,n=e?.detail?.metadata||e?.detail?.intent?.metadata||{};if(W(this.debug,"ICPay Progress: Transaction updated event received:",e.detail),!this.failed&&!this.completed&&this.isOnrampFlow){let i=n?.onramp_order_completed===!0||n?.icpay_onramp?.status==="completed"||n?.onrampCompleted===!0;t==="requires_payment"&&!i?(this.completeByKey("wallet"),this.setLoadingByKey("await")):(t==="pending"||t==="processing"||i)&&(this.completeByKey("wallet"),this.completeByKey("await"),this.setLoadingByKey("transfer"))}this.dispatchEvent(new CustomEvent("icpay-progress-transaction-updated",{detail:{status:t,transactionId:a,step:this.activeIndex},bubbles:!0}))};this.onTransactionCompleted=e=>{let t=e?.detail?.transactionId||e?.detail?.id,a=e?.detail?.status||"completed",n=e?.detail?.paymentIntent??e?.detail?.payment?.paymentIntent;n&&typeof n=="object"&&(n.fiatCurrencyCode!=null&&n.fiatCurrencyCode!==""&&(this.currentFiatCode=String(n.fiatCurrencyCode)),n.fiatCurrencySymbol!=null&&n.fiatCurrencySymbol!==""&&(this.currentFiatSymbol=String(n.fiatCurrencySymbol))),W(this.debug,"ICPay Progress: Transaction completed event received:",e.detail),W(this.debug,"ICPay Progress: Current state when transaction completed:",{activeIndex:this.activeIndex,completed:this.completed,failed:this.failed,showSuccess:this.showSuccess}),this.completeByKey("transfer"),this.completeByKey("await"),this.completeByKey("verify"),this.completed=!0,this.showSuccess=!0,this.showConfetti=!0,this.isOnrampFlow=!1,this.dispatchEvent(new CustomEvent("icpay-progress-completed",{detail:{transactionId:t,status:a,amount:this.currentAmount||this.amount,currency:this.currentCurrency||this.currency,ledgerSymbol:this.currentLedgerSymbol||this.ledgerSymbol},bubbles:!0})),setTimeout(()=>{this.showConfetti=!1},3e3)};this.onTransactionFailed=e=>{let t=e?.detail?.error,a=e?.detail?.message||e?.detail?.error?.message||"Transaction failed",n=t?m(t):this.transformErrorMessage(a),i=e?.detail?.error?.code||e?.detail?.code||"UNKNOWN_ERROR",s=e?.detail?.transactionId||e?.detail?.id;W(this.debug,"ICPay Progress: Transaction failed event received:",e.detail),this.failed=!0,this.errorMessage=this.preferSpecificError(this.errorMessage,n),this.showSuccess=!1,this.updateStepStatus(this.activeIndex,"error",this.errorMessage),this.stopAutomaticProgression(),this.open=!0,this.isOnrampFlow=!1,this.dispatchEvent(new CustomEvent("icpay-progress-failed",{detail:{errorMessage:this.errorMessage,errorCode:i,transactionId:s,step:this.activeIndex},bubbles:!0}))};this.onTransactionMismatched=e=>{let t=e?.detail?.requestedAmount,a=e?.detail?.paidAmount,n=e?.detail?.transactionId||e?.detail?.id;this.failed=!0;let i=t!=null?String(t):"unknown",s=a!=null?String(a):"unknown";this.errorMessage=`Amount mismatch. Requested ${i}, paid ${s}.`,this.showSuccess=!1,this.updateStepStatus(this.activeIndex,"error",this.errorMessage),this.stopAutomaticProgression(),this.open=!0,this.isOnrampFlow=!1,this.dispatchEvent(new CustomEvent("icpay-progress-failed",{detail:{errorMessage:this.errorMessage,errorCode:"MISMATCHED_AMOUNT",transactionId:n,step:this.activeIndex,requestedAmount:t,paidAmount:a},bubbles:!0}))};this.onMethodError=e=>{let t=e?.detail?.name||"",a=e?.detail?.error,n=e?.detail?.message||a&&a.message||"An error occurred",i=a?m(a):this.transformErrorMessage(n),s=e?.detail?.error?.code||e?.detail?.code||"METHOD_ERROR";W(this.debug,"ICPay Progress: Method error event received:",e.detail),(t?.startsWith("createPayment")||t==="sendUsd"||t==="pay"||t==="unlock"||t==="tip"||t==="donate"||t==="order")&&(this.failed=!0,this.errorMessage=this.preferSpecificError(this.errorMessage,i),this.showSuccess=!1,this.updateStepStatus(this.activeIndex,"error",this.errorMessage),this.stopAutomaticProgression(),this.open=!0,this.isOnrampFlow=!1,this.dispatchEvent(new CustomEvent("icpay-progress-error",{detail:{methodName:t,errorMessage:this.errorMessage,errorCode:s,step:this.activeIndex},bubbles:!0})))};this.onSDKError=e=>{let t=e?.detail?.error,a=e?.detail?.message||t&&t.message||"SDK error occurred",n=t?m(t):this.transformErrorMessage(a),i=e?.detail?.code||"SDK_ERROR";W(this.debug,"ICPay Progress: SDK error event received:",e.detail),this.failed=!0,this.errorMessage=this.preferSpecificError(this.errorMessage,n),this.showSuccess=!1,this.updateStepStatus(this.activeIndex,"error",this.errorMessage),this.stopAutomaticProgression(),this.open=!0,this.isOnrampFlow=!1,this.dispatchEvent(new CustomEvent("icpay-progress-sdk-error",{detail:{errorMessage:this.errorMessage,errorCode:i,step:this.activeIndex},bubbles:!0}))};this.onWalletConnected=e=>{let t=e?.detail?.walletType||"unknown";W(this.debug,"ICPay Progress: Wallet connected event received:",e.detail),this.completeByKey("wallet"),this.setLoadingByKey("await"),this.startTransitionToProgress(),this.dispatchEvent(new CustomEvent("icpay-progress-wallet-connected",{detail:{walletType:t,step:this.activeIndex},bubbles:!0})),this.currentWalletType=t};this.onOnrampOpened=e=>{!this.isOnrampFlow||this.failed||this.completed||(this.completeByKey("wallet"),this.setLoadingByKey("await"))};this.onWalletDisconnected=e=>{let t=e?.detail?.walletType||"unknown";W(this.debug,"ICPay Progress: Wallet disconnected event received:",e.detail),this.dispatchEvent(new CustomEvent("icpay-progress-wallet-disconnected",{detail:{walletType:t,step:this.activeIndex},bubbles:!0})),this.currentWalletType=null};this.onBalanceCheck=e=>{let t=e?.detail?.hasBalance||!1,a=e?.detail?.balance||0;W(this.debug,"ICPay Progress: Balance check event received:",e.detail),t||(this.failed=!0,this.errorMessage="Insufficient balance for transaction",this.updateStepStatus(this.activeIndex,"error","Insufficient balance for transaction"),this.stopAutomaticProgression(),this.showWalletSelector=!1,this.dispatchEvent(new CustomEvent("icpay-progress-insufficient-balance",{detail:{balance:a,required:this.currentAmount||this.amount,step:this.activeIndex},bubbles:!0})))};this.onLedgerVerified=e=>{let t=e?.detail?.ledgerId||e?.detail?.canisterId,a=e?.detail?.symbol||"unknown";W(this.debug,"ICPay Progress: Ledger verified event received:",e.detail),a&&a!=="unknown"&&(this.currentLedgerSymbol=a,this.ledgerSymbol=a),this.dispatchEvent(new CustomEvent("icpay-progress-ledger-verified",{detail:{ledgerId:t,symbol:a,step:this.activeIndex},bubbles:!0}))};this.onWidgetPayment=e=>{let t=e?.detail?.amount,a=e?.detail?.currency,n=e?.detail?.ledgerSymbol;if(W(this.debug,"ICPay Progress: Widget payment event received:",e.detail),t!==void 0&&(this.currentAmount=t,this.amount=t),a&&(this.currentCurrency=a,this.currency=a),n&&(this.currentLedgerSymbol=n,this.ledgerSymbol=n),!this.failed){for(let i=this.activeIndex;i<this.currentSteps.length;i++)this.updateStepStatus(i,"completed");this.activeIndex=this.currentSteps.length-1,this.completed=!0,this.showSuccess=!0,this.showConfetti=!0}this.dispatchEvent(new CustomEvent("icpay-progress-widget-payment",{detail:{amount:t,currency:a,ledgerSymbol:n,step:this.activeIndex},bubbles:!0}))};this.onWidgetError=e=>{let t=e?.detail?.error||e?.detail,a=t&&t.message||e?.detail?.message||"Widget error occurred",n=t?m(t):this.transformErrorMessage(a),i=t&&t.code||e?.detail?.code||"WIDGET_ERROR";W(this.debug,"ICPay Progress: Widget error event received:",e.detail),this.failed=!0,this.errorMessage=this.preferSpecificError(this.errorMessage,n),this.showSuccess=!1,this.updateStepStatus(this.activeIndex,"error",this.errorMessage),this.stopAutomaticProgression(),this.open=!0,this.dispatchEvent(new CustomEvent("icpay-progress-widget-error",{detail:{errorMessage:this.errorMessage,errorCode:i,step:this.activeIndex},bubbles:!0}))};this.onWidgetUnlock=e=>{let t=e?.detail?.amount,a=e?.detail?.currency;if(W(this.debug,"ICPay Progress: Widget unlock event received:",e.detail),!this.failed){for(let n=this.activeIndex;n<this.currentSteps.length;n++)this.updateStepStatus(n,"completed");this.activeIndex=this.currentSteps.length-1,this.completed=!0,this.showSuccess=!0,this.showConfetti=!0}this.dispatchEvent(new CustomEvent("icpay-progress-widget-unlock",{detail:{amount:t,currency:a,step:this.activeIndex},bubbles:!0}))};this.onWidgetTip=e=>{let t=e?.detail?.amount,a=e?.detail?.currency;if(W(this.debug,"ICPay Progress: Widget tip event received:",e.detail),!this.failed){for(let n=this.activeIndex;n<this.currentSteps.length;n++)this.updateStepStatus(n,"completed");this.activeIndex=this.currentSteps.length-1,this.completed=!0,this.showSuccess=!0,this.showConfetti=!0}this.dispatchEvent(new CustomEvent("icpay-progress-widget-tip",{detail:{amount:t,currency:a,step:this.activeIndex},bubbles:!0}))};this.onWidgetDonation=e=>{let t=e?.detail?.amount,a=e?.detail?.currency;if(W(this.debug,"ICPay Progress: Widget donation event received:",e.detail),!this.failed){for(let n=this.activeIndex;n<this.currentSteps.length;n++)this.updateStepStatus(n,"completed");this.activeIndex=this.currentSteps.length-1,this.completed=!0,this.showSuccess=!0,this.showConfetti=!0}this.dispatchEvent(new CustomEvent("icpay-progress-widget-donation",{detail:{amount:t,currency:a,step:this.activeIndex},bubbles:!0}))};this.onWidgetCoffee=e=>{let t=e?.detail?.amount,a=e?.detail?.currency;if(W(this.debug,"ICPay Progress: Widget coffee event received:",e.detail),!this.failed){for(let n=this.activeIndex;n<this.currentSteps.length;n++)this.updateStepStatus(n,"completed");this.activeIndex=this.currentSteps.length-1,this.completed=!0,this.showSuccess=!0,this.showConfetti=!0}this.dispatchEvent(new CustomEvent("icpay-progress-widget-coffee",{detail:{amount:t,currency:a,step:this.activeIndex},bubbles:!0}))};this.onWalletCancelled=e=>{try{let t=this.getStepIndexByKey("wallet"),a=this.getStepIndexByKey("await"),n=this.getStepIndexByKey("transfer"),i=this.getStepIndexByKey("verify"),s=this.currentSteps&&this.currentSteps.length>0&&this.currentSteps.some((p,y)=>t>=0&&y>t?p.status==="loading"||p.status==="completed":!1),d=(t>=0?this.currentSteps[t]:null)?.status==="completed";if(!s&&!d){this.open=!1,this.activeIndex=0,this.currentSteps=this.currentSteps.map(p=>({...p,status:"pending"})),this.requestUpdate();return}this.open=!0,t>=0&&(this.activeIndex=t,this.currentSteps[t]={...this.currentSteps[t],tooltip:"Wallet connection cancelled",status:"error"},this.requestUpdate())}catch{}};this.onWalletError=e=>{try{let t=e?.detail?.message||"Wallet error",a=this.transformErrorMessage(t);this.open=!0;let n=this.getStepIndexByKey("wallet");n>=0&&(this.activeIndex=n,this.currentSteps[n]={...this.currentSteps[n],tooltip:"Wallet connection failed",status:"error",errorMessage:a},this.requestUpdate())}catch{}}}connectedCallback(){super.connectedCallback();try{fe(this,this.theme);let e="light";if(typeof this.theme=="string")e=this.theme;else if(this.theme&&typeof this.theme=="object"&&this.theme.mode)e=this.theme.mode;else if(typeof document<"u"){let t=document.documentElement.getAttribute("data-icpay-theme")||document.documentElement.getAttribute("data-theme");(t==="light"||t==="dark")&&(e=t)}this.setAttribute("data-theme",e)}catch{}this.currentSteps=[...this.steps],this.currentAmount=this.amount,this.currentCurrency=this.currency,this.currentLedgerSymbol=this.ledgerSymbol,this.attachSDKEventListeners()}disconnectedCallback(){super.disconnectedCallback(),this.detachSDKEventListeners(),this.stopAutomaticProgression()}updated(e){if(e.has("theme"))try{fe(this,this.theme);let t="light";if(typeof this.theme=="string")t=this.theme;else if(this.theme&&typeof this.theme=="object"&&this.theme.mode)t=this.theme.mode;else if(typeof document<"u"){let a=document.documentElement.getAttribute("data-icpay-theme")||document.documentElement.getAttribute("data-theme");(a==="light"||a==="dark")&&(t=a)}this.setAttribute("data-theme",t)}catch{}}attachSDKEventListeners(){window.addEventListener("icpay-sdk-method-start",this.onMethodStart),window.addEventListener("icpay-sdk-method-success",this.onMethodSuccess),window.addEventListener("icpay-sdk-method-error",this.onMethodError),window.addEventListener("icpay-sdk-wallet-cancelled",this.onWalletCancelled),window.addEventListener("icpay-sdk-wallet-error",this.onWalletError),window.addEventListener("icpay-sdk-transaction-created",this.onTransactionCreated),window.addEventListener("icpay-sdk-transaction-updated",this.onTransactionUpdated),window.addEventListener("icpay-sdk-transaction-completed",this.onTransactionCompleted),window.addEventListener("icpay-sdk-transaction-failed",this.onTransactionFailed),window.addEventListener("icpay-sdk-transaction-mismatched",this.onTransactionMismatched),window.addEventListener("icpay-onramp-opened",this.onOnrampOpened),window.addEventListener("icpay-sdk-error",this.onSDKError),window.addEventListener("icpay-sdk-wallet-connected",this.onWalletConnected),window.addEventListener("icpay-sdk-wallet-disconnected",this.onWalletDisconnected),window.addEventListener("icpay-sdk-balance-check",this.onBalanceCheck),window.addEventListener("icpay-sdk-ledger-verified",this.onLedgerVerified),window.addEventListener("icpay-pay",this.onWidgetPayment),window.addEventListener("icpay-error",this.onWidgetError),window.addEventListener("icpay-unlock",this.onWidgetUnlock),window.addEventListener("icpay-tip",this.onWidgetTip),window.addEventListener("icpay-donation",this.onWidgetDonation),window.addEventListener("icpay-coffee",this.onWidgetCoffee),window.addEventListener("icpay-payment-reset",this.onPaymentReset)}detachSDKEventListeners(){window.removeEventListener("icpay-sdk-method-start",this.onMethodStart),window.removeEventListener("icpay-sdk-method-success",this.onMethodSuccess),window.removeEventListener("icpay-sdk-method-error",this.onMethodError),window.removeEventListener("icpay-sdk-wallet-cancelled",this.onWalletCancelled),window.removeEventListener("icpay-sdk-wallet-error",this.onWalletError),window.removeEventListener("icpay-sdk-transaction-created",this.onTransactionCreated),window.removeEventListener("icpay-sdk-transaction-updated",this.onTransactionUpdated),window.removeEventListener("icpay-sdk-transaction-completed",this.onTransactionCompleted),window.removeEventListener("icpay-sdk-transaction-failed",this.onTransactionFailed),window.removeEventListener("icpay-sdk-transaction-mismatched",this.onTransactionMismatched),window.removeEventListener("icpay-onramp-opened",this.onOnrampOpened),window.removeEventListener("icpay-sdk-error",this.onSDKError),window.removeEventListener("icpay-sdk-wallet-connected",this.onWalletConnected),window.removeEventListener("icpay-sdk-wallet-disconnected",this.onWalletDisconnected),window.removeEventListener("icpay-sdk-balance-check",this.onBalanceCheck),window.removeEventListener("icpay-sdk-ledger-verified",this.onLedgerVerified),window.removeEventListener("icpay-pay",this.onWidgetPayment),window.removeEventListener("icpay-error",this.onWidgetError),window.removeEventListener("icpay-unlock",this.onWidgetUnlock),window.removeEventListener("icpay-tip",this.onWidgetTip),window.removeEventListener("icpay-donation",this.onWidgetDonation),window.removeEventListener("icpay-coffee",this.onWidgetCoffee),window.removeEventListener("icpay-payment-reset",this.onPaymentReset)}startAutomaticProgression(){this.progressionTimer&&clearInterval(this.progressionTimer),this.activeIndex=1,this.updateStepStatus(this.activeIndex,"loading"),W(this.debug,"ICPay Progress: Starting automatic progression from step:",this.activeIndex),this.progressionTimer=setInterval(()=>{if(this.failed||this.completed){this.stopAutomaticProgression();return}W(this.debug,"ICPay Progress: Processing step:",this.activeIndex),this.updateStepStatus(this.activeIndex,"completed"),this.activeIndex<this.currentSteps.length-1?(this.activeIndex++,this.updateStepStatus(this.activeIndex,"loading"),W(this.debug,"ICPay Progress: Auto-progressed to step:",this.activeIndex)):(this.stopAutomaticProgression(),W(this.debug,"ICPay Progress: All steps completed, waiting for transaction completion")),this.requestUpdate()},3e3)}stopAutomaticProgression(){this.progressionTimer&&(clearInterval(this.progressionTimer),this.progressionTimer=null)}updateStepStatus(e,t,a){if(e>=0&&e<this.currentSteps.length){let n=this.currentSteps[e],i=n.status;n.status=t,t==="completed"&&(n.timestamp=this.getCurrentTime()),t==="error"&&a&&(n.errorMessage=this.transformErrorMessage(a)),i!==t&&W(this.debug,`ICPay Progress: Step ${e} (${n.label}) status changed from ${i} to ${t}`),this.requestUpdate()}}getCurrentTime(){return new Date().toLocaleTimeString("en-US",{hour12:!1,hour:"2-digit",minute:"2-digit",second:"2-digit"})}getStepIcon(e){return e.status==="error"?z`<div class="error-x">✕</div>`:z`<div class="spinner"></div>`}getStepIndexByKey(e){return this.currentSteps.findIndex(t=>t.key===e)}setLoadingByKey(e){let t=this.getStepIndexByKey(e);t>=0&&(this.activeIndex=t,this.updateStepStatus(t,"loading"),e==="verify"&&(this.confirmLoadingStartedAt=Date.now()))}completeByKey(e){let t=this.getStepIndexByKey(e);t>=0&&(this.updateStepStatus(t,"completed"),this.activeIndex=t)}transformErrorMessage(e){let t=String(e||"").toLowerCase();return t.includes("user rejected")||t.includes("user cancelled")||t.includes("user canceled")||t.includes("signature rejected")?"User have rejected the transfer":e}isGenericErrorText(e){if(!e)return!0;let t=e.toLowerCase();return t==="an error occurred"||t==="sdk error occurred"||t==="transaction failed"||t.includes("failed to create payment")||t.includes("wallet error")||t.includes("network error")}preferSpecificError(e,t){let a=this.transformErrorMessage(t||"");return e&&!this.isGenericErrorText(e)&&this.isGenericErrorText(a)?e:a}renderConfetti(){if(!this.showConfetti)return"";let e=Array.from({length:50},(a,n)=>n),t=["#0066FF","#ef4444","#10b981","#f59e0b","#8b5cf6"];return z`
147
147
  <div class="confetti">
148
- ${e.map(n=>D`
148
+ ${e.map(a=>z`
149
149
  <div
150
150
  class="confetti-piece"
151
151
  style="
@@ -158,7 +158,7 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
158
158
  ></div>
159
159
  `)}
160
160
  </div>
161
- `}renderSuccessState(){let e=this.currentAmount||this.amount,t=(this.currentFiatCode??this.currentFiatSymbol)||"USD";return M(this.debug,"ICPay Progress: Rendering success state with:",{displayAmount:e,currentAmount:this.currentAmount,amount:this.amount,currentCurrency:this.currentCurrency,currency:this.currency,currentLedgerSymbol:this.currentLedgerSymbol,ledgerSymbol:this.ledgerSymbol,fiatLabel:t}),D`
161
+ `}renderSuccessState(){let e=this.currentAmount||this.amount,t=(this.currentFiatCode??this.currentFiatSymbol)||"USD";return W(this.debug,"ICPay Progress: Rendering success state with:",{displayAmount:e,currentAmount:this.currentAmount,amount:this.amount,currentCurrency:this.currentCurrency,currency:this.currency,currentLedgerSymbol:this.currentLedgerSymbol,ledgerSymbol:this.ledgerSymbol,fiatLabel:t}),z`
162
162
  <div class="success-center">
163
163
  <div class="success-container">
164
164
  <div class="success-icon">
@@ -173,7 +173,7 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
173
173
  </div>
174
174
  </div>
175
175
  </div>
176
- `}renderErrorState(){return this.errorMessage?.includes("Insufficient balance")||!1?this.renderInsufficientFundsError():this.renderGenericError()}renderInsufficientFundsError(){let e=this.currentAmount||this.amount;return D`
176
+ `}renderErrorState(){return this.errorMessage?.includes("Insufficient balance")||!1?this.renderInsufficientFundsError():this.renderGenericError()}renderInsufficientFundsError(){let e=this.currentAmount||this.amount;return z`
177
177
  <div class="insufficient-funds-container">
178
178
  <div class="payment-summary">
179
179
  <div class="payment-amount">Pay $${e} with crypto</div>
@@ -205,7 +205,7 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
205
205
  </button>
206
206
  </div>
207
207
  </div>
208
- `}renderGenericError(){return D`
208
+ `}renderGenericError(){return z`
209
209
  <div class="error-container">
210
210
  <div class="error-icon-large">
211
211
  <svg fill="none" viewBox="0 0 24 24" stroke="currentColor">
@@ -229,7 +229,7 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
229
229
  </button>
230
230
  </div>
231
231
  </div>
232
- `}requestSwitchAccount(){try{this.open=!1;let e=this.currentWalletType||"unknown";window.dispatchEvent(new CustomEvent("icpay-switch-account",{detail:{walletType:e}}))}catch{}}handleAddFunds(){try{window.dispatchEvent(new CustomEvent("icpay-add-funds",{detail:{amount:this.currentAmount||this.amount,currency:this.currentLedgerSymbol||this.currentCurrency||this.currency}})),this.open=!1}catch(e){console.error("Error handling add funds:",e)}}startTransitionToProgress(){this.isTransitioning=!0,this.requestUpdate(),setTimeout(()=>{this.showWalletSelector=!1,this.isTransitioning=!1,this.requestUpdate()},400)}renderProgressContent(){return this.showSuccess?this.renderSuccessState():this.failed?this.renderErrorState():D`
232
+ `}requestSwitchAccount(){try{this.open=!1;let e=this.currentWalletType||"unknown";window.dispatchEvent(new CustomEvent("icpay-switch-account",{detail:{walletType:e}}))}catch{}}handleAddFunds(){try{window.dispatchEvent(new CustomEvent("icpay-add-funds",{detail:{amount:this.currentAmount||this.amount,currency:this.currentLedgerSymbol||this.currentCurrency||this.currency}})),this.open=!1}catch(e){console.error("Error handling add funds:",e)}}startTransitionToProgress(){this.isTransitioning=!0,this.requestUpdate(),setTimeout(()=>{this.showWalletSelector=!1,this.isTransitioning=!1,this.requestUpdate()},400)}renderProgressContent(){return this.showSuccess?this.renderSuccessState():this.failed?this.renderErrorState():z`
233
233
  <div class="progress-container">
234
234
  <div class="progress-header">
235
235
  <span class="progress-spacer"></span>
@@ -237,7 +237,7 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
237
237
  </div>
238
238
  ${this.renderConfirmTip()}
239
239
  <div class="progress-steps">
240
- ${this.currentSteps.map((e,t)=>D`
240
+ ${this.currentSteps.map((e,t)=>z`
241
241
  <div class="step ${t===this.activeIndex?"active":""} ${e.status==="completed"?"completed":""} ${e.status==="error"?"error":""}">
242
242
  <div class="step-icon">
243
243
  ${this.getStepIcon(e)}
@@ -245,7 +245,7 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
245
245
  <div class="step-content">
246
246
  <div class="step-title">${e.label}</div>
247
247
  <div class="step-description">${e.tooltip}</div>
248
- ${e.status==="error"&&e.errorMessage?D`
248
+ ${e.status==="error"&&e.errorMessage?z`
249
249
  <div class="step-error-message">${e.errorMessage}</div>
250
250
  `:""}
251
251
  </div>
@@ -253,7 +253,7 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
253
253
  `)}
254
254
  </div>
255
255
  </div>
256
- `}renderConfirmTip(){try{let e=this.getStepIndexByKey("verify");if(e<0||!(this.activeIndex===e&&this.currentSteps[e]?.status==="loading"))return null;let n=this.confirmLoadingStartedAt||0;return(n?Date.now()-n:0)<3e4?null:D`<p class="progress-subtitle" style="margin-top:8px;color:#60a5fa">Verification can take from 30 seconds up to 10 minutes depending on the amount. Please wait…</p>`}catch{return null}}retryTransaction(){this.activeIndex=0,this.completed=!1,this.failed=!1,this.errorMessage=null,this.showSuccess=!1,this.showConfetti=!1,this.currentSteps=this.currentSteps.map(e=>({...e,status:"pending"})),this.updateStepStatus(0,"loading"),this.startAutomaticProgression(),this.requestUpdate()}closeProgress(){this.open=!1,this.showWalletSelector=!1,this.isTransitioning=!1}renderStep(e,t){return D`
256
+ `}renderConfirmTip(){try{let e=this.getStepIndexByKey("verify");if(e<0||!(this.activeIndex===e&&this.currentSteps[e]?.status==="loading"))return null;let a=this.confirmLoadingStartedAt||0;return(a?Date.now()-a:0)<3e4?null:z`<p class="progress-subtitle" style="margin-top:8px;color:#60a5fa">Verification can take from 30 seconds up to 10 minutes depending on the amount. Please wait…</p>`}catch{return null}}retryTransaction(){this.activeIndex=0,this.completed=!1,this.failed=!1,this.errorMessage=null,this.showSuccess=!1,this.showConfetti=!1,this.currentSteps=this.currentSteps.map(e=>({...e,status:"pending"})),this.updateStepStatus(0,"loading"),this.startAutomaticProgression(),this.requestUpdate()}closeProgress(){this.open=!1,this.showWalletSelector=!1,this.isTransitioning=!1}renderStep(e,t){return z`
257
257
  <div class="step-item ${e.status}">
258
258
  <div class="step-icon">
259
259
  ${this.getStepIcon(e)}
@@ -262,23 +262,23 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
262
262
  <div class="step-title">
263
263
  ${e.status==="completed"?"COMPLETED":e.label}
264
264
  </div>
265
- ${e.status==="completed"?D`
265
+ ${e.status==="completed"?z`
266
266
  <div class="step-subtitle">
267
267
  ${e.timestamp} - ${e.tooltip}
268
268
  </div>
269
- `:e.status==="error"&&e.errorMessage?D`
269
+ `:e.status==="error"&&e.errorMessage?z`
270
270
  <div class="step-error">${e.errorMessage}</div>
271
- `:D`
271
+ `:z`
272
272
  <div class="step-subtitle">${e.tooltip}</div>
273
273
  `}
274
274
  </div>
275
275
  </div>
276
- `}get isWalletConnectLoading(){try{let e=this.currentSteps.findIndex(t=>t.key==="wallet");return e<0?!1:this.currentSteps[e].status==="loading"&&!this.failed&&!this.showSuccess}catch{return!1}}render(){return this.suspended?null:D`
277
- ${this.open?D`
276
+ `}get isWalletConnectLoading(){try{let e=this.currentSteps.findIndex(t=>t.key==="wallet");return e<0?!1:this.currentSteps[e].status==="loading"&&!this.failed&&!this.showSuccess}catch{return!1}}render(){return this.suspended?null:z`
277
+ ${this.open?z`
278
278
  ${this.renderConfetti()}
279
279
  <div class="modal-overlay active">
280
280
  <div class="modal-container">
281
- ${this.showSuccess?null:D`<button class="close-button" @click=${()=>this.closeProgress()} aria-label="Close" title="Close">✕</button>`}
281
+ ${this.showSuccess?null:z`<button class="close-button" @click=${()=>this.closeProgress()} aria-label="Close" title="Close">✕</button>`}
282
282
  <div class="modal-content ${this.isTransitioning?"transitioning":""}">
283
283
  ${this.renderProgressContent()}
284
284
  </div>
@@ -1047,7 +1047,7 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
1047
1047
  opacity: 0;
1048
1048
  }
1049
1049
  }
1050
- `,s([le({type:Boolean})],S.prototype,"open",2),s([le({type:Boolean})],S.prototype,"suspended",2),s([le({type:Array})],S.prototype,"steps",2),s([le({type:Number})],S.prototype,"amount",2),s([le({type:String})],S.prototype,"currency",2),s([le({type:String})],S.prototype,"ledgerSymbol",2),s([le({type:Boolean})],S.prototype,"debug",2),s([z()],S.prototype,"activeIndex",2),s([z()],S.prototype,"completed",2),s([z()],S.prototype,"failed",2),s([z()],S.prototype,"errorMessage",2),s([z()],S.prototype,"showSuccess",2),s([z()],S.prototype,"showConfetti",2),s([z()],S.prototype,"currentSteps",2),s([z()],S.prototype,"currentAmount",2),s([z()],S.prototype,"currentCurrency",2),s([z()],S.prototype,"currentLedgerSymbol",2),s([z()],S.prototype,"currentFiatCode",2),s([z()],S.prototype,"currentFiatSymbol",2),s([z()],S.prototype,"confirmLoadingStartedAt",2),s([z()],S.prototype,"currentWalletType",2),s([z()],S.prototype,"showWalletSelector",2),s([z()],S.prototype,"isTransitioning",2),s([z()],S.prototype,"isOnrampFlow",2),s([le({type:Object})],S.prototype,"theme",2),S=s([at("icpay-progress-bar")],S);import{html as Ae}from"lit";function rt(r){if(r==="light"||r==="dark")return r;if(typeof document>"u")return"light";let l=document.documentElement.getAttribute("data-icpay-theme");if(l==="light"||l==="dark")return l;let e=document.documentElement.getAttribute("data-theme");return e==="light"||e==="dark"?e:"light"}function H(r){if(!r.visible)return null;let l=r.width??420,e=r.height??680,t=typeof r.url=="string"&&(r.url||"").startsWith("http"),n=rt(r.theme);return Ae`
1050
+ `,c([pe({type:Boolean})],S.prototype,"open",2),c([pe({type:Boolean})],S.prototype,"suspended",2),c([pe({type:Array})],S.prototype,"steps",2),c([pe({type:Number})],S.prototype,"amount",2),c([pe({type:String})],S.prototype,"currency",2),c([pe({type:String})],S.prototype,"ledgerSymbol",2),c([pe({type:Boolean})],S.prototype,"debug",2),c([q()],S.prototype,"activeIndex",2),c([q()],S.prototype,"completed",2),c([q()],S.prototype,"failed",2),c([q()],S.prototype,"errorMessage",2),c([q()],S.prototype,"showSuccess",2),c([q()],S.prototype,"showConfetti",2),c([q()],S.prototype,"currentSteps",2),c([q()],S.prototype,"currentAmount",2),c([q()],S.prototype,"currentCurrency",2),c([q()],S.prototype,"currentLedgerSymbol",2),c([q()],S.prototype,"currentFiatCode",2),c([q()],S.prototype,"currentFiatSymbol",2),c([q()],S.prototype,"confirmLoadingStartedAt",2),c([q()],S.prototype,"currentWalletType",2),c([q()],S.prototype,"showWalletSelector",2),c([q()],S.prototype,"isTransitioning",2),c([q()],S.prototype,"isOnrampFlow",2),c([pe({type:Object})],S.prototype,"theme",2),S=c([at("icpay-progress-bar")],S);import{html as Ae}from"lit";function rt(r){if(r==="light"||r==="dark")return r;if(typeof document>"u")return"light";let l=document.documentElement.getAttribute("data-icpay-theme");if(l==="light"||l==="dark")return l;let e=document.documentElement.getAttribute("data-theme");return e==="light"||e==="dark"?e:"light"}function H(r){if(!r.visible)return null;let l=r.width??420,e=r.height??680,t=typeof r.url=="string"&&(r.url||"").startsWith("http"),a=rt(r.theme);return Ae`
1051
1051
  <style>
1052
1052
  /* Theme-aware color variables - Light mode defaults */
1053
1053
  .icpay-onramp-modal-overlay {
@@ -1121,7 +1121,7 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
1121
1121
  }
1122
1122
  }
1123
1123
  </style>
1124
- <div class="icpay-onramp-modal-overlay" data-theme="${n}">
1124
+ <div class="icpay-onramp-modal-overlay" data-theme="${a}">
1125
1125
  <div class="icpay-onramp-modal-container">
1126
1126
  <button @click=${r.onClose} style="position:absolute;right:12px;top:12px;background:transparent;border:none;color:var(--icpay-foreground);cursor:pointer;font-size:20px;opacity:0.8;z-index:10">×</button>
1127
1127
  ${r.onBack?Ae`<button @click=${r.onBack} style="position:absolute;left:12px;top:12px;background:transparent;border:1px solid var(--icpay-border);color:var(--icpay-foreground);cursor:pointer;font-size:12px;border-radius:8px;padding:6px 10px;opacity:0.9;z-index:10">Back</button>`:null}
@@ -1144,7 +1144,7 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
1144
1144
  `}
1145
1145
  </div>
1146
1146
  </div>
1147
- `}import{LitElement as vt,html as de,css as wt}from"lit";import{customElement as bt,property as Et,state as $}from"lit/decorators.js";import{html as ne}from"lit";var Fe=new Set(["metamask","walletconnect","coinbase","brave","rainbow","rabby","okx","trust"]),st=new Set(["phantom","backpack"]);function q(r){return r?Fe.has(String(r).toLowerCase()):!1}function ot(r){return r&&(r.id||r.provider||r.key)||""}function ct(r){return r&&(r.label||r.name||r.title||r.id)||"Wallet"}function lt(r){return r&&(r.icon||r.logo||r.image)||null}function V(r){return(r||[]).map(l=>({id:ot(l),label:ct(l),icon:lt(l)}))}async function X(r,l){try{let e=l?.provider||(typeof window<"u"?window.ethereum:null);if(!e||r===void 0||r===null)return!0;let t=typeof r=="number"?r:String(r).startsWith("0x")?parseInt(String(r),16):parseInt(String(r),10);if(!Number.isFinite(t))return!0;let n=await e.request({method:"eth_chainId"});if(parseInt(n,16)===t)return!0;let i="0x"+t.toString(16);return await e.request({method:"wallet_switchEthereumChain",params:[{chainId:i}]}),!0}catch{try{let t=l?.provider||(typeof window<"u"?window.ethereum:null);if(!t||r===void 0||r===null)return!1;let n=typeof r=="number"?r:String(r).startsWith("0x")?parseInt(String(r),16):parseInt(String(r),10),a="0x"+n.toString(16),i=l?.chainName||`Network ${n}`,o=(l?.rpcUrlPublic?[l.rpcUrlPublic]:[]).filter(Boolean),c={name:l?.nativeSymbol||"ETH",symbol:l?.nativeSymbol||"ETH",decimals:typeof l?.decimals=="number"&&isFinite(l.decimals)?l.decimals:18};return await t.request({method:"wallet_addEthereumChain",params:[{chainId:a,chainName:i,rpcUrls:o,nativeCurrency:c}]}),!0}catch{return!1}}}async function Y(r){let{sdk:l,lastWalletId:e,connectedWallet:t,amountUsd:n,fiatCurrency:a,chainShortcodes:i,tokenShortcodes:o}=r,c,d=(e||"").toLowerCase(),p=(t?.owner||t?.principal||"").toString();try{d&&Fe.has(d)?c=await l?.client?.getExternalWalletBalances?.({network:"evm",address:p,amountUsd:n,fiatCurrency:a,chainShortcodes:i,tokenShortcodes:o}):d&&st.has(d)?c=await l?.client?.getExternalWalletBalances?.({network:"sol",address:p,amountUsd:n,fiatCurrency:a,chainShortcodes:i,tokenShortcodes:o}):c=await l?.client?.getExternalWalletBalances?.({network:"ic",principal:p,amountUsd:n,fiatCurrency:a,chainShortcodes:i,tokenShortcodes:o})}catch{c={balances:[],totalBalancesUSD:0,lastUpdated:new Date}}return{balances:(c?.balances||[]).map(h=>({ledgerId:h.ledgerId,ledgerName:h.ledgerName,ledgerSymbol:h.ledgerSymbol,tokenShortcode:h.tokenShortcode??h.shortcode??null,canisterId:h.canisterId,eip3009Version:h?.eip3009Version??null,x402Accepts:h?.x402Accepts!=null?!!h.x402Accepts:void 0,balance:h.balance,formattedBalance:h.formattedBalance,decimals:h.decimals,currentPrice:h.currentPrice,lastPriceUpdate:h.lastPriceUpdate?new Date(h.lastPriceUpdate):void 0,lastUpdated:h.lastUpdated?new Date(h.lastUpdated):new Date,chainId:typeof h.chainId=="string"?h.chainId:typeof h.chainId=="number"?String(h.chainId):void 0,chainName:h.chainName||h.chain&&(h.chain.name||h.chain.chainName)||h.networkName||void 0,rpcUrlPublic:h.rpcUrlPublic,chainUuid:h.chainUuid,requiredAmount:h.requiredAmount,requiredAmountFormatted:h.requiredAmountFormatted,hasSufficientBalance:h.hasSufficientBalance,logoUrl:h.logoUrl??null})),totalBalancesUSD:c?.totalBalancesUSD,lastUpdated:c?.lastUpdated?new Date(c.lastUpdated):new Date}}function Pe(r){let l=Number(r);if(!isFinite(l)||l===0)return"0";if(Math.abs(l)<1e-5)return"< 0.00001";let t=1e5;return(Math.trunc(l*t)/t).toFixed(5).replace(/\.0+$/,"").replace(/(\.[0-9]*?)0+$/,"$1")}import{html as G}from"lit";function Ue(r){let l=parseFloat(String(r.formattedBalance||"0")),e=Number(r.currentPrice??0),t=(isFinite(l)?l:0)*(isFinite(e)?e:0);return isFinite(t)?t:0}var De=(r,l)=>Ue(l)-Ue(r);function Te(){return G`<style>
1147
+ `}import{LitElement as vt,html as he,css as wt}from"lit";import{customElement as bt,property as Et,state as R}from"lit/decorators.js";import{html as ae}from"lit";var ze=new Set(["metamask","walletconnect","coinbase","brave","rainbow","rabby","okx","trust"]),st=new Set(["phantom","solflare","backpack"]);function j(r){return r?ze.has(String(r).toLowerCase()):!1}function ot(r){return r&&(r.id||r.provider||r.key)||""}function ct(r){return r&&(r.label||r.name||r.title||r.id)||"Wallet"}function lt(r){return r&&(r.icon||r.logo||r.image)||null}function X(r){return(r||[]).map(l=>({id:ot(l),label:ct(l),icon:lt(l)}))}async function V(r,l){try{let e=l?.provider||(typeof window<"u"?window.ethereum:null);if(!e||r===void 0||r===null)return!0;let t=typeof r=="number"?r:String(r).startsWith("0x")?parseInt(String(r),16):parseInt(String(r),10);if(!Number.isFinite(t))return!0;let a=await e.request({method:"eth_chainId"});if(parseInt(a,16)===t)return!0;let i="0x"+t.toString(16);return await e.request({method:"wallet_switchEthereumChain",params:[{chainId:i}]}),!0}catch{try{let t=l?.provider||(typeof window<"u"?window.ethereum:null);if(!t||r===void 0||r===null)return!1;let a=typeof r=="number"?r:String(r).startsWith("0x")?parseInt(String(r),16):parseInt(String(r),10),n="0x"+a.toString(16),i=l?.chainName||`Network ${a}`,s=(l?.rpcUrlPublic?[l.rpcUrlPublic]:[]).filter(Boolean),o={name:l?.nativeSymbol||"ETH",symbol:l?.nativeSymbol||"ETH",decimals:typeof l?.decimals=="number"&&isFinite(l.decimals)?l.decimals:18};return await t.request({method:"wallet_addEthereumChain",params:[{chainId:n,chainName:i,rpcUrls:s,nativeCurrency:o}]}),!0}catch{return!1}}}async function Y(r){let{sdk:l,lastWalletId:e,connectedWallet:t,amountUsd:a,fiatCurrency:n,chainShortcodes:i,tokenShortcodes:s}=r,o,d=(e||"").toLowerCase(),p=(t?.owner||t?.principal||"").toString();try{d&&ze.has(d)?o=await l?.client?.getExternalWalletBalances?.({network:"evm",address:p,amountUsd:a,fiatCurrency:n,chainShortcodes:i,tokenShortcodes:s}):d&&st.has(d)?o=await l?.client?.getExternalWalletBalances?.({network:"sol",address:p,amountUsd:a,fiatCurrency:n,chainShortcodes:i,tokenShortcodes:s}):o=await l?.client?.getExternalWalletBalances?.({network:"ic",principal:p,amountUsd:a,fiatCurrency:n,chainShortcodes:i,tokenShortcodes:s})}catch{o={balances:[],totalBalancesUSD:0,lastUpdated:new Date}}return{balances:(o?.balances||[]).map(h=>({ledgerId:h.ledgerId,ledgerName:h.ledgerName,ledgerSymbol:h.ledgerSymbol,tokenShortcode:h.tokenShortcode??h.shortcode??null,canisterId:h.canisterId,eip3009Version:h?.eip3009Version??null,x402Accepts:h?.x402Accepts!=null?!!h.x402Accepts:void 0,balance:h.balance,formattedBalance:h.formattedBalance,decimals:h.decimals,currentPrice:h.currentPrice,lastPriceUpdate:h.lastPriceUpdate?new Date(h.lastPriceUpdate):void 0,lastUpdated:h.lastUpdated?new Date(h.lastUpdated):new Date,chainId:typeof h.chainId=="string"?h.chainId:typeof h.chainId=="number"?String(h.chainId):void 0,chainName:h.chainName||h.chain&&(h.chain.name||h.chain.chainName)||h.networkName||void 0,rpcUrlPublic:h.rpcUrlPublic,chainUuid:h.chainUuid,requiredAmount:h.requiredAmount,requiredAmountFormatted:h.requiredAmountFormatted,hasSufficientBalance:h.hasSufficientBalance,logoUrl:h.logoUrl??null})),totalBalancesUSD:o?.totalBalancesUSD,lastUpdated:o?.lastUpdated?new Date(o.lastUpdated):new Date}}function Pe(r){let l=Number(r);if(!isFinite(l)||l===0)return"0";if(Math.abs(l)<1e-5)return"< 0.00001";let t=1e5;return(Math.trunc(l*t)/t).toFixed(5).replace(/\.0+$/,"").replace(/(\.[0-9]*?)0+$/,"$1")}import{html as G}from"lit";function Oe(r){let l=parseFloat(String(r.formattedBalance||"0")),e=Number(r.currentPrice??0),t=(isFinite(l)?l:0)*(isFinite(e)?e:0);return isFinite(t)?t:0}var qe=(r,l)=>Oe(l)-Oe(r);function Te(){return G`<style>
1148
1148
  /* Theme-aware color variables - Light mode defaults */
1149
1149
  .modal {
1150
1150
  --icpay-background: #ffffff;
@@ -1205,7 +1205,7 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
1205
1205
  .get-started { font-size:14px; color:var(--icpay-primary); background:none; border:none; cursor:pointer; font-weight:500; }
1206
1206
  .get-started:hover { text-decoration:underline; }
1207
1207
  .muted { color:var(--icpay-muted-foreground); }
1208
- </style>`}function Le(r){let l=e=>Pe(e);return G`
1208
+ </style>`}function Ie(r){let l=e=>Pe(e);return G`
1209
1209
  <div class="header">
1210
1210
  <button class="back-button" @click=${r.onBack}>‹</button>
1211
1211
  <h1 class="title">Pay with</h1>
@@ -1216,29 +1216,29 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
1216
1216
  <div style="color:var(--icpay-error-text)">${r.error}</div>
1217
1217
  `:G`
1218
1218
  <div class="currency-list">
1219
- ${(()=>{let e=(r.balances||[]).filter(t=>t.hasSufficientBalance===!0||t.hasSufficientBalance===void 0).sort(De);return e.length>0?G`
1220
- ${e.map(t=>{let n=(t.ledgerSymbol||"").toUpperCase(),a=t.logoUrl?"":n==="ETH"?"eth-icon":n==="USDC"?"usdc-icon":n==="USDT"?"usdt-icon":"";return G`
1219
+ ${(()=>{let e=(r.balances||[]).filter(t=>t.hasSufficientBalance===!0||t.hasSufficientBalance===void 0).sort(qe);return e.length>0?G`
1220
+ ${e.map(t=>{let a=(t.ledgerSymbol||"").toUpperCase(),n=t.logoUrl?"":a==="ETH"?"eth-icon":a==="USDC"?"usdc-icon":a==="USDT"?"usdt-icon":"";return G`
1221
1221
  <div class="currency-item" @click=${()=>r.onSelect(t.tokenShortcode||t.ledgerSymbol)}>
1222
- <div class="currency-icon ${a}">
1223
- ${t.logoUrl?G`<img src="${t.logoUrl}" alt="${n} logo" style="width:100%;height:100%;object-fit:fill" />`:G`<span>${n.slice(0,1)}</span>`}
1222
+ <div class="currency-icon ${n}">
1223
+ ${t.logoUrl?G`<img src="${t.logoUrl}" alt="${a} logo" style="width:100%;height:100%;object-fit:fill" />`:G`<span>${a.slice(0,1)}</span>`}
1224
1224
  </div>
1225
1225
  <div class="currency-info">
1226
1226
  <div class="currency-name">${t.ledgerName}</div>
1227
1227
  <div class="currency-network">${t.chainName||""}</div>
1228
1228
  </div>
1229
1229
  <div class="currency-balance">
1230
- <div class="balance-amount">${l(t.formattedBalance)} ${n}</div>
1231
- <div class="balance-available">$${Ue(t).toFixed(2)}</div>
1230
+ <div class="balance-amount">${l(t.formattedBalance)} ${a}</div>
1231
+ <div class="balance-available">$${Oe(t).toFixed(2)}</div>
1232
1232
  </div>
1233
1233
  </div>
1234
1234
  `})}
1235
1235
  `:G`<div class="muted" style="margin-bottom:8px">You have no balances on verified tokens.</div>`})()}
1236
1236
 
1237
- ${(()=>{let e=(r.balances||[]).filter(t=>t.hasSufficientBalance===!1).sort(De);return e.length>0?G`
1238
- ${e.map(t=>{let n=(t.ledgerSymbol||"").toUpperCase(),a=t.logoUrl?"":n==="ETH"?"eth-icon":n==="USDC"?"usdc-icon":n==="USDT"?"usdt-icon":"";return G`
1237
+ ${(()=>{let e=(r.balances||[]).filter(t=>t.hasSufficientBalance===!1).sort(qe);return e.length>0?G`
1238
+ ${e.map(t=>{let a=(t.ledgerSymbol||"").toUpperCase(),n=t.logoUrl?"":a==="ETH"?"eth-icon":a==="USDC"?"usdc-icon":a==="USDT"?"usdt-icon":"";return G`
1239
1239
  <div class="currency-item" disabled title="Insufficient balance">
1240
- <div class="currency-icon ${a}">
1241
- ${t.logoUrl?G`<img src="${t.logoUrl}" alt="${n} logo" style="width:100%;height:100%;object-fit:fill" />`:G`<span>${n.slice(0,1)}</span>`}
1240
+ <div class="currency-icon ${n}">
1241
+ ${t.logoUrl?G`<img src="${t.logoUrl}" alt="${a} logo" style="width:100%;height:100%;object-fit:fill" />`:G`<span>${a.slice(0,1)}</span>`}
1242
1242
  </div>
1243
1243
  <div class="currency-info">
1244
1244
  <div class="currency-name">${t.ledgerName}</div>
@@ -1246,7 +1246,7 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
1246
1246
  </div>
1247
1247
  <div class="currency-balance">
1248
1248
  <div class="balance-amount">need ${t.requiredAmountFormatted||"--"}</div>
1249
- <div class="balance-available">${l(t.formattedBalance)} ${n} available</div>
1249
+ <div class="balance-available">${l(t.formattedBalance)} ${a} available</div>
1250
1250
  </div>
1251
1251
  </div>
1252
1252
  `})}
@@ -1257,7 +1257,7 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
1257
1257
  <span class="need-wallet">Need a wallet?</span>
1258
1258
  <button class="get-started" @click=${()=>{try{window.open("https://internetcomputer.org/wallets","_blank","noopener,noreferrer")}catch{}}}>Get started</button>
1259
1259
  </div>
1260
- `}function dt(r){if(r==="light"||r==="dark")return r;if(typeof document>"u")return"light";let l=document.documentElement.getAttribute("data-icpay-theme");if(l==="light"||l==="dark")return l;let e=document.documentElement.getAttribute("data-theme");return e==="light"||e==="dark"?e:"light"}function pt(r){return!r||!r.startsWith("data:")?r:r.replace(/\s+/g,"")}function ht(r,l){let e=(r||"").toLowerCase();return e==="ii"?"Internet Identity":e==="nfid"?"NFID":e==="plug"?"Plug":e==="oisy"?"Oisy":l&&l.trim()?l:r?r.charAt(0).toUpperCase()+r.slice(1):"Wallet"}function Q(r){if(!r.visible)return null;let{wallets:l,onSelect:e,onClose:t,isConnecting:n}=r,a=y=>Pe(y),i=y=>{let h=parseFloat(String(y.formattedBalance||"0")),u=Number(y.currentPrice??0),m=(isFinite(h)?h:0)*(isFinite(u)?u:0);return isFinite(m)?m:0},o=(y,h)=>i(h)-i(y),c=l.map(y=>{let h=(y.id||"").toLowerCase();return{...y,icon:y.icon??null}}),d=dt(r.theme);return ne`
1260
+ `}function dt(r){if(r==="light"||r==="dark")return r;if(typeof document>"u")return"light";let l=document.documentElement.getAttribute("data-icpay-theme");if(l==="light"||l==="dark")return l;let e=document.documentElement.getAttribute("data-theme");return e==="light"||e==="dark"?e:"light"}function pt(r){return!r||!r.startsWith("data:")?r:r.replace(/\s+/g,"")}function ht(r,l){let e=(r||"").toLowerCase();return e==="ii"?"Internet Identity":e==="nfid"?"NFID":e==="plug"?"Plug":e==="oisy"?"Oisy":l&&l.trim()?l:r?r.charAt(0).toUpperCase()+r.slice(1):"Wallet"}function Q(r){if(!r.visible)return null;let{wallets:l,onSelect:e,onClose:t,isConnecting:a}=r,n=y=>Pe(y),i=y=>{let h=parseFloat(String(y.formattedBalance||"0")),u=Number(y.currentPrice??0),g=(isFinite(h)?h:0)*(isFinite(u)?u:0);return isFinite(g)?g:0},s=(y,h)=>i(h)-i(y),o=l.map(y=>{let h=(y.id||"").toLowerCase();return{...y,icon:y.icon??null}}),d=dt(r.theme);return ae`
1261
1261
  <div class="icpay-modal-overlay" data-theme="${d}" @click=${y=>{y.target===y.currentTarget&&(y.preventDefault(),y.stopPropagation(),r.onDismiss?r.onDismiss():r.onClose())}} style="position:fixed !important;inset:0 !important;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.5);z-index:99999 !important;transform:none !important;">
1262
1262
  <style>
1263
1263
  .icpay-w-8 { width: 2rem; }
@@ -1343,28 +1343,28 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
1343
1343
  justify-content: stretch;
1344
1344
  padding: 0;
1345
1345
  }
1346
- .modal {
1347
- max-width:100%;
1348
- width:100%;
1346
+ .modal {
1347
+ max-width:100%;
1348
+ width:100%;
1349
1349
  height:auto;
1350
- max-height:50vh;
1351
- border-radius:24px 24px 0 0;
1352
- margin:0;
1350
+ max-height:50vh;
1351
+ border-radius:24px 24px 0 0;
1352
+ margin:0;
1353
1353
  padding:16px;
1354
- transform:translateY(100%);
1355
- overflow:hidden;
1356
- display:flex;
1354
+ transform:translateY(100%);
1355
+ overflow:hidden;
1356
+ display:flex;
1357
1357
  flex-direction:column;
1358
1358
  transition:transform 0.3s cubic-bezier(0.32, 0.72, 0, 1);
1359
1359
  align-self: flex-end;
1360
1360
  }
1361
- .icpay-modal-overlay:not([style*="display: none"]) .modal {
1362
- transform:translateY(0);
1361
+ .icpay-modal-overlay:not([style*="display: none"]) .modal {
1362
+ transform:translateY(0);
1363
1363
  }
1364
- .wallet-list {
1365
- overflow-y:auto;
1366
- flex:1;
1367
- min-height:0;
1364
+ .wallet-list {
1365
+ overflow-y:auto;
1366
+ flex:1;
1367
+ min-height:0;
1368
1368
  max-height:calc(50vh - 120px); /* Account for header, footer, and padding */
1369
1369
  }
1370
1370
  }
@@ -1373,7 +1373,7 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
1373
1373
  .close-button:hover { opacity:1; }
1374
1374
  .title { font-size:20px; font-weight:600; text-align:center; margin:0; }
1375
1375
  .wallet-list { display:flex; flex-direction:column; gap:0; overflow-y:auto; flex:1; padding-right:8px; padding-top:4px; scrollbar-gutter: stable; }
1376
- .wallet-item { display:flex; align-items:center; padding:16px 12px; cursor:pointer; transition:background-color 0.2s; border-radius:12px; }
1376
+ .wallet-item { display:flex; align-items:center; padding:14px 12px; cursor:pointer; transition:background-color 0.2s; border-radius:12px; }
1377
1377
  .wallet-item:hover { background-color:var(--icpay-accent); }
1378
1378
  .wallet-icon { width:48px; height:48px; border-radius:12px; margin-right:16px; display:flex; align-items:center; justify-content:center; font-size:24px; overflow:hidden; }
1379
1379
  .oisy-icon { background-color:var(--icpay-primary); }
@@ -1389,37 +1389,37 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
1389
1389
  </style>
1390
1390
  ${Te()}
1391
1391
  <div class="modal" @click=${y=>y.stopPropagation()}>
1392
- ${r.step==="balances"?ne`
1393
- ${Le({isLoading:!!r.balancesLoading,error:r.balancesError,balances:r.balances,onBack:()=>r.onBack&&r.onBack(),onSelect:y=>r.onSelectBalance&&r.onSelectBalance(y)})}
1394
- `:ne`
1392
+ ${r.step==="balances"?ae`
1393
+ ${Ie({isLoading:!!r.balancesLoading,error:r.balancesError,balances:r.balances,onBack:()=>r.onBack&&r.onBack(),onSelect:y=>r.onSelectBalance&&r.onSelectBalance(y)})}
1394
+ `:ae`
1395
1395
  <div class="header">
1396
1396
  <h1 class="title">Connect</h1>
1397
1397
  <button class="close-button" @click=${()=>{try{t()}catch{}}} aria-label="Close">×</button>
1398
1398
  </div>
1399
1399
  <div class="wallet-list">
1400
- ${r.showCreditCard&&r.onCreditCard?ne`
1400
+ ${r.showCreditCard&&r.onCreditCard?ae`
1401
1401
  <div class="wallet-item" style="border:1px solid var(--icpay-primary);background:var(--icpay-processing-bg)" @click=${()=>r.onCreditCard&&r.onCreditCard()}>
1402
1402
  <div class="wallet-icon">
1403
1403
  💳
1404
1404
  </div>
1405
1405
  <div class="wallet-info">
1406
1406
  <div class="wallet-name">${r.creditCardLabel||"Pay with credit card"}</div>
1407
- ${r.creditCardTooltip?ne`<div class="wallet-status">${r.creditCardTooltip}</div>`:null}
1407
+ ${r.creditCardTooltip?ae`<div class="wallet-status">${r.creditCardTooltip}</div>`:null}
1408
1408
  </div>
1409
1409
  </div>
1410
1410
  <div class="divider"></div>
1411
1411
  `:null}
1412
- ${(()=>{let y=[],h=null;return c.forEach(u=>{let m=(u.id||"").toLowerCase(),j=ht(u.id,u.label),Me=q(m),We=m==="phantom"||m==="backpack"?"sol":Me?"evm":"ic";h!==null&&We!==h&&y.push(ne`<div class="divider"></div>`);let _e=m==="oisy"||m==="plug"||m==="nfid"||m==="ii"?"Internet Computer":m==="phantom"||m==="backpack"?"Solana":Me?"Ethereum-compatible":"";y.push(ne`
1413
- <div class="wallet-item" style="opacity:${n?.6:1}" @click=${()=>e(u.id)}>
1412
+ ${(()=>{let y=[],h=null;return o.forEach(u=>{let g=(u.id||"").toLowerCase(),M=ht(u.id,u.label),te=j(g),de=g==="phantom"||g==="solflare"||g==="backpack"?"sol":te?"evm":"ic";h!==null&&de!==h&&y.push(ae`<div class="divider"></div>`);let Be=g==="oisy"||g==="plug"||g==="nfid"||g==="ii"?"Internet Computer":g==="phantom"||g==="solflare"||g==="backpack"?"Solana":te?"Ethereum-compatible":"";y.push(ae`
1413
+ <div class="wallet-item" style="opacity:${a?.6:1}" @click=${()=>e(u.id)}>
1414
1414
  <div class="wallet-icon">
1415
- ${u.icon?ne`<img src="${pt(u.icon)}" alt="${j} logo" class="icpay-w-8 icpay-h-8" style="object-fit:contain" />`:ne`<span>${j.charAt(0)}</span>`}
1415
+ ${u.icon?ae`<img src="${pt(u.icon)}" alt="${M} logo" class="icpay-w-8 icpay-h-8" style="object-fit:contain" />`:ae`<span>${M.charAt(0)}</span>`}
1416
1416
  </div>
1417
1417
  <div class="wallet-info">
1418
- <div class="wallet-name">${j}</div>
1419
- ${_e?ne`<div class="wallet-status">${_e}</div>`:null}
1418
+ <div class="wallet-name">${M}</div>
1419
+ ${Be?ae`<div class="wallet-status">${Be}</div>`:null}
1420
1420
  </div>
1421
1421
  </div>
1422
- `),h=We}),y})()}
1422
+ `),h=de}),y})()}
1423
1423
  </div>
1424
1424
  <div class="footer">
1425
1425
  <span class="need-wallet">Need a wallet?</span>
@@ -1485,12 +1485,12 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
1485
1485
  </style>
1486
1486
  ${Te()}
1487
1487
  <div class="modal">
1488
- ${Le({isLoading:r.isLoading,error:r.error,balances:r.balances,onBack:r.onClose,onSelect:r.onSelect})}
1488
+ ${Ie({isLoading:r.isLoading,error:r.error,balances:r.balances,onBack:r.onClose,onSelect:r.onSelect})}
1489
1489
  </div>
1490
1490
  </div>
1491
- `}function J(r){if(!r||String(r).toLowerCase()!=="coinbase")return!1;try{let l=typeof navigator<"u"?String(navigator.userAgent||"").toLowerCase():"";return l.includes("iphone")||l.includes("ipad")}catch{return!1}}function I(r){try{let l=r||{};l.adapters=l.adapters||{};let e=l.adapters.oisy||{},t=e.config||{},n={...t.transport||{},windowOpenerFeatures:"",detectNonClickEstablishment:!1};return l.adapters.oisy={...e,config:{...t,transport:n}},l}catch{return r}}function x(r,l){try{let e=l&&(l.owner||l.principal)||null,t=r&&r.account&&(r.account.owner||r.account.principal)||null,n=i=>typeof i=="string"?i:i&&typeof i.toString=="function"?i.toString():null,a=n(e)||n(t)||null;return a?{owner:a,principal:a}:l||{owner:null}}catch{return l||{owner:null}}}async function ae(r){try{let l=typeof r?.getEnabledWallets=="function"?r.getEnabledWallets.bind(r):null;if(!l)return null;let t=(l()||[]).find(c=>(c?.id||"").toLowerCase()==="oisy");if(!t||!t.adapter)return null;let n=t.adapter,a=new n({config:r?.config||{}});if(!await a.isConnected())return null;let o=await a.getPrincipal();return o&&o!=="2vxsx-fae"?o:null}catch{return null}}function gt(){try{typeof window<"u"&&window.dispatchEvent(new CustomEvent("icpay-payment-reset"))}catch{}}function mt(r){let l=r;if(!l||typeof l!="object")return;let e=l.onrampNotifyController;if(e){try{e.stop()}catch{}l.onrampNotifyController=null}let t=l.onrampPollTimer;if(t!=null){try{clearTimeout(t)}catch{}l.onrampPollTimer=null}"onrampPollingActive"in l&&(l.onrampPollingActive=!1)}function ft(r){let l=r;if(!l||typeof l!="object")return;let e=l.config,t=l.pnp;if(!(e?.useOwnWallet||!t||!e)){try{t.disconnect?.()}catch{}l.config={...e,actorProvider:void 0,connectedWallet:void 0}}}function ee(r,l){let e=r??{};if(typeof e!="object")return;let t=!!l.keepWalletConnected;gt(),e.errorMessage=null,e.errorSeverity=null,e.errorAction=null,e.processing=!1,e.showBalanceModal=!1,e.selectedSymbol=null,e.pendingAction=l.pendingAction,e.oisyReadyToPay=!1,e.showOnrampModal=!1,e.onrampUrl=null,e.onrampPaymentIntentId=null,e.onrampErrorMessage=null,t||(e.showWalletModal=!0,e.walletModalStep="connect",e.lastWalletId=null,e.walletConnected=!1),"succeeded"in e&&(e.succeeded=!1),"skipDisconnectOnce"in e&&(e.skipDisconnectOnce=!1),"oisySignerPreopened"in e&&(e.oisySignerPreopened=!1),"showProviderPicker"in e&&(e.showProviderPicker=!1),"selectedOnrampProvider"in e&&(e.selectedOnrampProvider=null),mt(r),t||ft(r);let n=r.requestUpdate;typeof n=="function"&&n.call(r)}var ze=typeof window<"u",ie=null;function Ee(r,l,e){r&&(e!==void 0?console.log(`[ICPay Widget] ${l}`,e):console.log(`[ICPay Widget] ${l}`))}var T=class extends vt{constructor(){super(...arguments);this.selectedSymbol=null;this.unlocked=!1;this.succeeded=!1;this.processing=!1;this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.walletModalStep="connect";this.oisyReadyToPay=!1;this.lastWalletId=null;this.pnp=null;this.showOnrampModal=!1;this.onrampUrl=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.transakMessageHandlerBound=null;this.onrampPollTimer=null;this.onrampPollingActive=!1;this.onrampNotifyController=null;this.showBalanceModal=!1;this.balancesLoading=!1;this.balancesError=null;this.walletBalances=[];this.sdk=null;this.onTransactionCompleted=null;this.onUnlock=null;this.onSwitchAccount=async e=>{try{if(this.pnp)try{await this.pnp.disconnect()}catch{}this.walletConnected=!1,this.config={...this.config,actorProvider:void 0,connectedWallet:void 0},this.pendingAction="pay",this.showWalletModal=!0,this.requestUpdate();try{let t=Number(this.config?.priceUsd||0),n=this.selectedSymbol||"ICP";window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"pay",type:"sendUsd",amount:t,currency:n}}))}catch{}}catch{}};this.onSelectBalanceSymbol=async e=>{let t=(this.walletBalances||[]).find(a=>a?.tokenShortcode===e);if(t?.ledgerSymbol&&(this.selectedSymbol=t.ledgerSymbol),q(this.lastWalletId)){let a=(this.walletBalances||[]).find(o=>o?.tokenShortcode===e),i=a?.chainId;this.showBalanceModal=!1,this.showWalletModal=!1,X(i,{provider:this.pnp?.getEvmProvider?.()||this.config?.evmProvider,chainName:a?.chainName,rpcUrlPublic:a?.rpcUrlPublic,nativeSymbol:a?.ledgerSymbol,decimals:a?.decimals}).then(async()=>{try{let o=E(this.config),c=Number(this.config?.priceUsd??0);if(a?.x402Accepts&&!J(this.lastWalletId))try{await o.client.createPaymentX402Usd({usdAmount:c,tokenShortcode:a?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:"evm",icpay_ledger_id:a?.ledgerId,icpay_context:"premium:x402"}},recipientAddress:(this.config?.recipientAddresses||{})?.evm||"0x0000000000000000000000000000000000000000",fiat_currency:this.config?.fiat_currency});return}catch(d){f(d,{onError:p=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:p,bubbles:!0})),v(p)&&(this.errorMessage=g(p),this.errorSeverity=b(p),this.errorAction=w(p))}})}await o.client.createPaymentUsd({usdAmount:c,tokenShortcode:a?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:"evm",icpay_ledger_id:a?.ledgerId}},recipientAddress:(this.config?.recipientAddresses||{})?.evm||"0x0000000000000000000000000000000000000000"}).catch(d=>{throw d})}catch(o){f(o,{onError:c=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:c,bubbles:!0})),v(c)&&(this.errorMessage=g(c),this.errorSeverity=b(c),this.errorAction=w(c))}})}});return}this.showBalanceModal=!1,this.showWalletModal=!1;let n=this.pendingAction;if(this.pendingAction=null,n==="pay")try{let a=(this.walletBalances||[]).find(u=>u?.tokenShortcode===e),i=E(this.config),o=Number(this.config?.priceUsd??0),c=String(a?.chainName||a?.ledgerName||"").toLowerCase(),d=c.includes("sol"),p=this.config?.recipientAddresses||{},y=d&&p.sol||p.ic,h=c.includes("ic");if(a?.x402Accepts)try{await i.client.createPaymentX402Usd({usdAmount:o,tokenShortcode:a?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:d?"sol":h?"ic":this.config?.icpay_network,icpay_ledger_id:a?.ledgerId,icpay_context:"premium:x402"}},recipientAddress:y||"",fiat_currency:this.config?.fiat_currency});return}catch(u){f(u,{onError:m=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:m,bubbles:!0})),v(m)&&(this.errorMessage=g(m),this.errorSeverity=b(m),this.errorAction=w(m))}});return}await i.client.createPaymentUsd({usdAmount:o,tokenShortcode:a?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:"ic",icpay_ledger_id:a?.ledgerId}},recipientAddress:y||"0x0000000000000000000000000000000000000000"}).catch(u=>{throw u})}catch(a){f(a,{onError:i=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:i,bubbles:!0})),v(i)&&(this.errorMessage=g(i),this.errorSeverity=b(i),this.errorAction=w(i))}})}}}async tryAutoConnectPNP(){try{if(!this.config||this.config?.useOwnWallet)return;let e=localStorage.getItem("icpay:pnp");if(!e)return;let t=JSON.parse(e);if(!t?.provider||!t?.principal)return;ie||(ie=(await import("./wallet-select-VE5FSSFG.js")).WalletSelect);let n={...this.config?.plugNPlay||{}};try{if(typeof window<"u"){let{resolveDerivationOrigin:i}=await import("./origin-44ZEXSX4.js");n.derivationOrigin=this.config?.derivationOrigin||i()}}catch{}let a=new ie(n);this.walletConnected=!1,this.config={...this.config,connectedWallet:{owner:t.principal,principal:t.principal,connected:!1}}}catch{}}async getOrCreatePnp(){if(this.pnp)return this.pnp;ie||(ie=(await import("./wallet-select-VE5FSSFG.js")).WalletSelect);let e=!!(this.config?.openOisyInNewTab||this.config?.plugNPlay?.openOisyInNewTab),t={...this.config?.plugNPlay||{}},n=this.config?.recipientAddresses;if(n&&(n.ic||n.evm||n.sol)){let i=[];n.ic&&i.push("ic"),n.evm&&i.push("evm"),n.sol&&i.push("sol"),i.length&&(t.chainTypes=i)}else this.config?.chainTypes&&(t.chainTypes=this.config.chainTypes);let a=e?I(t):t;try{if(typeof window<"u"){let{resolveDerivationOrigin:i}=await import("./origin-44ZEXSX4.js");a.derivationOrigin=this.config?.derivationOrigin||i()}}catch{}return this.pnp=new ie(a),this.pnp}async generateWalletConnectQr(e){try{let t=await this.getOrCreatePnp();return!t||typeof t.generateWalletConnectQr!="function"?null:await t.generateWalletConnectQr({onConnected:n=>{this.walletConnected=!0,this.lastWalletId="walletconnect";let a=x(this.pnp,n),i=this.pnp?.getEvmProvider?.(),o=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:a,actorProvider:(c,d)=>this.pnp.getActor({canisterId:c,idl:d,requiresSigning:!0,anon:!1}),...i?{evmProvider:i}:{},...o?{solanaProvider:o}:{}},this.sdk=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"walletconnect"}}))}catch{}try{e?.onConnected?.()}catch{}this.requestUpdate()}})}catch{return null}}async checkCoinbaseConnection(){try{return(await this.getOrCreatePnp())?.hasCoinbaseAccounts?.()??!1}catch{return!1}}async connectWallet(e){let t=await this.getOrCreatePnp();if(!t||!e)throw new Error("Wallet not available");let n=(e||"").toLowerCase(),a=await t.connect(n);if(!!!(a&&(a.connected===!0||a.principal||a.owner||t.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0,this.lastWalletId=n;let o=x(this.pnp,a),c=this.pnp?.getEvmProvider?.(),d=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:o,actorProvider:(p,y)=>this.pnp.getActor({canisterId:p,idl:y,requiresSigning:!0,anon:!1}),...c?{evmProvider:c}:{},...d?{solanaProvider:d}:{}},this.sdk=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:n}}))}catch{}this.requestUpdate()}connectedCallback(){if(super.connectedCallback(),!!ze){Ee(this.config?.debug||!1,"Premium content connected",{config:this.config}),this.tryAutoConnectPNP();try{window.addEventListener("icpay-switch-account",this.onSwitchAccount)}catch{}try{window.addEventListener("icpay-sdk-transaction-created",(()=>{this.showWalletModal=!1,this.showBalanceModal=!1,this.requestUpdate()}))}catch{}this.onTransactionCompleted=(()=>{this.unlocked=!0,this.succeeded=!0,this.processing=!1;try{window.dispatchEvent(new CustomEvent("icpay-unlock",{detail:{amount:this.config?.priceUsd,currency:this.selectedSymbol||"ICP"}}))}catch{}this.requestUpdate()});try{window.addEventListener("icpay-sdk-transaction-completed",this.onTransactionCompleted)}catch{}this.onUnlock=(()=>{this.unlocked=!0,this.succeeded=!0,this.processing=!1,this.requestUpdate()});try{window.addEventListener("icpay-unlock",this.onUnlock)}catch{}}}disconnectedCallback(){super.disconnectedCallback();try{window.removeEventListener("icpay-switch-account",this.onSwitchAccount)}catch{}if(this.onTransactionCompleted)try{window.removeEventListener("icpay-sdk-transaction-completed",this.onTransactionCompleted)}catch{}if(this.onUnlock)try{window.removeEventListener("icpay-unlock",this.onUnlock)}catch{}}updated(e){if(e.has("config")&&this.pendingAction&&this.config?.actorProvider){let t=this.pendingAction;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}this.walletModalStep!=="balances"&&!this.oisyReadyToPay&&(this.pendingAction=null,setTimeout(()=>{t==="pay"&&this.onPay()},0))}}resetPaymentFlow(){ee(this,{pendingAction:"pay"})}async onPay(){if(ze&&!this.unlocked){this.resetPaymentFlow(),Ee(this.config?.debug||!1,"Premium content payment started",{priceUsd:this.config.priceUsd,selectedSymbol:this.selectedSymbol,useOwnWallet:this.config.useOwnWallet});try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"pay",type:"sendUsd",amount:this.config.priceUsd,currency:this.selectedSymbol||"ICP"}}))}catch{}this.processing=!0;try{if(this.config.useOwnWallet){if(!this.config.actorProvider){this.pendingAction="pay",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0}));return}}else if(!this.walletConnected){Ee(this.config?.debug||!1,"Connecting to wallet via Plug N Play");try{ie||(ie=(await import("./wallet-select-VE5FSSFG.js")).WalletSelect);let t=!!(this.config?.openOisyInNewTab||this.config?.plugNPlay?.openOisyInNewTab)?I({...this.config?.plugNPlay||{}}):{...this.config?.plugNPlay||{}};this.config?.chainTypes&&(t.chainTypes=this.config.chainTypes);try{if(typeof window<"u"){let{resolveDerivationOrigin:a}=await import("./origin-44ZEXSX4.js");t.derivationOrigin=this.config?.derivationOrigin||a()}}catch{}this.pnp=new ie(t);try{let a=await ae(this.pnp);if(a){this.walletConnected=!0;let i=x(this.pnp,{owner:a,principal:a,connected:!0}),o=this.pnp?.getEvmProvider?.();this.config={...this.config,connectedWallet:i,actorProvider:(c,d)=>this.pnp.getActor({canisterId:c,idl:d,requiresSigning:!0,anon:!1}),...o?{evmProvider:o}:{}},this.sdk=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"oisy"}}))}catch{}this.onPay();return}}catch{}let n=this.pnp.getEnabledWallets();if(Ee(this.config?.debug||!1,"Available wallets",n),!n?.length)throw new Error("No wallets available");this.pendingAction="pay",this.showWalletModal=!0;return}catch(e){Ee(this.config?.debug||!1,"Wallet connection error:",e),this.errorMessage=e instanceof Error?e.message:"Wallet connection failed",this.errorSeverity="error";return}}this.walletModalStep="balances",this.showBalanceModal=!1,this.showWalletModal=!0,await this.fetchAndShowBalances("pay");return}catch(e){f(e,{onError:t=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:t,bubbles:!0})),v(t)&&(this.errorMessage=g(t),this.errorSeverity=b(t),this.errorAction=w(t))}});try{!this.config.useOwnWallet&&this.pnp&&(await this.pnp.disconnect?.(),this.walletConnected=!1,this.config={...this.config,actorProvider:void 0,connectedWallet:void 0})}catch{}}finally{this.processing=!1}}}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=e=>this.onTransakMessage(e);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(e){let t=e?.data,n=t?.event_id||t?.eventId||t?.id;if(!(!n||typeof n!="string")&&n==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;this.showOnrampModal=!1;let a=t?.data?.id||t?.id||t?.webhookData?.id||null;this.startOnrampPolling(a||void 0)}}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"createPaymentUsd",type:"onramp"}}))}catch{}this.showWalletModal=!1,setTimeout(()=>this.createOnrampIntent(),0)}async createOnrampIntent(){try{let t=await E(this.config).startOnrampUsd(this.config.priceUsd,void 0,{context:"premium:onramp",onrampPayment:!0,onrampProvider:"coinbase"}),n=t?.metadata?.onramp?.url||t?.onramp?.url||t?.metadata?.icpay_onramp?.url||t?.paymentIntent?.metadata?.icpay?.onrampUrl||t?.metadata?.icpay?.onrampUrl||null,a=t?.metadata?.icpay_payment_intent_id||t?.metadata?.paymentIntentId||t?.paymentIntentId||null,i=t?.metadata?.icpay_onramp?.errorMessage||t?.metadata?.onramp?.errorMessage||t?.paymentIntent?.metadata?.icpay?.onrampError||t?.paymentIntent?.metadata?.icpay?.errorMessage||t?.metadata?.icpay?.onrampError||t?.metadata?.icpay?.errorMessage||null;if(this.onrampPaymentIntentId=a,n){this.onrampUrl=n,this.onrampErrorMessage=null;try{window.open(n,"icpay_onramp","noopener,noreferrer");try{window.dispatchEvent(new CustomEvent("icpay-onramp-opened",{detail:{url:n}}))}catch{}}catch{}this.startOnrampPolling()}else this.onrampUrl=null,this.onrampErrorMessage=i||"Failed to obtain onramp URL",this.showOnrampModal=!0}catch(e){this.onrampUrl=null,this.onrampErrorMessage=e?.message||"Failed to obtain onramp URL",this.showOnrampModal=!0}}startOnrampPolling(e){if(this.onrampPollTimer){try{clearInterval(this.onrampPollTimer)}catch{}this.onrampPollTimer=null}if(this.onrampNotifyController){try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null}let t=this.onrampPaymentIntentId;if(!t)return;let n=E(this.config),a=()=>{if(this.detachTransakMessageListener(),this.onrampNotifyController)try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null,this.onrampPollingActive=!1};try{window.addEventListener("icpay-sdk-transaction-completed",(()=>a()),{once:!0})}catch{}this.onrampPollingActive=!0,this.onrampNotifyController=n.notifyIntentUntilComplete(t,5e3,e),this.onrampPollTimer=1}select(e){this.selectedSymbol=e}getWalletId(e){return e&&(e.id||e.provider||e.key)||""}getWalletLabel(e){return e&&(e.label||e.name||e.title||e.id)||"Wallet"}getWalletIcon(e){return e&&(e.icon||e.logo||e.image)||null}connectWithWallet(e){if(this.pnp)try{if(!e)throw new Error("No wallet ID provided");this.lastWalletId=(e||"").toLowerCase(),this.pnp.connect(e).then(n=>{if(!!!(n&&(n.connected===!0||n.principal||n.owner||this.pnp?.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:e}}))}catch{}let i=x(this.pnp,n),o=this.pnp?.getEvmProvider?.(),c=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:i,actorProvider:(d,p)=>this.pnp.getActor({canisterId:d,idl:p,requiresSigning:!0,anon:!1}),...o?{evmProvider:o}:{},...c?{solanaProvider:c}:{}},this.sdk=null,this.walletModalStep="balances",this.showBalanceModal=!1,this.showWalletModal=!0,this.fetchAndShowBalances("pay")}).catch(n=>{this.errorMessage=n instanceof Error?n.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-error",{detail:{message:this.errorMessage,code:"WALLET_CONNECT_ERROR"}}))}catch{}})}catch(t){this.errorMessage=t instanceof Error?t.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-error",{detail:{message:this.errorMessage,code:"WALLET_CONNECT_ERROR"}}))}catch{}}}async fetchAndShowBalances(e){try{this.balancesLoading=!0,this.balancesError=null,this.walletModalStep="balances",this.showBalanceModal=!1;let t=E(this.config),{balances:n}=await Y({sdk:t,lastWalletId:this.lastWalletId,connectedWallet:this.config?.connectedWallet,amountUsd:Number(this.config?.priceUsd??0),fiatCurrency:this.config?.fiat_currency});this.walletBalances=n,this.pendingAction=e}catch(t){this.walletBalances=[],this.balancesError=t&&(t.message||String(t))||"Failed to load balances"}finally{this.balancesLoading=!1}}render(){return this.config?de`
1491
+ `}function J(r){if(!r||String(r).toLowerCase()!=="coinbase")return!1;try{let l=typeof navigator<"u"?String(navigator.userAgent||"").toLowerCase():"";return l.includes("iphone")||l.includes("ipad")}catch{return!1}}function O(r){try{let l=r||{};l.adapters=l.adapters||{};let e=l.adapters.oisy||{},t=e.config||{},a={...t.transport||{},windowOpenerFeatures:"",detectNonClickEstablishment:!1};return l.adapters.oisy={...e,config:{...t,transport:a}},l}catch{return r}}function x(r,l){try{let e=l&&(l.owner||l.principal)||null,t=r&&r.account&&(r.account.owner||r.account.principal)||null,a=i=>typeof i=="string"?i:i&&typeof i.toString=="function"?i.toString():null,n=a(e)||a(t)||null;return n?{owner:n,principal:n}:l||{owner:null}}catch{return l||{owner:null}}}async function ie(r){try{let l=typeof r?.getEnabledWallets=="function"?r.getEnabledWallets.bind(r):null;if(!l)return null;let t=(l()||[]).find(o=>(o?.id||"").toLowerCase()==="oisy");if(!t||!t.adapter)return null;let a=t.adapter,n=new a({config:r?.config||{}});if(!await n.isConnected())return null;let s=await n.getPrincipal();return s&&s!=="2vxsx-fae"?s:null}catch{return null}}function gt(){try{typeof window<"u"&&window.dispatchEvent(new CustomEvent("icpay-payment-reset"))}catch{}}function mt(r){let l=r;if(!l||typeof l!="object")return;let e=l.onrampNotifyController;if(e){try{e.stop()}catch{}l.onrampNotifyController=null}let t=l.onrampPollTimer;if(t!=null){try{clearTimeout(t)}catch{}l.onrampPollTimer=null}"onrampPollingActive"in l&&(l.onrampPollingActive=!1)}function ft(r){let l=r;if(!l||typeof l!="object")return;let e=l.config,t=l.pnp;if(!(e?.useOwnWallet||!t||!e)){try{t.disconnect?.()}catch{}l.config={...e,actorProvider:void 0,connectedWallet:void 0}}}function ee(r,l){let e=r??{};if(typeof e!="object")return;let t=!!l.keepWalletConnected;gt(),e.errorMessage=null,e.errorSeverity=null,e.errorAction=null,e.processing=!1,e.showBalanceModal=!1,e.selectedSymbol=null,e.pendingAction=l.pendingAction,e.oisyReadyToPay=!1,e.showOnrampModal=!1,e.onrampUrl=null,e.onrampPaymentIntentId=null,e.onrampErrorMessage=null,t||(e.showWalletModal=!0,e.walletModalStep="connect",e.lastWalletId=null,e.walletConnected=!1),"succeeded"in e&&(e.succeeded=!1),"skipDisconnectOnce"in e&&(e.skipDisconnectOnce=!1),"oisySignerPreopened"in e&&(e.oisySignerPreopened=!1),"showProviderPicker"in e&&(e.showProviderPicker=!1),"selectedOnrampProvider"in e&&(e.selectedOnrampProvider=null),mt(r),t||ft(r);let a=r.requestUpdate;typeof a=="function"&&a.call(r)}var je=typeof window<"u",re=null;function ke(r,l,e){r&&(e!==void 0?console.log(`[ICPay Widget] ${l}`,e):console.log(`[ICPay Widget] ${l}`))}var I=class extends vt{constructor(){super(...arguments);this.selectedSymbol=null;this.unlocked=!1;this.succeeded=!1;this.processing=!1;this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.walletModalStep="connect";this.oisyReadyToPay=!1;this.lastWalletId=null;this.pnp=null;this.showOnrampModal=!1;this.onrampUrl=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.transakMessageHandlerBound=null;this.onrampPollTimer=null;this.onrampPollingActive=!1;this.onrampNotifyController=null;this.showBalanceModal=!1;this.balancesLoading=!1;this.balancesError=null;this.walletBalances=[];this.sdk=null;this.onTransactionCompleted=null;this.onUnlock=null;this.onSwitchAccount=async e=>{try{if(this.pnp)try{await this.pnp.disconnect()}catch{}this.walletConnected=!1,this.config={...this.config,actorProvider:void 0,connectedWallet:void 0},this.pendingAction="pay",this.showWalletModal=!0,this.requestUpdate();try{let t=Number(this.config?.priceUsd||0),a=this.selectedSymbol||"ICP";window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"pay",type:"sendUsd",amount:t,currency:a}}))}catch{}}catch{}};this.onSelectBalanceSymbol=async e=>{let t=(this.walletBalances||[]).find(n=>n?.tokenShortcode===e);if(t?.ledgerSymbol&&(this.selectedSymbol=t.ledgerSymbol),j(this.lastWalletId)){let n=(this.walletBalances||[]).find(s=>s?.tokenShortcode===e),i=n?.chainId;this.showBalanceModal=!1,this.showWalletModal=!1,V(i,{provider:this.pnp?.getEvmProvider?.()||this.config?.evmProvider,chainName:n?.chainName,rpcUrlPublic:n?.rpcUrlPublic,nativeSymbol:n?.ledgerSymbol,decimals:n?.decimals}).then(async()=>{try{let s=E(this.config),o=Number(this.config?.priceUsd??0);if(n?.x402Accepts&&!J(this.lastWalletId))try{await s.client.createPaymentX402Usd({usdAmount:o,tokenShortcode:n?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:"evm",icpay_ledger_id:n?.ledgerId,icpay_context:"premium:x402"}},recipientAddress:(this.config?.recipientAddresses||{})?.evm||"0x0000000000000000000000000000000000000000",fiat_currency:this.config?.fiat_currency});return}catch(d){f(d,{onError:p=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:p,bubbles:!0})),w(p)&&(this.errorMessage=m(p),this.errorSeverity=v(p),this.errorAction=b(p))}})}await s.client.createPaymentUsd({usdAmount:o,tokenShortcode:n?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:"evm",icpay_ledger_id:n?.ledgerId}},recipientAddress:(this.config?.recipientAddresses||{})?.evm||"0x0000000000000000000000000000000000000000"}).catch(d=>{throw d})}catch(s){f(s,{onError:o=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:o,bubbles:!0})),w(o)&&(this.errorMessage=m(o),this.errorSeverity=v(o),this.errorAction=b(o))}})}});return}this.showBalanceModal=!1,this.showWalletModal=!1;let a=this.pendingAction;if(this.pendingAction=null,a==="pay")try{let n=(this.walletBalances||[]).find(u=>u?.tokenShortcode===e),i=E(this.config),s=Number(this.config?.priceUsd??0),o=String(n?.chainName||n?.ledgerName||"").toLowerCase(),d=o.includes("sol"),p=this.config?.recipientAddresses||{},y=d&&p.sol||p.ic,h=o.includes("ic");if(n?.x402Accepts)try{await i.client.createPaymentX402Usd({usdAmount:s,tokenShortcode:n?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:d?"sol":h?"ic":this.config?.icpay_network,icpay_ledger_id:n?.ledgerId,icpay_context:"premium:x402"}},recipientAddress:y||"",fiat_currency:this.config?.fiat_currency});return}catch(u){f(u,{onError:g=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:g,bubbles:!0})),w(g)&&(this.errorMessage=m(g),this.errorSeverity=v(g),this.errorAction=b(g))}});return}await i.client.createPaymentUsd({usdAmount:s,tokenShortcode:n?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:"ic",icpay_ledger_id:n?.ledgerId}},recipientAddress:y||"0x0000000000000000000000000000000000000000"}).catch(u=>{throw u})}catch(n){f(n,{onError:i=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:i,bubbles:!0})),w(i)&&(this.errorMessage=m(i),this.errorSeverity=v(i),this.errorAction=b(i))}})}}}async tryAutoConnectPNP(){try{if(!this.config||this.config?.useOwnWallet)return;let e=localStorage.getItem("icpay:pnp");if(!e)return;let t=JSON.parse(e);if(!t?.provider||!t?.principal)return;re||(re=(await import("./wallet-select-3A5Z7KZJ.js")).WalletSelect);let a={...this.config?.plugNPlay||{}};try{if(typeof window<"u"){let{resolveDerivationOrigin:i}=await import("./origin-44ZEXSX4.js");a.derivationOrigin=this.config?.derivationOrigin||i()}}catch{}let n=new re(a);this.walletConnected=!1,this.config={...this.config,connectedWallet:{owner:t.principal,principal:t.principal,connected:!1}}}catch{}}async getOrCreatePnp(){if(this.pnp)return this.pnp;re||(re=(await import("./wallet-select-3A5Z7KZJ.js")).WalletSelect);let e=!!(this.config?.openOisyInNewTab||this.config?.plugNPlay?.openOisyInNewTab),t={...this.config?.plugNPlay||{}},a=this.config?.recipientAddresses;if(a&&(a.ic||a.evm||a.sol)){let i=[];a.ic&&i.push("ic"),a.evm&&i.push("evm"),a.sol&&i.push("sol"),i.length&&(t.chainTypes=i)}else this.config?.chainTypes&&(t.chainTypes=this.config.chainTypes);let n=e?O(t):t;try{if(typeof window<"u"){let{resolveDerivationOrigin:i}=await import("./origin-44ZEXSX4.js");n.derivationOrigin=this.config?.derivationOrigin||i()}}catch{}return this.pnp=new re(n),this.pnp}async generateWalletConnectQr(e){try{let t=await this.getOrCreatePnp();return!t||typeof t.generateWalletConnectQr!="function"?null:await t.generateWalletConnectQr({onConnected:a=>{this.walletConnected=!0,this.lastWalletId="walletconnect";let n=x(this.pnp,a),i=this.pnp?.getEvmProvider?.(),s=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:n,actorProvider:(o,d)=>this.pnp.getActor({canisterId:o,idl:d,requiresSigning:!0,anon:!1}),...i?{evmProvider:i}:{},...s?{solanaProvider:s}:{}},this.sdk=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"walletconnect"}}))}catch{}try{e?.onConnected?.()}catch{}this.requestUpdate()}})}catch{return null}}async checkCoinbaseConnection(){try{return(await this.getOrCreatePnp())?.hasCoinbaseAccounts?.()??!1}catch{return!1}}async connectWallet(e){let t=await this.getOrCreatePnp();if(!t||!e)throw new Error("Wallet not available");let a=(e||"").toLowerCase(),n=await t.connect(a);if(!!!(n&&(n.connected===!0||n.principal||n.owner||t.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0,this.lastWalletId=a;let s=x(this.pnp,n),o=this.pnp?.getEvmProvider?.(),d=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:s,actorProvider:(p,y)=>this.pnp.getActor({canisterId:p,idl:y,requiresSigning:!0,anon:!1}),...o?{evmProvider:o}:{},...d?{solanaProvider:d}:{}},this.sdk=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:a}}))}catch{}this.requestUpdate()}connectedCallback(){if(super.connectedCallback(),!!je){ke(this.config?.debug||!1,"Premium content connected",{config:this.config}),this.tryAutoConnectPNP();try{window.addEventListener("icpay-switch-account",this.onSwitchAccount)}catch{}try{window.addEventListener("icpay-sdk-transaction-created",(()=>{this.showWalletModal=!1,this.showBalanceModal=!1,this.requestUpdate()}))}catch{}this.onTransactionCompleted=(()=>{this.unlocked=!0,this.succeeded=!0,this.processing=!1;try{window.dispatchEvent(new CustomEvent("icpay-unlock",{detail:{amount:this.config?.priceUsd,currency:this.selectedSymbol||"ICP"}}))}catch{}this.requestUpdate()});try{window.addEventListener("icpay-sdk-transaction-completed",this.onTransactionCompleted)}catch{}this.onUnlock=(()=>{this.unlocked=!0,this.succeeded=!0,this.processing=!1,this.requestUpdate()});try{window.addEventListener("icpay-unlock",this.onUnlock)}catch{}}}disconnectedCallback(){super.disconnectedCallback();try{window.removeEventListener("icpay-switch-account",this.onSwitchAccount)}catch{}if(this.onTransactionCompleted)try{window.removeEventListener("icpay-sdk-transaction-completed",this.onTransactionCompleted)}catch{}if(this.onUnlock)try{window.removeEventListener("icpay-unlock",this.onUnlock)}catch{}}updated(e){if(e.has("config")&&this.pendingAction&&this.config?.actorProvider){let t=this.pendingAction;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}this.walletModalStep!=="balances"&&!this.oisyReadyToPay&&(this.pendingAction=null,setTimeout(()=>{t==="pay"&&this.onPay()},0))}}resetPaymentFlow(){ee(this,{pendingAction:"pay"})}async onPay(){if(je&&!this.unlocked){this.resetPaymentFlow(),ke(this.config?.debug||!1,"Premium content payment started",{priceUsd:this.config.priceUsd,selectedSymbol:this.selectedSymbol,useOwnWallet:this.config.useOwnWallet});try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"pay",type:"sendUsd",amount:this.config.priceUsd,currency:this.selectedSymbol||"ICP"}}))}catch{}this.processing=!0;try{if(this.config.useOwnWallet){if(!this.config.actorProvider){this.pendingAction="pay",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0}));return}}else if(!this.walletConnected){ke(this.config?.debug||!1,"Connecting to wallet via Plug N Play");try{re||(re=(await import("./wallet-select-3A5Z7KZJ.js")).WalletSelect);let t=!!(this.config?.openOisyInNewTab||this.config?.plugNPlay?.openOisyInNewTab)?O({...this.config?.plugNPlay||{}}):{...this.config?.plugNPlay||{}};this.config?.chainTypes&&(t.chainTypes=this.config.chainTypes);try{if(typeof window<"u"){let{resolveDerivationOrigin:n}=await import("./origin-44ZEXSX4.js");t.derivationOrigin=this.config?.derivationOrigin||n()}}catch{}this.pnp=new re(t);try{let n=await ie(this.pnp);if(n){this.walletConnected=!0;let i=x(this.pnp,{owner:n,principal:n,connected:!0}),s=this.pnp?.getEvmProvider?.();this.config={...this.config,connectedWallet:i,actorProvider:(o,d)=>this.pnp.getActor({canisterId:o,idl:d,requiresSigning:!0,anon:!1}),...s?{evmProvider:s}:{}},this.sdk=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"oisy"}}))}catch{}this.onPay();return}}catch{}let a=this.pnp.getEnabledWallets();if(ke(this.config?.debug||!1,"Available wallets",a),!a?.length)throw new Error("No wallets available");this.pendingAction="pay",this.showWalletModal=!0;return}catch(e){ke(this.config?.debug||!1,"Wallet connection error:",e),this.errorMessage=e instanceof Error?e.message:"Wallet connection failed",this.errorSeverity="error";return}}this.walletModalStep="balances",this.showBalanceModal=!1,this.showWalletModal=!0,await this.fetchAndShowBalances("pay");return}catch(e){f(e,{onError:t=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:t,bubbles:!0})),w(t)&&(this.errorMessage=m(t),this.errorSeverity=v(t),this.errorAction=b(t))}});try{!this.config.useOwnWallet&&this.pnp&&(await this.pnp.disconnect?.(),this.walletConnected=!1,this.config={...this.config,actorProvider:void 0,connectedWallet:void 0})}catch{}}finally{this.processing=!1}}}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=e=>this.onTransakMessage(e);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(e){let t=e?.data,a=t?.event_id||t?.eventId||t?.id;if(!(!a||typeof a!="string")&&a==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;this.showOnrampModal=!1;let n=t?.data?.id||t?.id||t?.webhookData?.id||null;this.startOnrampPolling(n||void 0)}}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"createPaymentUsd",type:"onramp"}}))}catch{}this.showWalletModal=!1,setTimeout(()=>this.createOnrampIntent(),0)}async createOnrampIntent(){try{let t=await E(this.config).startOnrampUsd(this.config.priceUsd,void 0,{context:"premium:onramp",onrampPayment:!0,onrampProvider:"coinbase"}),a=t?.metadata?.onramp?.url||t?.onramp?.url||t?.metadata?.icpay_onramp?.url||t?.paymentIntent?.metadata?.icpay?.onrampUrl||t?.metadata?.icpay?.onrampUrl||null,n=t?.metadata?.icpay_payment_intent_id||t?.metadata?.paymentIntentId||t?.paymentIntentId||null,i=t?.metadata?.icpay_onramp?.errorMessage||t?.metadata?.onramp?.errorMessage||t?.paymentIntent?.metadata?.icpay?.onrampError||t?.paymentIntent?.metadata?.icpay?.errorMessage||t?.metadata?.icpay?.onrampError||t?.metadata?.icpay?.errorMessage||null;if(this.onrampPaymentIntentId=n,a){this.onrampUrl=a,this.onrampErrorMessage=null;try{window.open(a,"icpay_onramp","noopener,noreferrer");try{window.dispatchEvent(new CustomEvent("icpay-onramp-opened",{detail:{url:a}}))}catch{}}catch{}this.startOnrampPolling()}else this.onrampUrl=null,this.onrampErrorMessage=i||"Failed to obtain onramp URL",this.showOnrampModal=!0}catch(e){this.onrampUrl=null,this.onrampErrorMessage=e?.message||"Failed to obtain onramp URL",this.showOnrampModal=!0}}startOnrampPolling(e){if(this.onrampPollTimer){try{clearInterval(this.onrampPollTimer)}catch{}this.onrampPollTimer=null}if(this.onrampNotifyController){try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null}let t=this.onrampPaymentIntentId;if(!t)return;let a=E(this.config),n=()=>{if(this.detachTransakMessageListener(),this.onrampNotifyController)try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null,this.onrampPollingActive=!1};try{window.addEventListener("icpay-sdk-transaction-completed",(()=>n()),{once:!0})}catch{}this.onrampPollingActive=!0,this.onrampNotifyController=a.notifyIntentUntilComplete(t,5e3,e),this.onrampPollTimer=1}select(e){this.selectedSymbol=e}getWalletId(e){return e&&(e.id||e.provider||e.key)||""}getWalletLabel(e){return e&&(e.label||e.name||e.title||e.id)||"Wallet"}getWalletIcon(e){return e&&(e.icon||e.logo||e.image)||null}connectWithWallet(e){if(this.pnp)try{if(!e)throw new Error("No wallet ID provided");this.lastWalletId=(e||"").toLowerCase(),this.pnp.connect(e).then(a=>{if(!!!(a&&(a.connected===!0||a.principal||a.owner||this.pnp?.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:e}}))}catch{}let i=x(this.pnp,a),s=this.pnp?.getEvmProvider?.(),o=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:i,actorProvider:(d,p)=>this.pnp.getActor({canisterId:d,idl:p,requiresSigning:!0,anon:!1}),...s?{evmProvider:s}:{},...o?{solanaProvider:o}:{}},this.sdk=null,this.walletModalStep="balances",this.showBalanceModal=!1,this.showWalletModal=!0,this.fetchAndShowBalances("pay")}).catch(a=>{this.errorMessage=a instanceof Error?a.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-error",{detail:{message:this.errorMessage,code:"WALLET_CONNECT_ERROR"}}))}catch{}})}catch(t){this.errorMessage=t instanceof Error?t.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-error",{detail:{message:this.errorMessage,code:"WALLET_CONNECT_ERROR"}}))}catch{}}}async fetchAndShowBalances(e){try{this.balancesLoading=!0,this.balancesError=null,this.walletModalStep="balances",this.showBalanceModal=!1;let t=E(this.config),{balances:a}=await Y({sdk:t,lastWalletId:this.lastWalletId,connectedWallet:this.config?.connectedWallet,amountUsd:Number(this.config?.priceUsd??0),fiatCurrency:this.config?.fiat_currency});this.walletBalances=a,this.pendingAction=e}catch(t){this.walletBalances=[],this.balancesError=t&&(t.message||String(t))||"Failed to load balances"}finally{this.balancesLoading=!1}}render(){return this.config?he`
1492
1492
  <div class="icpay-card icpay-section icpay-widget-base">
1493
- ${this.config?.progressBar?.enabled!==!1?de`
1493
+ ${this.config?.progressBar?.enabled!==!1?he`
1494
1494
  <icpay-progress-bar
1495
1495
  .debug=${!!this.config?.debug}
1496
1496
  .theme=${this.config?.theme}
@@ -1500,7 +1500,7 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
1500
1500
  `:null}
1501
1501
  <div class="image-container">
1502
1502
  <div class="locked-image ${this.unlocked?"unlocked":""}" style="background-image:url('${this.config.imageUrl||""}')"></div>
1503
- ${this.unlocked?null:de`<div class="lock-overlay">🔒</div>`}
1503
+ ${this.unlocked?null:he`<div class="lock-overlay">🔒</div>`}
1504
1504
  </div>
1505
1505
 
1506
1506
  <div class="pricing">
@@ -1514,19 +1514,19 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
1514
1514
  ${this.unlocked?"Unlocked":this.processing?"Processing\u2026":(this.config?.buttonLabel||"Pay with crypto").replace("{amount}",`${Number(this.config?.priceUsd??0).toFixed(2)}`).replace("{symbol}",this.selectedSymbol||"ICP")}
1515
1515
  </button>
1516
1516
 
1517
- ${this.errorMessage?de`
1517
+ ${this.errorMessage?he`
1518
1518
  <div class="error-message ${this.errorSeverity}" style="margin-top: 12px; padding: 8px 12px; border-radius: 6px; font-size: 14px; text-align: center;">
1519
1519
  ${this.errorMessage}
1520
- ${this.errorAction?de`
1520
+ ${this.errorAction?he`
1521
1521
  <button style="margin-left: 8px; padding: 4px 8px; background: transparent; border: 1px solid currentColor; border-radius: 4px; font-size: 12px; cursor: pointer;">
1522
1522
  ${this.errorAction}
1523
1523
  </button>
1524
1524
  `:""}
1525
1525
  </div>
1526
1526
  `:""}
1527
- ${(()=>{let e=this.pnp?.getEnabledWallets?.()||[],t=V(e),n=this.config?.theme?typeof this.config.theme=="string"?this.config.theme:this.config.theme.mode||"light":void 0;return Q({visible:!!(this.showWalletModal&&this.pnp),wallets:t,isConnecting:!1,step:this.walletModalStep,balances:this.walletModalStep==="balances"?this.walletBalances:[],balancesLoading:this.walletModalStep==="balances"?this.balancesLoading:!1,balancesError:this.walletModalStep==="balances"?this.balancesError:null,onSelectBalance:a=>this.onSelectBalanceSymbol(a),onBack:()=>{this.walletModalStep="connect"},onSwitchAccount:()=>this.onSwitchAccount(null),onSelect:a=>this.connectWithWallet(a),onClose:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-cancelled",{detail:{reason:"user_cancelled"}}))}catch{}},onDismiss:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1},onCreditCard:this.config?.onramp?.enabled===!0&&this.config?.onrampDisabled!==!0?()=>this.startOnramp():void 0,creditCardLabel:this.config?.onramp?.creditCardLabel||"Pay with credit card",showCreditCard:this.config?.onramp?.enabled===!0&&this.config?.onrampDisabled!==!0,creditCardTooltip:(()=>{let i=Number(this.config?.priceUsd||0);return i>0&&i<5&&this.config?.onramp?.enabled===!0&&this.config?.onrampDisabled!==!0?`Note: Minimum card amount is $5. You will pay about $${(5-i).toFixed(2)} more.`:null})(),oisyReadyToPay:this.oisyReadyToPay,onOisyPay:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1,this.onPay()},theme:n})})()}
1527
+ ${(()=>{let e=this.pnp?.getEnabledWallets?.()||[],t=X(e),a=this.config?.theme?typeof this.config.theme=="string"?this.config.theme:this.config.theme.mode||"light":void 0;return Q({visible:!!(this.showWalletModal&&this.pnp),wallets:t,isConnecting:!1,step:this.walletModalStep,balances:this.walletModalStep==="balances"?this.walletBalances:[],balancesLoading:this.walletModalStep==="balances"?this.balancesLoading:!1,balancesError:this.walletModalStep==="balances"?this.balancesError:null,onSelectBalance:n=>this.onSelectBalanceSymbol(n),onBack:()=>{this.walletModalStep="connect"},onSwitchAccount:()=>this.onSwitchAccount(null),onSelect:n=>this.connectWithWallet(n),onClose:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-cancelled",{detail:{reason:"user_cancelled"}}))}catch{}},onDismiss:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1},onCreditCard:this.config?.onramp?.enabled===!0&&this.config?.onrampDisabled!==!0?()=>this.startOnramp():void 0,creditCardLabel:this.config?.onramp?.creditCardLabel||"Pay with credit card",showCreditCard:this.config?.onramp?.enabled===!0&&this.config?.onrampDisabled!==!0,creditCardTooltip:(()=>{let i=Number(this.config?.priceUsd||0);return i>0&&i<5&&this.config?.onramp?.enabled===!0&&this.config?.onrampDisabled!==!0?`Note: Minimum card amount is $5. You will pay about $${(5-i).toFixed(2)} more.`:null})(),oisyReadyToPay:this.oisyReadyToPay,onOisyPay:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1,this.onPay()},theme:a})})()}
1528
1528
 
1529
- ${(()=>{let e=this.config?.theme?typeof this.config.theme=="string"?this.config.theme:this.config.theme.mode||"light":void 0;return de`
1529
+ ${(()=>{let e=this.config?.theme?typeof this.config.theme=="string"?this.config.theme:this.config.theme.mode||"light":void 0;return he`
1530
1530
  ${Z({visible:this.showBalanceModal,isLoading:this.balancesLoading,error:this.balancesError,balances:this.walletBalances,onSelect:t=>this.onSelectBalanceSymbol(t),onClose:()=>{this.showBalanceModal=!1},theme:e})}
1531
1531
 
1532
1532
  ${H({visible:this.showOnrampModal,url:this.onrampUrl||void 0,errorMessage:this.onrampErrorMessage||void 0,width:this.config?.onramp?.width,height:this.config?.onramp?.height,onClose:()=>{this.showOnrampModal=!1},onBack:()=>{this.showOnrampModal=!1,this.showWalletModal=!0},title:"Pay with credit card",theme:e})}
@@ -1535,7 +1535,7 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
1535
1535
  <a href="https://icpay.org" target="_blank" rel="noopener noreferrer">Powered by icpay</a>
1536
1536
  </div>
1537
1537
  </div>
1538
- `:de`<div class="icpay-card icpay-section">Loading...</div>`}};T.styles=[K,wt`
1538
+ `:he`<div class="icpay-card icpay-section">Loading...</div>`}};I.styles=[K,wt`
1539
1539
  .image-container {
1540
1540
  position: relative;
1541
1541
  border-radius: 16px;
@@ -1586,9 +1586,9 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
1586
1586
  border-color: var(--icpay-error-border);
1587
1587
  color: var(--icpay-error-text);
1588
1588
  }
1589
- `],s([Et({type:Object})],T.prototype,"config",2),s([$()],T.prototype,"selectedSymbol",2),s([$()],T.prototype,"unlocked",2),s([$()],T.prototype,"succeeded",2),s([$()],T.prototype,"processing",2),s([$()],T.prototype,"errorMessage",2),s([$()],T.prototype,"errorSeverity",2),s([$()],T.prototype,"errorAction",2),s([$()],T.prototype,"walletConnected",2),s([$()],T.prototype,"pendingAction",2),s([$()],T.prototype,"showWalletModal",2),s([$()],T.prototype,"walletModalStep",2),s([$()],T.prototype,"oisyReadyToPay",2),s([$()],T.prototype,"lastWalletId",2),s([$()],T.prototype,"showOnrampModal",2),s([$()],T.prototype,"onrampUrl",2),s([$()],T.prototype,"onrampPaymentIntentId",2),s([$()],T.prototype,"onrampErrorMessage",2),s([$()],T.prototype,"showBalanceModal",2),s([$()],T.prototype,"balancesLoading",2),s([$()],T.prototype,"balancesError",2),s([$()],T.prototype,"walletBalances",2),T=s([bt("icpay-premium-content")],T);import{LitElement as xt,html as pe,css as kt}from"lit";import{customElement as St,property as Ct,state as U}from"lit/decorators.js";var qe=typeof window<"u",re=null;function xe(r,l,e){r&&(e!==void 0?console.log(`[ICPay Widget] ${l}`,e):console.log(`[ICPay Widget] ${l}`))}var W=class extends xt{constructor(){super(...arguments);this.selectedAmount=1;this.selectedSymbol=null;this.total=0;this.processing=!1;this.succeeded=!1;this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.walletModalStep="connect";this.oisyReadyToPay=!1;this.lastWalletId=null;this.pnp=null;this.showOnrampModal=!1;this.onrampUrl=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.transakMessageHandlerBound=null;this.onrampPollTimer=null;this.onrampPollingActive=!1;this.onrampNotifyController=null;this.sdk=null;this.showBalanceModal=!1;this.balancesLoading=!1;this.balancesError=null;this.walletBalances=[];this.onSwitchAccount=async e=>{try{if(this.pnp)try{await this.pnp.disconnect()}catch{}this.walletConnected=!1,this.config={...this.config,actorProvider:void 0,connectedWallet:void 0},this.pendingAction="tip",this.showWalletModal=!0,this.requestUpdate();try{let t=Number(this.selectedAmount||0),n=this.selectedSymbol||"ICP";window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"tip",type:"sendUsd",amount:t,currency:n}}))}catch{}}catch{}};this.onSelectBalanceSymbol=async e=>{let t=(this.walletBalances||[]).find(a=>a?.tokenShortcode===e);if(t?.ledgerSymbol&&(this.selectedSymbol=t.ledgerSymbol),this.showBalanceModal=!1,this.showWalletModal=!1,q(this.lastWalletId)){let a=(this.walletBalances||[]).find(o=>o?.tokenShortcode===e),i=a?.chainId;X(i,{provider:this.pnp?.getEvmProvider?.()||this.config?.evmProvider,chainName:a?.chainName,rpcUrlPublic:a?.rpcUrlPublic,nativeSymbol:a?.ledgerSymbol,decimals:a?.decimals}).then(async()=>{try{let o=E(this.config),c=Number(this.selectedAmount||0);if(a?.x402Accepts&&!J(this.lastWalletId))try{await o.client.createPaymentX402Usd({usdAmount:c,tokenShortcode:a?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:"evm",icpay_ledger_id:a?.ledgerId,icpay_context:"tip:x402"}},recipientAddress:(this.config?.recipientAddresses||{})?.evm||"0x0000000000000000000000000000000000000000",fiat_currency:this.config?.fiat_currency}),this.showBalanceModal=!1;return}catch(d){f(d,{onError:p=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:p,bubbles:!0})),v(p)&&(this.errorMessage=g(p),this.errorSeverity=b(p),this.errorAction=w(p))}})}await o.client.createPaymentUsd({usdAmount:c,tokenShortcode:a?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:"evm",icpay_ledger_id:a?.ledgerId}},recipientAddress:(this.config?.recipientAddresses||{})?.evm||"0x0000000000000000000000000000000000000000"}).catch(d=>{throw d})}catch(o){f(o,{onError:c=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:c,bubbles:!0})),v(c)&&(this.errorMessage=g(c),this.errorSeverity=b(c),this.errorAction=w(c))}})}this.showBalanceModal=!1});return}let n=this.pendingAction;if(this.pendingAction=null,n==="tip")try{let a=(this.walletBalances||[]).find(u=>u?.tokenShortcode===e),i=E(this.config),o=Number(this.selectedAmount||0),c=String(a?.ledgerName||a?.chainName||"").toLowerCase(),d=c.includes("sol"),p=c.includes("ic"),y=this.config?.recipientAddresses||{},h=d&&y.sol||y.ic;if(a?.x402Accepts)try{await i.client.createPaymentX402Usd({usdAmount:o,tokenShortcode:a?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:d?"sol":p?"ic":this.config?.icpay_network,icpay_ledger_id:a?.ledgerId,icpay_context:"tip:x402"}},recipientAddress:h||"",fiat_currency:this.config?.fiat_currency});return}catch(u){f(u,{onError:m=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:m,bubbles:!0})),v(m)&&(this.errorMessage=g(m),this.errorSeverity=b(m),this.errorAction=w(m))}});return}await i.client.createPaymentUsd({usdAmount:o,tokenShortcode:a?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:"ic",icpay_ledger_id:a?.ledgerId}},recipientAddress:h||"0x0000000000000000000000000000000000000000"}).catch(u=>{throw u})}catch(a){f(a,{onError:i=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:i,bubbles:!0})),v(i)&&(this.errorMessage=g(i),this.errorSeverity=b(i),this.errorAction=w(i))}})}}}async tryAutoConnectPNP(){try{if(!this.config||this.config?.useOwnWallet)return;let e=localStorage.getItem("icpay:pnp");if(!e)return;let t=JSON.parse(e);if(!t?.provider||!t?.principal)return;re||(re=(await import("./wallet-select-VE5FSSFG.js")).WalletSelect);let n=I({...this.config?.plugNPlay||{}});try{if(typeof window<"u"){let{resolveDerivationOrigin:i}=await import("./origin-44ZEXSX4.js");n.derivationOrigin=this.config?.derivationOrigin||i()}}catch{}let a=new re(n);this.walletConnected=!1,this.config={...this.config,connectedWallet:{owner:t.principal,principal:t.principal,connected:!1}}}catch{}}get amounts(){return this.config?.amountsUsd||[1,5,10]}async getOrCreatePnp(){if(this.pnp)return this.pnp;re||(re=(await import("./wallet-select-VE5FSSFG.js")).WalletSelect);let e=!!(this.config?.openOisyInNewTab||this.config?.plugNPlay?.openOisyInNewTab),t={...this.config?.plugNPlay||{}},n=this.config?.recipientAddresses;if(n&&(n.ic||n.evm||n.sol)){let i=[];n.ic&&i.push("ic"),n.evm&&i.push("evm"),n.sol&&i.push("sol"),i.length&&(t.chainTypes=i)}else this.config?.chainTypes&&(t.chainTypes=this.config.chainTypes);let a=e?I(t):t;try{if(typeof window<"u"){let{resolveDerivationOrigin:i}=await import("./origin-44ZEXSX4.js");a.derivationOrigin=this.config?.derivationOrigin||i()}}catch{}return this.pnp=new re(a),this.pnp}async generateWalletConnectQr(e){try{let t=await this.getOrCreatePnp();return!t||typeof t.generateWalletConnectQr!="function"?null:await t.generateWalletConnectQr({onConnected:n=>{this.walletConnected=!0,this.lastWalletId="walletconnect";let a=x(this.pnp,n),i=this.pnp?.getEvmProvider?.(),o=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:a,actorProvider:(c,d)=>this.pnp.getActor({canisterId:c,idl:d,requiresSigning:!0,anon:!1}),...i?{evmProvider:i}:{},...o?{solanaProvider:o}:{}},this.sdk=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"walletconnect"}}))}catch{}try{e?.onConnected?.()}catch{}this.requestUpdate()}})}catch{return null}}async checkCoinbaseConnection(){try{return(await this.getOrCreatePnp())?.hasCoinbaseAccounts?.()??!1}catch{return!1}}async connectWallet(e){let t=await this.getOrCreatePnp();if(!t||!e)throw new Error("Wallet not available");let n=(e||"").toLowerCase(),a=await t.connect(n);if(!!!(a&&(a.connected===!0||a.principal||a.owner||t.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0,this.lastWalletId=n;let o=x(this.pnp,a),c=this.pnp?.getEvmProvider?.(),d=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:o,actorProvider:(p,y)=>this.pnp.getActor({canisterId:p,idl:y,requiresSigning:!0,anon:!1}),...c?{evmProvider:c}:{},...d?{solanaProvider:d}:{}},this.sdk=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:n}}))}catch{}this.requestUpdate()}connectedCallback(){if(super.connectedCallback(),!!qe){xe(this.config?.debug||!1,"Tip jar connected",{config:this.config}),this.config&&this.config.defaultAmountUsd&&(this.selectedAmount=this.config.defaultAmountUsd),this.tryAutoConnectPNP();try{window.addEventListener("icpay-switch-account",this.onSwitchAccount)}catch{}try{window.addEventListener("icpay-sdk-transaction-created",(()=>{this.showWalletModal=!1,this.requestUpdate()}))}catch{}}}updated(e){if(e.has("config")&&this.pendingAction&&this.config?.actorProvider){let t=this.pendingAction;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}this.walletModalStep!=="balances"&&!this.oisyReadyToPay&&(this.pendingAction=null,setTimeout(()=>{t==="tip"&&this.tip()},0))}}selectAmount(e){this.selectedAmount=e}selectSymbol(e){this.selectedSymbol=e}get fillPercentage(){return Math.min(this.total/50*100,100)}resetPaymentFlow(){ee(this,{pendingAction:"tip"})}async tip(){if(qe){this.resetPaymentFlow(),xe(this.config?.debug||!1,"Tip button clicked!",{config:this.config,processing:this.processing});try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"tip",type:"sendUsd",amount:this.selectedAmount,currency:this.selectedSymbol||"ICP"}}))}catch{}this.processing=!0;try{if(this.config.useOwnWallet){if(!this.config.actorProvider){this.pendingAction="tip",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0}));return}}else if(!this.walletConnected){xe(this.config?.debug||!1,"Connecting to wallet via wallet");try{re||(re=(await import("./wallet-select-VE5FSSFG.js")).WalletSelect);let t=!!(this.config?.openOisyInNewTab||this.config?.plugNPlay?.openOisyInNewTab)?I({...this.config?.plugNPlay||{}}):{...this.config?.plugNPlay||{}};this.config?.chainTypes&&(t.chainTypes=this.config.chainTypes);try{if(typeof window<"u"){let{resolveDerivationOrigin:a}=await import("./origin-44ZEXSX4.js");t.derivationOrigin=this.config?.derivationOrigin||a()}}catch{}this.pnp=new re(t);try{let a=await ae(this.pnp);if(a){this.walletConnected=!0;let i=x(this.pnp,{owner:a,principal:a,connected:!0}),o=this.pnp?.getEvmProvider?.();this.config={...this.config,connectedWallet:i,actorProvider:(c,d)=>this.pnp.getActor({canisterId:c,idl:d,requiresSigning:!0,anon:!1}),...o?{evmProvider:o}:{}},this.sdk=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"oisy"}}))}catch{}this.tip();return}}catch{}let n=this.pnp.getEnabledWallets();if(xe(this.config?.debug||!1,"Available wallets",n),!n?.length)throw new Error("No wallets available");this.pendingAction="tip",this.showWalletModal=!0;return}catch(e){xe(this.config?.debug||!1,"Wallet connection error:",e),this.errorMessage=e instanceof Error?e.message:"Wallet connection failed",this.errorSeverity="error";return}}this.showWalletModal=!0,await this.fetchAndShowBalances();return}catch(e){f(e,{onError:t=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:t,bubbles:!0})),v(t)&&(this.errorMessage=g(t),this.errorSeverity=b(t),this.errorAction=w(t))}});try{!this.config.useOwnWallet&&this.pnp&&(await this.pnp.disconnect?.(),this.walletConnected=!1,this.config={...this.config,actorProvider:void 0,connectedWallet:void 0})}catch{}}finally{this.processing=!1}}}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=e=>this.onTransakMessage(e);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(e){let t=e?.data,n=t?.event_id||t?.eventId||t?.id;if(!(!n||typeof n!="string")&&n==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;this.showOnrampModal=!1;let a=t?.data?.id||t?.id||t?.webhookData?.id||null;this.startOnrampPolling(a||void 0)}}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"createPaymentUsd",type:"onramp"}}))}catch{}this.showWalletModal=!1,setTimeout(()=>this.createOnrampIntent(),0)}async createOnrampIntent(){try{let t=await E(this.config).startOnrampUsd(this.selectedAmount,void 0,{context:"tip:onramp",onrampPayment:!0,onrampProvider:this?.selectedOnrampProvider||"coinbase"}),n=t?.metadata?.onramp?.url||t?.onramp?.url||t?.metadata?.icpay_onramp?.url||t?.paymentIntent?.metadata?.icpay?.onrampUrl||t?.metadata?.icpay?.onrampUrl||null,a=t?.metadata?.icpay_payment_intent_id||t?.metadata?.paymentIntentId||t?.paymentIntentId||null,i=t?.metadata?.icpay_onramp?.errorMessage||t?.metadata?.onramp?.errorMessage||t?.paymentIntent?.metadata?.icpay?.onrampError||t?.paymentIntent?.metadata?.icpay?.errorMessage||t?.metadata?.icpay?.onrampError||t?.metadata?.icpay?.errorMessage||null;if(this.onrampPaymentIntentId=a,n){this.onrampUrl=n,this.onrampErrorMessage=null;try{window.open(n,"icpay_onramp","noopener,noreferrer");try{window.dispatchEvent(new CustomEvent("icpay-onramp-opened",{detail:{url:n}}))}catch{}}catch{}this.startOnrampPolling()}else this.onrampUrl=null,this.onrampErrorMessage=i||"Failed to obtain onramp sessionId",this.showOnrampModal=!0}catch(e){this.onrampUrl=null,this.onrampErrorMessage=e?.message||"Failed to obtain onramp sessionId",this.showOnrampModal=!0}}startOnrampPolling(e){if(this.onrampPollTimer){try{clearInterval(this.onrampPollTimer)}catch{}this.onrampPollTimer=null}if(this.onrampNotifyController){try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null}let t=this.onrampPaymentIntentId;if(!t)return;let n=E(this.config),a=()=>{if(this.detachTransakMessageListener(),this.onrampNotifyController)try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null,this.onrampPollingActive=!1};try{window.addEventListener("icpay-sdk-transaction-completed",(()=>a()),{once:!0})}catch{}this.onrampPollingActive=!0,this.onrampNotifyController=n.notifyIntentUntilComplete(t,5e3,e),this.onrampPollTimer=1}getWalletId(e){return e&&(e.id||e.provider||e.key)||""}getWalletLabel(e){return e&&(e.label||e.name||e.title||e.id)||"Wallet"}getWalletIcon(e){return e&&(e.icon||e.logo||e.image)||null}connectWithWallet(e){if(this.pnp)try{if(!e)throw new Error("No wallet ID provided");this.lastWalletId=(e||"").toLowerCase(),this.pnp.connect(e).then(n=>{if(!!!(n&&(n.connected===!0||n.principal||n.owner||this.pnp?.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:e}}))}catch{}let i=x(this.pnp,n),o=this.pnp?.getEvmProvider?.(),c=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:i,actorProvider:(d,p)=>this.pnp.getActor({canisterId:d,idl:p,requiresSigning:!0,anon:!1}),...o?{evmProvider:o}:{},...c?{solanaProvider:c}:{}},this.sdk=null,this.walletModalStep="balances",this.showBalanceModal=!1,this.showWalletModal=!0,this.fetchAndShowBalances()}).catch(n=>{this.errorMessage=n instanceof Error?n.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-error",{detail:{message:this.errorMessage,code:"WALLET_CONNECT_ERROR"}}))}catch{}})}catch(t){this.errorMessage=t instanceof Error?t.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-error",{detail:{message:this.errorMessage,code:"WALLET_CONNECT_ERROR"}}))}catch{}}}async fetchAndShowBalances(){try{this.balancesLoading=!0,this.balancesError=null,this.walletModalStep="balances",this.showBalanceModal=!1;let e=E(this.config),{balances:t}=await Y({sdk:e,lastWalletId:this.lastWalletId,connectedWallet:this.config?.connectedWallet,amountUsd:Number(this.selectedAmount||0),fiatCurrency:this.config?.fiat_currency,chainShortcodes:this.config?.chainShortcodes,tokenShortcodes:this.config?.tokenShortcodes});this.walletBalances=t}catch(e){this.walletBalances=[],this.balancesError=e&&(e.message||String(e))||"Failed to load balances"}finally{this.balancesLoading=!1}}render(){return this.config?pe`
1589
+ `],c([Et({type:Object})],I.prototype,"config",2),c([R()],I.prototype,"selectedSymbol",2),c([R()],I.prototype,"unlocked",2),c([R()],I.prototype,"succeeded",2),c([R()],I.prototype,"processing",2),c([R()],I.prototype,"errorMessage",2),c([R()],I.prototype,"errorSeverity",2),c([R()],I.prototype,"errorAction",2),c([R()],I.prototype,"walletConnected",2),c([R()],I.prototype,"pendingAction",2),c([R()],I.prototype,"showWalletModal",2),c([R()],I.prototype,"walletModalStep",2),c([R()],I.prototype,"oisyReadyToPay",2),c([R()],I.prototype,"lastWalletId",2),c([R()],I.prototype,"showOnrampModal",2),c([R()],I.prototype,"onrampUrl",2),c([R()],I.prototype,"onrampPaymentIntentId",2),c([R()],I.prototype,"onrampErrorMessage",2),c([R()],I.prototype,"showBalanceModal",2),c([R()],I.prototype,"balancesLoading",2),c([R()],I.prototype,"balancesError",2),c([R()],I.prototype,"walletBalances",2),I=c([bt("icpay-premium-content")],I);import{LitElement as xt,html as ye,css as kt}from"lit";import{customElement as St,property as Ct,state as _}from"lit/decorators.js";var Ke=typeof window<"u",se=null;function Se(r,l,e){r&&(e!==void 0?console.log(`[ICPay Widget] ${l}`,e):console.log(`[ICPay Widget] ${l}`))}var A=class extends xt{constructor(){super(...arguments);this.selectedAmount=1;this.selectedSymbol=null;this.total=0;this.processing=!1;this.succeeded=!1;this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.walletModalStep="connect";this.oisyReadyToPay=!1;this.lastWalletId=null;this.pnp=null;this.showOnrampModal=!1;this.onrampUrl=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.transakMessageHandlerBound=null;this.onrampPollTimer=null;this.onrampPollingActive=!1;this.onrampNotifyController=null;this.sdk=null;this.showBalanceModal=!1;this.balancesLoading=!1;this.balancesError=null;this.walletBalances=[];this.onSwitchAccount=async e=>{try{if(this.pnp)try{await this.pnp.disconnect()}catch{}this.walletConnected=!1,this.config={...this.config,actorProvider:void 0,connectedWallet:void 0},this.pendingAction="tip",this.showWalletModal=!0,this.requestUpdate();try{let t=Number(this.selectedAmount||0),a=this.selectedSymbol||"ICP";window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"tip",type:"sendUsd",amount:t,currency:a}}))}catch{}}catch{}};this.onSelectBalanceSymbol=async e=>{let t=(this.walletBalances||[]).find(n=>n?.tokenShortcode===e);if(t?.ledgerSymbol&&(this.selectedSymbol=t.ledgerSymbol),this.showBalanceModal=!1,this.showWalletModal=!1,j(this.lastWalletId)){let n=(this.walletBalances||[]).find(s=>s?.tokenShortcode===e),i=n?.chainId;V(i,{provider:this.pnp?.getEvmProvider?.()||this.config?.evmProvider,chainName:n?.chainName,rpcUrlPublic:n?.rpcUrlPublic,nativeSymbol:n?.ledgerSymbol,decimals:n?.decimals}).then(async()=>{try{let s=E(this.config),o=Number(this.selectedAmount||0);if(n?.x402Accepts&&!J(this.lastWalletId))try{await s.client.createPaymentX402Usd({usdAmount:o,tokenShortcode:n?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:"evm",icpay_ledger_id:n?.ledgerId,icpay_context:"tip:x402"}},recipientAddress:(this.config?.recipientAddresses||{})?.evm||"0x0000000000000000000000000000000000000000",fiat_currency:this.config?.fiat_currency}),this.showBalanceModal=!1;return}catch(d){f(d,{onError:p=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:p,bubbles:!0})),w(p)&&(this.errorMessage=m(p),this.errorSeverity=v(p),this.errorAction=b(p))}})}await s.client.createPaymentUsd({usdAmount:o,tokenShortcode:n?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:"evm",icpay_ledger_id:n?.ledgerId}},recipientAddress:(this.config?.recipientAddresses||{})?.evm||"0x0000000000000000000000000000000000000000"}).catch(d=>{throw d})}catch(s){f(s,{onError:o=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:o,bubbles:!0})),w(o)&&(this.errorMessage=m(o),this.errorSeverity=v(o),this.errorAction=b(o))}})}this.showBalanceModal=!1});return}let a=this.pendingAction;if(this.pendingAction=null,a==="tip")try{let n=(this.walletBalances||[]).find(u=>u?.tokenShortcode===e),i=E(this.config),s=Number(this.selectedAmount||0),o=String(n?.ledgerName||n?.chainName||"").toLowerCase(),d=o.includes("sol"),p=o.includes("ic"),y=this.config?.recipientAddresses||{},h=d&&y.sol||y.ic;if(n?.x402Accepts)try{await i.client.createPaymentX402Usd({usdAmount:s,tokenShortcode:n?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:d?"sol":p?"ic":this.config?.icpay_network,icpay_ledger_id:n?.ledgerId,icpay_context:"tip:x402"}},recipientAddress:h||"",fiat_currency:this.config?.fiat_currency});return}catch(u){f(u,{onError:g=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:g,bubbles:!0})),w(g)&&(this.errorMessage=m(g),this.errorSeverity=v(g),this.errorAction=b(g))}});return}await i.client.createPaymentUsd({usdAmount:s,tokenShortcode:n?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:"ic",icpay_ledger_id:n?.ledgerId}},recipientAddress:h||"0x0000000000000000000000000000000000000000"}).catch(u=>{throw u})}catch(n){f(n,{onError:i=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:i,bubbles:!0})),w(i)&&(this.errorMessage=m(i),this.errorSeverity=v(i),this.errorAction=b(i))}})}}}async tryAutoConnectPNP(){try{if(!this.config||this.config?.useOwnWallet)return;let e=localStorage.getItem("icpay:pnp");if(!e)return;let t=JSON.parse(e);if(!t?.provider||!t?.principal)return;se||(se=(await import("./wallet-select-3A5Z7KZJ.js")).WalletSelect);let a=O({...this.config?.plugNPlay||{}});try{if(typeof window<"u"){let{resolveDerivationOrigin:i}=await import("./origin-44ZEXSX4.js");a.derivationOrigin=this.config?.derivationOrigin||i()}}catch{}let n=new se(a);this.walletConnected=!1,this.config={...this.config,connectedWallet:{owner:t.principal,principal:t.principal,connected:!1}}}catch{}}get amounts(){return this.config?.amountsUsd||[1,5,10]}async getOrCreatePnp(){if(this.pnp)return this.pnp;se||(se=(await import("./wallet-select-3A5Z7KZJ.js")).WalletSelect);let e=!!(this.config?.openOisyInNewTab||this.config?.plugNPlay?.openOisyInNewTab),t={...this.config?.plugNPlay||{}},a=this.config?.recipientAddresses;if(a&&(a.ic||a.evm||a.sol)){let i=[];a.ic&&i.push("ic"),a.evm&&i.push("evm"),a.sol&&i.push("sol"),i.length&&(t.chainTypes=i)}else this.config?.chainTypes&&(t.chainTypes=this.config.chainTypes);let n=e?O(t):t;try{if(typeof window<"u"){let{resolveDerivationOrigin:i}=await import("./origin-44ZEXSX4.js");n.derivationOrigin=this.config?.derivationOrigin||i()}}catch{}return this.pnp=new se(n),this.pnp}async generateWalletConnectQr(e){try{let t=await this.getOrCreatePnp();return!t||typeof t.generateWalletConnectQr!="function"?null:await t.generateWalletConnectQr({onConnected:a=>{this.walletConnected=!0,this.lastWalletId="walletconnect";let n=x(this.pnp,a),i=this.pnp?.getEvmProvider?.(),s=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:n,actorProvider:(o,d)=>this.pnp.getActor({canisterId:o,idl:d,requiresSigning:!0,anon:!1}),...i?{evmProvider:i}:{},...s?{solanaProvider:s}:{}},this.sdk=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"walletconnect"}}))}catch{}try{e?.onConnected?.()}catch{}this.requestUpdate()}})}catch{return null}}async checkCoinbaseConnection(){try{return(await this.getOrCreatePnp())?.hasCoinbaseAccounts?.()??!1}catch{return!1}}async connectWallet(e){let t=await this.getOrCreatePnp();if(!t||!e)throw new Error("Wallet not available");let a=(e||"").toLowerCase(),n=await t.connect(a);if(!!!(n&&(n.connected===!0||n.principal||n.owner||t.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0,this.lastWalletId=a;let s=x(this.pnp,n),o=this.pnp?.getEvmProvider?.(),d=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:s,actorProvider:(p,y)=>this.pnp.getActor({canisterId:p,idl:y,requiresSigning:!0,anon:!1}),...o?{evmProvider:o}:{},...d?{solanaProvider:d}:{}},this.sdk=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:a}}))}catch{}this.requestUpdate()}connectedCallback(){if(super.connectedCallback(),!!Ke){Se(this.config?.debug||!1,"Tip jar connected",{config:this.config}),this.config&&this.config.defaultAmountUsd&&(this.selectedAmount=this.config.defaultAmountUsd),this.tryAutoConnectPNP();try{window.addEventListener("icpay-switch-account",this.onSwitchAccount)}catch{}try{window.addEventListener("icpay-sdk-transaction-created",(()=>{this.showWalletModal=!1,this.requestUpdate()}))}catch{}}}updated(e){if(e.has("config")&&this.pendingAction&&this.config?.actorProvider){let t=this.pendingAction;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}this.walletModalStep!=="balances"&&!this.oisyReadyToPay&&(this.pendingAction=null,setTimeout(()=>{t==="tip"&&this.tip()},0))}}selectAmount(e){this.selectedAmount=e}selectSymbol(e){this.selectedSymbol=e}get fillPercentage(){return Math.min(this.total/50*100,100)}resetPaymentFlow(){ee(this,{pendingAction:"tip"})}async tip(){if(Ke){this.resetPaymentFlow(),Se(this.config?.debug||!1,"Tip button clicked!",{config:this.config,processing:this.processing});try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"tip",type:"sendUsd",amount:this.selectedAmount,currency:this.selectedSymbol||"ICP"}}))}catch{}this.processing=!0;try{if(this.config.useOwnWallet){if(!this.config.actorProvider){this.pendingAction="tip",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0}));return}}else if(!this.walletConnected){Se(this.config?.debug||!1,"Connecting to wallet via wallet");try{se||(se=(await import("./wallet-select-3A5Z7KZJ.js")).WalletSelect);let t=!!(this.config?.openOisyInNewTab||this.config?.plugNPlay?.openOisyInNewTab)?O({...this.config?.plugNPlay||{}}):{...this.config?.plugNPlay||{}};this.config?.chainTypes&&(t.chainTypes=this.config.chainTypes);try{if(typeof window<"u"){let{resolveDerivationOrigin:n}=await import("./origin-44ZEXSX4.js");t.derivationOrigin=this.config?.derivationOrigin||n()}}catch{}this.pnp=new se(t);try{let n=await ie(this.pnp);if(n){this.walletConnected=!0;let i=x(this.pnp,{owner:n,principal:n,connected:!0}),s=this.pnp?.getEvmProvider?.();this.config={...this.config,connectedWallet:i,actorProvider:(o,d)=>this.pnp.getActor({canisterId:o,idl:d,requiresSigning:!0,anon:!1}),...s?{evmProvider:s}:{}},this.sdk=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"oisy"}}))}catch{}this.tip();return}}catch{}let a=this.pnp.getEnabledWallets();if(Se(this.config?.debug||!1,"Available wallets",a),!a?.length)throw new Error("No wallets available");this.pendingAction="tip",this.showWalletModal=!0;return}catch(e){Se(this.config?.debug||!1,"Wallet connection error:",e),this.errorMessage=e instanceof Error?e.message:"Wallet connection failed",this.errorSeverity="error";return}}this.showWalletModal=!0,await this.fetchAndShowBalances();return}catch(e){f(e,{onError:t=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:t,bubbles:!0})),w(t)&&(this.errorMessage=m(t),this.errorSeverity=v(t),this.errorAction=b(t))}});try{!this.config.useOwnWallet&&this.pnp&&(await this.pnp.disconnect?.(),this.walletConnected=!1,this.config={...this.config,actorProvider:void 0,connectedWallet:void 0})}catch{}}finally{this.processing=!1}}}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=e=>this.onTransakMessage(e);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(e){let t=e?.data,a=t?.event_id||t?.eventId||t?.id;if(!(!a||typeof a!="string")&&a==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;this.showOnrampModal=!1;let n=t?.data?.id||t?.id||t?.webhookData?.id||null;this.startOnrampPolling(n||void 0)}}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"createPaymentUsd",type:"onramp"}}))}catch{}this.showWalletModal=!1,setTimeout(()=>this.createOnrampIntent(),0)}async createOnrampIntent(){try{let t=await E(this.config).startOnrampUsd(this.selectedAmount,void 0,{context:"tip:onramp",onrampPayment:!0,onrampProvider:this?.selectedOnrampProvider||"coinbase"}),a=t?.metadata?.onramp?.url||t?.onramp?.url||t?.metadata?.icpay_onramp?.url||t?.paymentIntent?.metadata?.icpay?.onrampUrl||t?.metadata?.icpay?.onrampUrl||null,n=t?.metadata?.icpay_payment_intent_id||t?.metadata?.paymentIntentId||t?.paymentIntentId||null,i=t?.metadata?.icpay_onramp?.errorMessage||t?.metadata?.onramp?.errorMessage||t?.paymentIntent?.metadata?.icpay?.onrampError||t?.paymentIntent?.metadata?.icpay?.errorMessage||t?.metadata?.icpay?.onrampError||t?.metadata?.icpay?.errorMessage||null;if(this.onrampPaymentIntentId=n,a){this.onrampUrl=a,this.onrampErrorMessage=null;try{window.open(a,"icpay_onramp","noopener,noreferrer");try{window.dispatchEvent(new CustomEvent("icpay-onramp-opened",{detail:{url:a}}))}catch{}}catch{}this.startOnrampPolling()}else this.onrampUrl=null,this.onrampErrorMessage=i||"Failed to obtain onramp sessionId",this.showOnrampModal=!0}catch(e){this.onrampUrl=null,this.onrampErrorMessage=e?.message||"Failed to obtain onramp sessionId",this.showOnrampModal=!0}}startOnrampPolling(e){if(this.onrampPollTimer){try{clearInterval(this.onrampPollTimer)}catch{}this.onrampPollTimer=null}if(this.onrampNotifyController){try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null}let t=this.onrampPaymentIntentId;if(!t)return;let a=E(this.config),n=()=>{if(this.detachTransakMessageListener(),this.onrampNotifyController)try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null,this.onrampPollingActive=!1};try{window.addEventListener("icpay-sdk-transaction-completed",(()=>n()),{once:!0})}catch{}this.onrampPollingActive=!0,this.onrampNotifyController=a.notifyIntentUntilComplete(t,5e3,e),this.onrampPollTimer=1}getWalletId(e){return e&&(e.id||e.provider||e.key)||""}getWalletLabel(e){return e&&(e.label||e.name||e.title||e.id)||"Wallet"}getWalletIcon(e){return e&&(e.icon||e.logo||e.image)||null}connectWithWallet(e){if(this.pnp)try{if(!e)throw new Error("No wallet ID provided");this.lastWalletId=(e||"").toLowerCase(),this.pnp.connect(e).then(a=>{if(!!!(a&&(a.connected===!0||a.principal||a.owner||this.pnp?.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:e}}))}catch{}let i=x(this.pnp,a),s=this.pnp?.getEvmProvider?.(),o=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:i,actorProvider:(d,p)=>this.pnp.getActor({canisterId:d,idl:p,requiresSigning:!0,anon:!1}),...s?{evmProvider:s}:{},...o?{solanaProvider:o}:{}},this.sdk=null,this.walletModalStep="balances",this.showBalanceModal=!1,this.showWalletModal=!0,this.fetchAndShowBalances()}).catch(a=>{this.errorMessage=a instanceof Error?a.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-error",{detail:{message:this.errorMessage,code:"WALLET_CONNECT_ERROR"}}))}catch{}})}catch(t){this.errorMessage=t instanceof Error?t.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-error",{detail:{message:this.errorMessage,code:"WALLET_CONNECT_ERROR"}}))}catch{}}}async fetchAndShowBalances(){try{this.balancesLoading=!0,this.balancesError=null,this.walletModalStep="balances",this.showBalanceModal=!1;let e=E(this.config),{balances:t}=await Y({sdk:e,lastWalletId:this.lastWalletId,connectedWallet:this.config?.connectedWallet,amountUsd:Number(this.selectedAmount||0),fiatCurrency:this.config?.fiat_currency,chainShortcodes:this.config?.chainShortcodes,tokenShortcodes:this.config?.tokenShortcodes});this.walletBalances=t}catch(e){this.walletBalances=[],this.balancesError=e&&(e.message||String(e))||"Failed to load balances"}finally{this.balancesLoading=!1}}render(){return this.config?ye`
1590
1590
  <div class="icpay-card icpay-section icpay-widget-base" style="text-align:center;">
1591
- ${this.config?.progressBar?.enabled!==!1?pe`
1591
+ ${this.config?.progressBar?.enabled!==!1?ye`
1592
1592
  <icpay-progress-bar
1593
1593
  .debug=${!!this.config?.debug}
1594
1594
  .theme=${this.config?.theme}
@@ -1600,7 +1600,7 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
1600
1600
  <div class="label">Total Tips: $${this.total}</div>
1601
1601
 
1602
1602
  <div class="amounts">
1603
- ${this.amounts.map(e=>pe`<div class="chip ${this.selectedAmount===e?"selected":""}" @click=${()=>this.selectAmount(e)}>$${e}</div>`)}
1603
+ ${this.amounts.map(e=>ye`<div class="chip ${this.selectedAmount===e?"selected":""}" @click=${()=>this.selectAmount(e)}>$${e}</div>`)}
1604
1604
  </div>
1605
1605
 
1606
1606
 
@@ -1611,19 +1611,19 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
1611
1611
  ${this.succeeded&&this.config?.disableAfterSuccess?"Paid":this.processing?"Processing\u2026":this.config?.buttonLabel?this.config.buttonLabel.replace("{amount}",String(this.selectedAmount)).replace("{symbol}",this.selectedSymbol||"ICP"):`Tip $${this.selectedAmount} with crypto`}
1612
1612
  </button>
1613
1613
 
1614
- ${this.errorMessage?pe`
1614
+ ${this.errorMessage?ye`
1615
1615
  <div class="error-message ${this.errorSeverity}" style="margin-top: 12px; padding: 8px 12px; border-radius: 6px; font-size: 14px; text-align: center;">
1616
1616
  ${this.errorMessage}
1617
- ${this.errorAction?pe`
1617
+ ${this.errorAction?ye`
1618
1618
  <button style="margin-left: 8px; padding: 4px 8px; background: transparent; border: 1px solid currentColor; border-radius: 4px; font-size: 12px; cursor: pointer;">
1619
1619
  ${this.errorAction}
1620
1620
  </button>
1621
1621
  `:""}
1622
1622
  </div>
1623
1623
  `:""}
1624
- ${(()=>{let e=this.pnp?.getEnabledWallets?.()||[],t=V(e),n=this.config?.theme?typeof this.config.theme=="string"?this.config.theme:this.config.theme.mode||"light":void 0;return Q({visible:!!(this.showWalletModal&&this.pnp),wallets:t,isConnecting:!1,step:this.walletModalStep,balances:this.walletModalStep==="balances"?this.walletBalances:[],balancesLoading:this.walletModalStep==="balances"?this.balancesLoading:!1,balancesError:this.walletModalStep==="balances"?this.balancesError:null,onSelectBalance:a=>this.onSelectBalanceSymbol(a),onBack:()=>{this.walletModalStep="connect"},onSwitchAccount:()=>this.onSwitchAccount(null),onSelect:a=>this.connectWithWallet(a),onClose:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-cancelled",{detail:{reason:"user_cancelled"}}))}catch{}},onDismiss:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1},onCreditCard:this.config?.onramp?.enabled===!0&&this.config?.onrampDisabled!==!0?()=>this.startOnramp():void 0,creditCardLabel:this.config?.onramp?.creditCardLabel||"Pay with credit card",showCreditCard:this.config?.onramp?.enabled===!0&&this.config?.onrampDisabled!==!0,creditCardTooltip:(()=>{let i=Number(this.selectedAmount||this.config?.defaultAmountUsd||0);return i>0&&i<5&&this.config?.onramp?.enabled===!0&&this.config?.onrampDisabled!==!0?`Note: Minimum card amount is $5. You will pay about $${(5-i).toFixed(2)} more.`:null})(),oisyReadyToPay:this.oisyReadyToPay,onOisyPay:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1,this.tip()},theme:n})})()}
1624
+ ${(()=>{let e=this.pnp?.getEnabledWallets?.()||[],t=X(e),a=this.config?.theme?typeof this.config.theme=="string"?this.config.theme:this.config.theme.mode||"light":void 0;return Q({visible:!!(this.showWalletModal&&this.pnp),wallets:t,isConnecting:!1,step:this.walletModalStep,balances:this.walletModalStep==="balances"?this.walletBalances:[],balancesLoading:this.walletModalStep==="balances"?this.balancesLoading:!1,balancesError:this.walletModalStep==="balances"?this.balancesError:null,onSelectBalance:n=>this.onSelectBalanceSymbol(n),onBack:()=>{this.walletModalStep="connect"},onSwitchAccount:()=>this.onSwitchAccount(null),onSelect:n=>this.connectWithWallet(n),onClose:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-cancelled",{detail:{reason:"user_cancelled"}}))}catch{}},onDismiss:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1},onCreditCard:this.config?.onramp?.enabled===!0&&this.config?.onrampDisabled!==!0?()=>this.startOnramp():void 0,creditCardLabel:this.config?.onramp?.creditCardLabel||"Pay with credit card",showCreditCard:this.config?.onramp?.enabled===!0&&this.config?.onrampDisabled!==!0,creditCardTooltip:(()=>{let i=Number(this.selectedAmount||this.config?.defaultAmountUsd||0);return i>0&&i<5&&this.config?.onramp?.enabled===!0&&this.config?.onrampDisabled!==!0?`Note: Minimum card amount is $5. You will pay about $${(5-i).toFixed(2)} more.`:null})(),oisyReadyToPay:this.oisyReadyToPay,onOisyPay:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1,this.tip()},theme:a})})()}
1625
1625
 
1626
- ${(()=>{let e=this.config?.theme?typeof this.config.theme=="string"?this.config.theme:this.config.theme.mode||"light":void 0;return pe`
1626
+ ${(()=>{let e=this.config?.theme?typeof this.config.theme=="string"?this.config.theme:this.config.theme.mode||"light":void 0;return ye`
1627
1627
  ${Z({visible:this.showBalanceModal,isLoading:this.balancesLoading,error:this.balancesError,balances:this.walletBalances,onSelect:t=>this.onSelectBalanceSymbol(t),onClose:()=>{this.showBalanceModal=!1},theme:e})}
1628
1628
 
1629
1629
  ${H({visible:this.showOnrampModal,url:this.onrampUrl||void 0,errorMessage:this.onrampErrorMessage||void 0,width:this.config?.onramp?.width,height:this.config?.onramp?.height,onClose:()=>{this.showOnrampModal=!1},onBack:()=>{this.showOnrampModal=!1,this.showWalletModal=!0},title:"Pay with credit card",theme:e})}
@@ -1632,7 +1632,7 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
1632
1632
  <a href="https://icpay.org" target="_blank" rel="noopener noreferrer">Powered by icpay</a>
1633
1633
  </div>
1634
1634
  </div>
1635
- `:pe`<div class="icpay-card icpay-section">Loading...</div>`}};W.styles=[K,kt`
1635
+ `:ye`<div class="icpay-card icpay-section">Loading...</div>`}};A.styles=[K,kt`
1636
1636
  .jar { width: 120px; height: 160px; margin: 0 auto 12px; position: relative; background: linear-gradient(135deg, #374151 0%, #4b5563 100%); border-radius: 0 0 60px 60px; border: 3px solid #6b7280; border-top: 8px solid #6b7280; overflow: hidden; }
1637
1637
  .fill { position: absolute; bottom: 0; left: 0; right: 0; background: linear-gradient(135deg, #d1d5db 0%, #9ca3af 100%); transition: height 0.8s ease; height: 0%; }
1638
1638
  .amounts { display: grid; grid-template-columns: repeat(3,1fr); gap: 8px; margin: 12px 0; }
@@ -1664,9 +1664,9 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
1664
1664
  border-color: var(--icpay-error-border);
1665
1665
  color: var(--icpay-error-text);
1666
1666
  }
1667
- `],s([Ct({type:Object})],W.prototype,"config",2),s([U()],W.prototype,"selectedAmount",2),s([U()],W.prototype,"selectedSymbol",2),s([U()],W.prototype,"total",2),s([U()],W.prototype,"processing",2),s([U()],W.prototype,"succeeded",2),s([U()],W.prototype,"errorMessage",2),s([U()],W.prototype,"errorSeverity",2),s([U()],W.prototype,"errorAction",2),s([U()],W.prototype,"walletConnected",2),s([U()],W.prototype,"pendingAction",2),s([U()],W.prototype,"showWalletModal",2),s([U()],W.prototype,"walletModalStep",2),s([U()],W.prototype,"oisyReadyToPay",2),s([U()],W.prototype,"lastWalletId",2),s([U()],W.prototype,"showOnrampModal",2),s([U()],W.prototype,"onrampUrl",2),s([U()],W.prototype,"onrampPaymentIntentId",2),s([U()],W.prototype,"onrampErrorMessage",2),s([U()],W.prototype,"showBalanceModal",2),s([U()],W.prototype,"balancesLoading",2),s([U()],W.prototype,"balancesError",2),s([U()],W.prototype,"walletBalances",2),W=s([St("icpay-tip-jar")],W);import{LitElement as Mt,html as ve,css as Wt}from"lit";import{customElement as At,property as Oe,state as B}from"lit/decorators.js";var je=typeof window<"u",se=null;function ke(r,l,e){r&&(e!==void 0?console.log(`[ICPay Widget] ${l}`,e):console.log(`[ICPay Widget] ${l}`))}var C=class extends Mt{constructor(){super(...arguments);this.title="Article Title";this.preview="";this.lockedContent="";this.selectedSymbol=null;this.unlocked=!1;this.succeeded=!1;this.processing=!1;this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.walletModalStep="connect";this.oisyReadyToPay=!1;this.lastWalletId=null;this.pnp=null;this.showOnrampModal=!1;this.onrampUrl=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.transakMessageHandlerBound=null;this.onrampPollTimer=null;this.onrampPollingActive=!1;this.onrampNotifyController=null;this.showBalanceModal=!1;this.balancesLoading=!1;this.balancesError=null;this.walletBalances=[];this.sdk=null;this.onTransactionCompleted=null;this.onUnlock=null;this.onSwitchAccount=async e=>{try{if(this.pnp)try{await this.pnp.disconnect()}catch{}this.walletConnected=!1,this.config={...this.config,actorProvider:void 0,connectedWallet:void 0},this.pendingAction="unlock",this.showWalletModal=!0,this.requestUpdate();try{let t=Number(this.config?.priceUsd||0),n=this.selectedSymbol||"ICP";window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"unlock",type:"sendUsd",amount:t,currency:n}}))}catch{}}catch{}};this.onSelectBalanceSymbol=async e=>{let t=(this.walletBalances||[]).find(a=>a?.tokenShortcode===e);if(t?.ledgerSymbol&&(this.selectedSymbol=t.ledgerSymbol),q(this.lastWalletId)){let a=(this.walletBalances||[]).find(o=>o?.tokenShortcode===e),i=a?.chainId;this.showBalanceModal=!1,this.showWalletModal=!1,X(i,{provider:this.pnp?.getEvmProvider?.()||this.config?.evmProvider,chainName:a?.chainName,rpcUrlPublic:a?.rpcUrlPublic,nativeSymbol:a?.ledgerSymbol,decimals:a?.decimals}).then(async()=>{try{let o=E(this.config),c=Number(this.config?.priceUsd??0);if(a?.x402Accepts&&!J(this.lastWalletId))try{await o.client.createPaymentX402Usd({usdAmount:c,tokenShortcode:a?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:"evm",icpay_ledger_id:a?.ledgerId,icpay_context:"article:x402"}},recipientAddress:(this.config?.recipientAddresses||{})?.evm||"0x0000000000000000000000000000000000000000",fiat_currency:this.config?.fiat_currency});return}catch(d){f(d,{onError:p=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:p,bubbles:!0})),v(p)&&(this.errorMessage=g(p),this.errorSeverity=b(p),this.errorAction=w(p))}})}await o.client.createPaymentUsd({usdAmount:c,tokenShortcode:a?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:"evm",icpay_ledger_id:a?.ledgerId}},recipientAddress:(this.config?.recipientAddresses||{})?.evm||"0x0000000000000000000000000000000000000000"}).catch(d=>{throw d})}catch(o){f(o,{onError:c=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:c,bubbles:!0})),v(c)&&(this.errorMessage=g(c),this.errorSeverity=b(c),this.errorAction=w(c))}})}});return}this.showBalanceModal=!1,this.showWalletModal=!1;let n=this.pendingAction;if(this.pendingAction=null,n==="unlock")try{let a=(this.walletBalances||[]).find(h=>h?.tokenShortcode===e),i=E(this.config),o=Number(this.config?.priceUsd??0),d=String(a?.ledgerName||a?.chainName||"").toLowerCase().includes("sol"),p=this.config?.recipientAddresses||{},y=d&&p.sol||p.ic;if(d&&a?.x402Accepts)try{await i.client.createPaymentX402Usd({usdAmount:o,tokenShortcode:a?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:"sol",icpay_ledger_id:a?.ledgerId,icpay_context:"article:x402"}},recipientAddress:y||"",fiat_currency:this.config?.fiat_currency});return}catch(h){f(h,{onError:u=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:u,bubbles:!0})),v(u)&&(this.errorMessage=g(u),this.errorSeverity=b(u),this.errorAction=w(u))}});return}await i.client.createPaymentUsd({usdAmount:o,tokenShortcode:a?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:"ic",icpay_ledger_id:a?.ledgerId}},recipientAddress:y||"0x0000000000000000000000000000000000000000"}).catch(h=>{throw h})}catch(a){f(a,{onError:i=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:i,bubbles:!0})),v(i)&&(this.errorMessage=g(i),this.errorSeverity=b(i),this.errorAction=w(i))}})}}}get obfuscatedLockedContent(){try{return(this.lockedContent||"").replace(/[^\s]/g,"x")}catch{return"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}}async tryAutoConnectPNP(){try{if(!this.config||this.config?.useOwnWallet)return;let e=localStorage.getItem("icpay:pnp");if(!e)return;let t=JSON.parse(e);if(!t?.provider||!t?.principal)return;se||(se=(await import("./wallet-select-VE5FSSFG.js")).WalletSelect);let n={...this.config?.plugNPlay||{}};try{if(typeof window<"u"){let{resolveDerivationOrigin:i}=await import("./origin-44ZEXSX4.js");n.derivationOrigin=this.config?.derivationOrigin||i()}}catch{}let a=new se(n);this.walletConnected=!1,this.config={...this.config,connectedWallet:{owner:t.principal,principal:t.principal,connected:!1}}}catch{}}async getOrCreatePnp(){if(this.pnp)return this.pnp;se||(se=(await import("./wallet-select-VE5FSSFG.js")).WalletSelect);let e=!!(this.config?.openOisyInNewTab||this.config?.plugNPlay?.openOisyInNewTab),t={...this.config?.plugNPlay||{}},n=this.config?.recipientAddresses;if(n&&(n.ic||n.evm||n.sol)){let i=[];n.ic&&i.push("ic"),n.evm&&i.push("evm"),n.sol&&i.push("sol"),i.length&&(t.chainTypes=i)}else this.config?.chainTypes&&(t.chainTypes=this.config.chainTypes);let a=e?I(t):t;try{if(typeof window<"u"){let{resolveDerivationOrigin:i}=await import("./origin-44ZEXSX4.js");a.derivationOrigin=this.config?.derivationOrigin||i()}}catch{}return this.pnp=new se(a),this.pnp}async generateWalletConnectQr(e){try{let t=await this.getOrCreatePnp();return!t||typeof t.generateWalletConnectQr!="function"?null:await t.generateWalletConnectQr({onConnected:n=>{this.walletConnected=!0,this.lastWalletId="walletconnect";let a=x(this.pnp,n),i=this.pnp?.getEvmProvider?.(),o=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:a,actorProvider:(c,d)=>this.pnp.getActor({canisterId:c,idl:d,requiresSigning:!0,anon:!1}),...i?{evmProvider:i}:{},...o?{solanaProvider:o}:{}},this.sdk=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"walletconnect"}}))}catch{}try{e?.onConnected?.()}catch{}this.requestUpdate()}})}catch{return null}}async checkCoinbaseConnection(){try{return(await this.getOrCreatePnp())?.hasCoinbaseAccounts?.()??!1}catch{return!1}}async connectWallet(e){let t=await this.getOrCreatePnp();if(!t||!e)throw new Error("Wallet not available");let n=(e||"").toLowerCase(),a=await t.connect(n);if(!!!(a&&(a.connected===!0||a.principal||a.owner||t.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0,this.lastWalletId=n;let o=x(this.pnp,a),c=this.pnp?.getEvmProvider?.(),d=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:o,actorProvider:(p,y)=>this.pnp.getActor({canisterId:p,idl:y,requiresSigning:!0,anon:!1}),...c?{evmProvider:c}:{},...d?{solanaProvider:d}:{}},this.sdk=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:n}}))}catch{}this.requestUpdate()}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=e=>this.onTransakMessage(e);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(e){let t=e?.data,n=t?.event_id||t?.eventId||t?.id;if(!(!n||typeof n!="string")&&n==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;this.showOnrampModal=!1;let a=t?.data?.id||t?.id||t?.webhookData?.id||null;this.startOnrampPolling(a||void 0)}}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"createPaymentUsd",type:"onramp"}}))}catch{}this.showWalletModal=!1,setTimeout(()=>this.createOnrampIntent(),0)}async createOnrampIntent(){try{let t=await E(this.config).startOnrampUsd(this.config.priceUsd,void 0,{context:"article:onramp",onrampPayment:!0,onrampProvider:"coinbase"}),n=t?.metadata?.onramp?.url||t?.onramp?.url||t?.metadata?.icpay_onramp?.url||t?.paymentIntent?.metadata?.icpay?.onrampUrl||t?.metadata?.icpay?.onrampUrl||null,a=t?.metadata?.icpay_payment_intent_id||t?.metadata?.paymentIntentId||t?.paymentIntentId||null,i=t?.metadata?.icpay_onramp?.errorMessage||t?.metadata?.onramp?.errorMessage||t?.paymentIntent?.metadata?.icpay?.onrampError||t?.paymentIntent?.metadata?.icpay?.errorMessage||t?.metadata?.icpay?.onrampError||t?.metadata?.icpay?.errorMessage||null;if(this.onrampPaymentIntentId=a,n){this.onrampUrl=n,this.onrampErrorMessage=null;try{window.open(n,"icpay_onramp","noopener,noreferrer");try{window.dispatchEvent(new CustomEvent("icpay-onramp-opened",{detail:{url:n}}))}catch{}}catch{}this.startOnrampPolling()}else this.onrampUrl=null,this.onrampErrorMessage=i||"Failed to obtain onramp URL",this.showOnrampModal=!0}catch(e){this.onrampUrl=null,this.onrampErrorMessage=e?.message||"Failed to obtain onramp URL",this.showOnrampModal=!0}}startOnrampPolling(e){if(this.onrampPollTimer){try{clearInterval(this.onrampPollTimer)}catch{}this.onrampPollTimer=null}if(this.onrampNotifyController){try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null}let t=this.onrampPaymentIntentId;if(!t)return;let n=E(this.config),a=()=>{if(this.detachTransakMessageListener(),this.onrampNotifyController)try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null,this.onrampPollingActive=!1};try{window.addEventListener("icpay-sdk-transaction-completed",(()=>a()),{once:!0})}catch{}this.onrampPollingActive=!0,this.onrampNotifyController=n.notifyIntentUntilComplete(t,5e3,e),this.onrampPollTimer=1}connectedCallback(){if(super.connectedCallback(),!!je){ke(this.config?.debug||!1,"Article paywall connected",{config:this.config}),this.config&&(typeof this.config.title=="string"&&(this.title=this.config.title),typeof this.config.preview=="string"&&(this.preview=this.config.preview),typeof this.config.lockedContent=="string"&&(this.lockedContent=this.config.lockedContent)),this.tryAutoConnectPNP();try{window.addEventListener("icpay-switch-account",this.onSwitchAccount)}catch{}try{window.addEventListener("icpay-sdk-transaction-created",(()=>{this.showWalletModal=!1,this.showBalanceModal=!1,this.requestUpdate()}))}catch{}this.onTransactionCompleted=(()=>{this.unlocked=!0,this.succeeded=!0,this.processing=!1;try{window.dispatchEvent(new CustomEvent("icpay-unlock",{detail:{amount:this.config?.priceUsd,currency:this.selectedSymbol||"ICP"}}))}catch{}this.requestUpdate()});try{window.addEventListener("icpay-sdk-transaction-completed",this.onTransactionCompleted)}catch{}this.onUnlock=(()=>{this.unlocked=!0,this.succeeded=!0,this.processing=!1,this.requestUpdate()});try{window.addEventListener("icpay-unlock",this.onUnlock)}catch{}}}disconnectedCallback(){super.disconnectedCallback();try{window.removeEventListener("icpay-switch-account",this.onSwitchAccount)}catch{}if(this.onTransactionCompleted)try{window.removeEventListener("icpay-sdk-transaction-completed",this.onTransactionCompleted)}catch{}if(this.onUnlock)try{window.removeEventListener("icpay-unlock",this.onUnlock)}catch{}}updated(e){if(e.has("config")&&this.config&&(typeof this.config.title=="string"&&(this.title=this.config.title),typeof this.config.preview=="string"&&(this.preview=this.config.preview),typeof this.config.lockedContent=="string"&&(this.lockedContent=this.config.lockedContent)),e.has("config")&&this.pendingAction&&this.config?.actorProvider){let t=this.pendingAction;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}this.walletModalStep!=="balances"&&!this.oisyReadyToPay&&(this.pendingAction=null,setTimeout(()=>{t==="unlock"&&this.unlock()},0))}}selectSymbol(e){this.selectedSymbol=e}resetPaymentFlow(){ee(this,{pendingAction:"unlock"})}async unlock(){if(je&&!this.unlocked){this.resetPaymentFlow(),ke(this.config?.debug||!1,"Article paywall unlock started",{priceUsd:this.config.priceUsd,selectedSymbol:this.selectedSymbol,useOwnWallet:this.config.useOwnWallet});try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"unlock",type:"sendUsd",amount:this.config.priceUsd,currency:this.selectedSymbol||"ICP"}}))}catch{}this.processing=!0;try{if(this.config.useOwnWallet){if(!this.config.actorProvider){this.pendingAction="unlock",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0}));return}}else if(!this.walletConnected){ke(this.config?.debug||!1,"Connecting to wallet via Plug N Play");try{se||(se=(await import("./wallet-select-VE5FSSFG.js")).WalletSelect);let t=!!(this.config?.openOisyInNewTab||this.config?.plugNPlay?.openOisyInNewTab)?I({...this.config?.plugNPlay||{}}):{...this.config?.plugNPlay||{}};try{if(typeof window<"u"){let{resolveDerivationOrigin:a}=await import("./origin-44ZEXSX4.js");t.derivationOrigin=this.config?.derivationOrigin||a()}}catch{}this.pnp=new se(t);try{let a=await ae(this.pnp);if(a){this.walletConnected=!0;let i=x(this.pnp,{owner:a,principal:a,connected:!0}),o=this.pnp?.getEvmProvider?.(),c=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:i,actorProvider:(d,p)=>this.pnp.getActor({canisterId:d,idl:p,requiresSigning:!0,anon:!1}),...o?{evmProvider:o}:{},...c?{solanaProvider:c}:{}},this.sdk=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"oisy"}}))}catch{}this.unlock();return}}catch{}let n=this.pnp.getEnabledWallets();if(ke(this.config?.debug||!1,"Available wallets",n),!n?.length)throw new Error("No wallets available");this.pendingAction="unlock",this.showWalletModal=!0;return}catch(e){ke(this.config?.debug||!1,"Wallet connection error:",e),this.errorMessage=e instanceof Error?e.message:"Wallet connection failed",this.errorSeverity="error";return}}this.showWalletModal=!1,await this.fetchAndShowBalances();return}catch(e){f(e,{onError:t=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:t,bubbles:!0})),v(t)&&(this.errorMessage=g(t),this.errorSeverity=b(t),this.errorAction=w(t))}});try{!this.config.useOwnWallet&&this.pnp&&(await this.pnp.disconnect?.(),this.walletConnected=!1,this.config={...this.config,actorProvider:void 0,connectedWallet:void 0})}catch{}}finally{this.processing=!1}}}getWalletId(e){return e&&(e.id||e.provider||e.key)||""}getWalletLabel(e){return e&&(e.label||e.name||e.title||e.id)||"Wallet"}getWalletIcon(e){return e&&(e.icon||e.logo||e.image)||null}connectWithWallet(e){if(this.pnp)try{if(!e)throw new Error("No wallet ID provided");this.lastWalletId=(e||"").toLowerCase(),this.pnp.connect(e).then(n=>{if(!!!(n&&(n.connected===!0||n.principal||n.owner||this.pnp?.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:e}}))}catch{}let i=x(this.pnp,n),o=this.pnp?.getEvmProvider?.();this.config={...this.config,connectedWallet:i,actorProvider:(c,d)=>this.pnp.getActor({canisterId:c,idl:d,requiresSigning:!0,anon:!1}),...o?{evmProvider:o}:{}},this.sdk=null,this.walletModalStep="balances",this.showBalanceModal=!1,this.showWalletModal=!0,this.fetchAndShowBalances()}).catch(n=>{this.errorMessage=n instanceof Error?n.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-error",{detail:{message:this.errorMessage,code:"WALLET_CONNECT_ERROR"}}))}catch{}})}catch(t){this.errorMessage=t instanceof Error?t.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-error",{detail:{message:this.errorMessage,code:"WALLET_CONNECT_ERROR"}}))}catch{}}}async fetchAndShowBalances(){try{this.balancesLoading=!0,this.balancesError=null,this.walletModalStep="balances",this.showBalanceModal=!1;let e=E(this.config),{balances:t}=await Y({sdk:e,lastWalletId:this.lastWalletId,connectedWallet:this.config?.connectedWallet,amountUsd:Number(this.config?.priceUsd??0),fiatCurrency:this.config?.fiat_currency,chainShortcodes:this.config?.chainShortcodes,tokenShortcodes:this.config?.tokenShortcodes});this.walletBalances=t}catch(e){this.walletBalances=[],this.balancesError=e&&(e.message||String(e))||"Failed to load balances"}finally{this.balancesLoading=!1}}render(){return this.config?ve`
1667
+ `],c([Ct({type:Object})],A.prototype,"config",2),c([_()],A.prototype,"selectedAmount",2),c([_()],A.prototype,"selectedSymbol",2),c([_()],A.prototype,"total",2),c([_()],A.prototype,"processing",2),c([_()],A.prototype,"succeeded",2),c([_()],A.prototype,"errorMessage",2),c([_()],A.prototype,"errorSeverity",2),c([_()],A.prototype,"errorAction",2),c([_()],A.prototype,"walletConnected",2),c([_()],A.prototype,"pendingAction",2),c([_()],A.prototype,"showWalletModal",2),c([_()],A.prototype,"walletModalStep",2),c([_()],A.prototype,"oisyReadyToPay",2),c([_()],A.prototype,"lastWalletId",2),c([_()],A.prototype,"showOnrampModal",2),c([_()],A.prototype,"onrampUrl",2),c([_()],A.prototype,"onrampPaymentIntentId",2),c([_()],A.prototype,"onrampErrorMessage",2),c([_()],A.prototype,"showBalanceModal",2),c([_()],A.prototype,"balancesLoading",2),c([_()],A.prototype,"balancesError",2),c([_()],A.prototype,"walletBalances",2),A=c([St("icpay-tip-jar")],A);import{LitElement as Mt,html as be,css as Wt}from"lit";import{customElement as At,property as Le,state as F}from"lit/decorators.js";var He=typeof window<"u",oe=null;function Ce(r,l,e){r&&(e!==void 0?console.log(`[ICPay Widget] ${l}`,e):console.log(`[ICPay Widget] ${l}`))}var C=class extends Mt{constructor(){super(...arguments);this.title="Article Title";this.preview="";this.lockedContent="";this.selectedSymbol=null;this.unlocked=!1;this.succeeded=!1;this.processing=!1;this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.walletModalStep="connect";this.oisyReadyToPay=!1;this.lastWalletId=null;this.pnp=null;this.showOnrampModal=!1;this.onrampUrl=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.transakMessageHandlerBound=null;this.onrampPollTimer=null;this.onrampPollingActive=!1;this.onrampNotifyController=null;this.showBalanceModal=!1;this.balancesLoading=!1;this.balancesError=null;this.walletBalances=[];this.sdk=null;this.onTransactionCompleted=null;this.onUnlock=null;this.onSwitchAccount=async e=>{try{if(this.pnp)try{await this.pnp.disconnect()}catch{}this.walletConnected=!1,this.config={...this.config,actorProvider:void 0,connectedWallet:void 0},this.pendingAction="unlock",this.showWalletModal=!0,this.requestUpdate();try{let t=Number(this.config?.priceUsd||0),a=this.selectedSymbol||"ICP";window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"unlock",type:"sendUsd",amount:t,currency:a}}))}catch{}}catch{}};this.onSelectBalanceSymbol=async e=>{let t=(this.walletBalances||[]).find(n=>n?.tokenShortcode===e);if(t?.ledgerSymbol&&(this.selectedSymbol=t.ledgerSymbol),j(this.lastWalletId)){let n=(this.walletBalances||[]).find(s=>s?.tokenShortcode===e),i=n?.chainId;this.showBalanceModal=!1,this.showWalletModal=!1,V(i,{provider:this.pnp?.getEvmProvider?.()||this.config?.evmProvider,chainName:n?.chainName,rpcUrlPublic:n?.rpcUrlPublic,nativeSymbol:n?.ledgerSymbol,decimals:n?.decimals}).then(async()=>{try{let s=E(this.config),o=Number(this.config?.priceUsd??0);if(n?.x402Accepts&&!J(this.lastWalletId))try{await s.client.createPaymentX402Usd({usdAmount:o,tokenShortcode:n?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:"evm",icpay_ledger_id:n?.ledgerId,icpay_context:"article:x402"}},recipientAddress:(this.config?.recipientAddresses||{})?.evm||"0x0000000000000000000000000000000000000000",fiat_currency:this.config?.fiat_currency});return}catch(d){f(d,{onError:p=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:p,bubbles:!0})),w(p)&&(this.errorMessage=m(p),this.errorSeverity=v(p),this.errorAction=b(p))}})}await s.client.createPaymentUsd({usdAmount:o,tokenShortcode:n?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:"evm",icpay_ledger_id:n?.ledgerId}},recipientAddress:(this.config?.recipientAddresses||{})?.evm||"0x0000000000000000000000000000000000000000"}).catch(d=>{throw d})}catch(s){f(s,{onError:o=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:o,bubbles:!0})),w(o)&&(this.errorMessage=m(o),this.errorSeverity=v(o),this.errorAction=b(o))}})}});return}this.showBalanceModal=!1,this.showWalletModal=!1;let a=this.pendingAction;if(this.pendingAction=null,a==="unlock")try{let n=(this.walletBalances||[]).find(h=>h?.tokenShortcode===e),i=E(this.config),s=Number(this.config?.priceUsd??0),d=String(n?.ledgerName||n?.chainName||"").toLowerCase().includes("sol"),p=this.config?.recipientAddresses||{},y=d&&p.sol||p.ic;if(d&&n?.x402Accepts)try{await i.client.createPaymentX402Usd({usdAmount:s,tokenShortcode:n?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:"sol",icpay_ledger_id:n?.ledgerId,icpay_context:"article:x402"}},recipientAddress:y||"",fiat_currency:this.config?.fiat_currency});return}catch(h){f(h,{onError:u=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:u,bubbles:!0})),w(u)&&(this.errorMessage=m(u),this.errorSeverity=v(u),this.errorAction=b(u))}});return}await i.client.createPaymentUsd({usdAmount:s,tokenShortcode:n?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:"ic",icpay_ledger_id:n?.ledgerId}},recipientAddress:y||"0x0000000000000000000000000000000000000000"}).catch(h=>{throw h})}catch(n){f(n,{onError:i=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:i,bubbles:!0})),w(i)&&(this.errorMessage=m(i),this.errorSeverity=v(i),this.errorAction=b(i))}})}}}get obfuscatedLockedContent(){try{return(this.lockedContent||"").replace(/[^\s]/g,"x")}catch{return"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"}}async tryAutoConnectPNP(){try{if(!this.config||this.config?.useOwnWallet)return;let e=localStorage.getItem("icpay:pnp");if(!e)return;let t=JSON.parse(e);if(!t?.provider||!t?.principal)return;oe||(oe=(await import("./wallet-select-3A5Z7KZJ.js")).WalletSelect);let a={...this.config?.plugNPlay||{}};try{if(typeof window<"u"){let{resolveDerivationOrigin:i}=await import("./origin-44ZEXSX4.js");a.derivationOrigin=this.config?.derivationOrigin||i()}}catch{}let n=new oe(a);this.walletConnected=!1,this.config={...this.config,connectedWallet:{owner:t.principal,principal:t.principal,connected:!1}}}catch{}}async getOrCreatePnp(){if(this.pnp)return this.pnp;oe||(oe=(await import("./wallet-select-3A5Z7KZJ.js")).WalletSelect);let e=!!(this.config?.openOisyInNewTab||this.config?.plugNPlay?.openOisyInNewTab),t={...this.config?.plugNPlay||{}},a=this.config?.recipientAddresses;if(a&&(a.ic||a.evm||a.sol)){let i=[];a.ic&&i.push("ic"),a.evm&&i.push("evm"),a.sol&&i.push("sol"),i.length&&(t.chainTypes=i)}else this.config?.chainTypes&&(t.chainTypes=this.config.chainTypes);let n=e?O(t):t;try{if(typeof window<"u"){let{resolveDerivationOrigin:i}=await import("./origin-44ZEXSX4.js");n.derivationOrigin=this.config?.derivationOrigin||i()}}catch{}return this.pnp=new oe(n),this.pnp}async generateWalletConnectQr(e){try{let t=await this.getOrCreatePnp();return!t||typeof t.generateWalletConnectQr!="function"?null:await t.generateWalletConnectQr({onConnected:a=>{this.walletConnected=!0,this.lastWalletId="walletconnect";let n=x(this.pnp,a),i=this.pnp?.getEvmProvider?.(),s=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:n,actorProvider:(o,d)=>this.pnp.getActor({canisterId:o,idl:d,requiresSigning:!0,anon:!1}),...i?{evmProvider:i}:{},...s?{solanaProvider:s}:{}},this.sdk=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"walletconnect"}}))}catch{}try{e?.onConnected?.()}catch{}this.requestUpdate()}})}catch{return null}}async checkCoinbaseConnection(){try{return(await this.getOrCreatePnp())?.hasCoinbaseAccounts?.()??!1}catch{return!1}}async connectWallet(e){let t=await this.getOrCreatePnp();if(!t||!e)throw new Error("Wallet not available");let a=(e||"").toLowerCase(),n=await t.connect(a);if(!!!(n&&(n.connected===!0||n.principal||n.owner||t.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0,this.lastWalletId=a;let s=x(this.pnp,n),o=this.pnp?.getEvmProvider?.(),d=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:s,actorProvider:(p,y)=>this.pnp.getActor({canisterId:p,idl:y,requiresSigning:!0,anon:!1}),...o?{evmProvider:o}:{},...d?{solanaProvider:d}:{}},this.sdk=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:a}}))}catch{}this.requestUpdate()}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=e=>this.onTransakMessage(e);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(e){let t=e?.data,a=t?.event_id||t?.eventId||t?.id;if(!(!a||typeof a!="string")&&a==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;this.showOnrampModal=!1;let n=t?.data?.id||t?.id||t?.webhookData?.id||null;this.startOnrampPolling(n||void 0)}}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"createPaymentUsd",type:"onramp"}}))}catch{}this.showWalletModal=!1,setTimeout(()=>this.createOnrampIntent(),0)}async createOnrampIntent(){try{let t=await E(this.config).startOnrampUsd(this.config.priceUsd,void 0,{context:"article:onramp",onrampPayment:!0,onrampProvider:"coinbase"}),a=t?.metadata?.onramp?.url||t?.onramp?.url||t?.metadata?.icpay_onramp?.url||t?.paymentIntent?.metadata?.icpay?.onrampUrl||t?.metadata?.icpay?.onrampUrl||null,n=t?.metadata?.icpay_payment_intent_id||t?.metadata?.paymentIntentId||t?.paymentIntentId||null,i=t?.metadata?.icpay_onramp?.errorMessage||t?.metadata?.onramp?.errorMessage||t?.paymentIntent?.metadata?.icpay?.onrampError||t?.paymentIntent?.metadata?.icpay?.errorMessage||t?.metadata?.icpay?.onrampError||t?.metadata?.icpay?.errorMessage||null;if(this.onrampPaymentIntentId=n,a){this.onrampUrl=a,this.onrampErrorMessage=null;try{window.open(a,"icpay_onramp","noopener,noreferrer");try{window.dispatchEvent(new CustomEvent("icpay-onramp-opened",{detail:{url:a}}))}catch{}}catch{}this.startOnrampPolling()}else this.onrampUrl=null,this.onrampErrorMessage=i||"Failed to obtain onramp URL",this.showOnrampModal=!0}catch(e){this.onrampUrl=null,this.onrampErrorMessage=e?.message||"Failed to obtain onramp URL",this.showOnrampModal=!0}}startOnrampPolling(e){if(this.onrampPollTimer){try{clearInterval(this.onrampPollTimer)}catch{}this.onrampPollTimer=null}if(this.onrampNotifyController){try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null}let t=this.onrampPaymentIntentId;if(!t)return;let a=E(this.config),n=()=>{if(this.detachTransakMessageListener(),this.onrampNotifyController)try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null,this.onrampPollingActive=!1};try{window.addEventListener("icpay-sdk-transaction-completed",(()=>n()),{once:!0})}catch{}this.onrampPollingActive=!0,this.onrampNotifyController=a.notifyIntentUntilComplete(t,5e3,e),this.onrampPollTimer=1}connectedCallback(){if(super.connectedCallback(),!!He){Ce(this.config?.debug||!1,"Article paywall connected",{config:this.config}),this.config&&(typeof this.config.title=="string"&&(this.title=this.config.title),typeof this.config.preview=="string"&&(this.preview=this.config.preview),typeof this.config.lockedContent=="string"&&(this.lockedContent=this.config.lockedContent)),this.tryAutoConnectPNP();try{window.addEventListener("icpay-switch-account",this.onSwitchAccount)}catch{}try{window.addEventListener("icpay-sdk-transaction-created",(()=>{this.showWalletModal=!1,this.showBalanceModal=!1,this.requestUpdate()}))}catch{}this.onTransactionCompleted=(()=>{this.unlocked=!0,this.succeeded=!0,this.processing=!1;try{window.dispatchEvent(new CustomEvent("icpay-unlock",{detail:{amount:this.config?.priceUsd,currency:this.selectedSymbol||"ICP"}}))}catch{}this.requestUpdate()});try{window.addEventListener("icpay-sdk-transaction-completed",this.onTransactionCompleted)}catch{}this.onUnlock=(()=>{this.unlocked=!0,this.succeeded=!0,this.processing=!1,this.requestUpdate()});try{window.addEventListener("icpay-unlock",this.onUnlock)}catch{}}}disconnectedCallback(){super.disconnectedCallback();try{window.removeEventListener("icpay-switch-account",this.onSwitchAccount)}catch{}if(this.onTransactionCompleted)try{window.removeEventListener("icpay-sdk-transaction-completed",this.onTransactionCompleted)}catch{}if(this.onUnlock)try{window.removeEventListener("icpay-unlock",this.onUnlock)}catch{}}updated(e){if(e.has("config")&&this.config&&(typeof this.config.title=="string"&&(this.title=this.config.title),typeof this.config.preview=="string"&&(this.preview=this.config.preview),typeof this.config.lockedContent=="string"&&(this.lockedContent=this.config.lockedContent)),e.has("config")&&this.pendingAction&&this.config?.actorProvider){let t=this.pendingAction;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}this.walletModalStep!=="balances"&&!this.oisyReadyToPay&&(this.pendingAction=null,setTimeout(()=>{t==="unlock"&&this.unlock()},0))}}selectSymbol(e){this.selectedSymbol=e}resetPaymentFlow(){ee(this,{pendingAction:"unlock"})}async unlock(){if(He&&!this.unlocked){this.resetPaymentFlow(),Ce(this.config?.debug||!1,"Article paywall unlock started",{priceUsd:this.config.priceUsd,selectedSymbol:this.selectedSymbol,useOwnWallet:this.config.useOwnWallet});try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"unlock",type:"sendUsd",amount:this.config.priceUsd,currency:this.selectedSymbol||"ICP"}}))}catch{}this.processing=!0;try{if(this.config.useOwnWallet){if(!this.config.actorProvider){this.pendingAction="unlock",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0}));return}}else if(!this.walletConnected){Ce(this.config?.debug||!1,"Connecting to wallet via Plug N Play");try{oe||(oe=(await import("./wallet-select-3A5Z7KZJ.js")).WalletSelect);let t=!!(this.config?.openOisyInNewTab||this.config?.plugNPlay?.openOisyInNewTab)?O({...this.config?.plugNPlay||{}}):{...this.config?.plugNPlay||{}};try{if(typeof window<"u"){let{resolveDerivationOrigin:n}=await import("./origin-44ZEXSX4.js");t.derivationOrigin=this.config?.derivationOrigin||n()}}catch{}this.pnp=new oe(t);try{let n=await ie(this.pnp);if(n){this.walletConnected=!0;let i=x(this.pnp,{owner:n,principal:n,connected:!0}),s=this.pnp?.getEvmProvider?.(),o=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:i,actorProvider:(d,p)=>this.pnp.getActor({canisterId:d,idl:p,requiresSigning:!0,anon:!1}),...s?{evmProvider:s}:{},...o?{solanaProvider:o}:{}},this.sdk=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"oisy"}}))}catch{}this.unlock();return}}catch{}let a=this.pnp.getEnabledWallets();if(Ce(this.config?.debug||!1,"Available wallets",a),!a?.length)throw new Error("No wallets available");this.pendingAction="unlock",this.showWalletModal=!0;return}catch(e){Ce(this.config?.debug||!1,"Wallet connection error:",e),this.errorMessage=e instanceof Error?e.message:"Wallet connection failed",this.errorSeverity="error";return}}this.showWalletModal=!1,await this.fetchAndShowBalances();return}catch(e){f(e,{onError:t=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:t,bubbles:!0})),w(t)&&(this.errorMessage=m(t),this.errorSeverity=v(t),this.errorAction=b(t))}});try{!this.config.useOwnWallet&&this.pnp&&(await this.pnp.disconnect?.(),this.walletConnected=!1,this.config={...this.config,actorProvider:void 0,connectedWallet:void 0})}catch{}}finally{this.processing=!1}}}getWalletId(e){return e&&(e.id||e.provider||e.key)||""}getWalletLabel(e){return e&&(e.label||e.name||e.title||e.id)||"Wallet"}getWalletIcon(e){return e&&(e.icon||e.logo||e.image)||null}connectWithWallet(e){if(this.pnp)try{if(!e)throw new Error("No wallet ID provided");this.lastWalletId=(e||"").toLowerCase(),this.pnp.connect(e).then(a=>{if(!!!(a&&(a.connected===!0||a.principal||a.owner||this.pnp?.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:e}}))}catch{}let i=x(this.pnp,a),s=this.pnp?.getEvmProvider?.();this.config={...this.config,connectedWallet:i,actorProvider:(o,d)=>this.pnp.getActor({canisterId:o,idl:d,requiresSigning:!0,anon:!1}),...s?{evmProvider:s}:{}},this.sdk=null,this.walletModalStep="balances",this.showBalanceModal=!1,this.showWalletModal=!0,this.fetchAndShowBalances()}).catch(a=>{this.errorMessage=a instanceof Error?a.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-error",{detail:{message:this.errorMessage,code:"WALLET_CONNECT_ERROR"}}))}catch{}})}catch(t){this.errorMessage=t instanceof Error?t.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-error",{detail:{message:this.errorMessage,code:"WALLET_CONNECT_ERROR"}}))}catch{}}}async fetchAndShowBalances(){try{this.balancesLoading=!0,this.balancesError=null,this.walletModalStep="balances",this.showBalanceModal=!1;let e=E(this.config),{balances:t}=await Y({sdk:e,lastWalletId:this.lastWalletId,connectedWallet:this.config?.connectedWallet,amountUsd:Number(this.config?.priceUsd??0),fiatCurrency:this.config?.fiat_currency,chainShortcodes:this.config?.chainShortcodes,tokenShortcodes:this.config?.tokenShortcodes});this.walletBalances=t}catch(e){this.walletBalances=[],this.balancesError=e&&(e.message||String(e))||"Failed to load balances"}finally{this.balancesLoading=!1}}render(){return this.config?be`
1668
1668
  <div class="icpay-card icpay-section icpay-widget-base">
1669
- ${this.config?.progressBar?.enabled!==!1?ve`
1669
+ ${this.config?.progressBar?.enabled!==!1?be`
1670
1670
  <icpay-progress-bar
1671
1671
  .debug=${!!this.config?.debug}
1672
1672
  .theme=${this.config?.theme}
@@ -1684,19 +1684,19 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
1684
1684
  ${this.unlocked?"Unlocked":this.processing?"Processing\u2026":(this.config?.buttonLabel||"Pay with crypto").replace("{amount}",`${Number(this.config?.priceUsd??0).toFixed(2)}`).replace("{symbol}",this.selectedSymbol||"ICP")}
1685
1685
  </button>
1686
1686
 
1687
- ${this.errorMessage?ve`
1687
+ ${this.errorMessage?be`
1688
1688
  <div class="error-message ${this.errorSeverity}" style="margin-top: 12px; padding: 8px 12px; border-radius: 6px; font-size: 14px; text-align: center;">
1689
1689
  ${this.errorMessage}
1690
- ${this.errorAction?ve`
1690
+ ${this.errorAction?be`
1691
1691
  <button style="margin-left: 8px; padding: 4px 8px; background: transparent; border: 1px solid currentColor; border-radius: 4px; font-size: 12px; cursor: pointer;">
1692
1692
  ${this.errorAction}
1693
1693
  </button>
1694
1694
  `:""}
1695
1695
  </div>
1696
1696
  `:""}
1697
- ${(()=>{let e=this.pnp?.getEnabledWallets?.()||[],t=V(e),n=this.config?.theme?typeof this.config.theme=="string"?this.config.theme:this.config.theme.mode||"light":void 0;return Q({visible:!!(this.showWalletModal&&this.pnp),wallets:t,isConnecting:!1,step:this.walletModalStep,balances:this.walletModalStep==="balances"?this.walletBalances:[],balancesLoading:this.walletModalStep==="balances"?this.balancesLoading:!1,balancesError:this.walletModalStep==="balances"?this.balancesError:null,onSelectBalance:a=>this.onSelectBalanceSymbol(a),onBack:()=>{this.walletModalStep="connect"},onSelect:a=>this.connectWithWallet(a),onClose:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-cancelled",{detail:{reason:"user_cancelled"}}))}catch{}},onDismiss:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1},onCreditCard:this.config?.onramp?.enabled===!0&&this.config?.onrampDisabled!==!0?()=>this.startOnramp():void 0,creditCardLabel:this.config?.onramp?.creditCardLabel||"Pay with credit card",showCreditCard:this.config?.onramp?.enabled===!0&&this.config?.onrampDisabled!==!0,creditCardTooltip:(()=>{let i=Number(this.config?.priceUsd||0);return i>0&&i<5&&this.config?.onramp?.enabled===!0&&this.config?.onrampDisabled!==!0?`Note: Minimum card amount is $5. You will pay about $${(5-i).toFixed(2)} more.`:null})(),oisyReadyToPay:this.oisyReadyToPay,onOisyPay:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1,this.unlock()},theme:n})})()}
1697
+ ${(()=>{let e=this.pnp?.getEnabledWallets?.()||[],t=X(e),a=this.config?.theme?typeof this.config.theme=="string"?this.config.theme:this.config.theme.mode||"light":void 0;return Q({visible:!!(this.showWalletModal&&this.pnp),wallets:t,isConnecting:!1,step:this.walletModalStep,balances:this.walletModalStep==="balances"?this.walletBalances:[],balancesLoading:this.walletModalStep==="balances"?this.balancesLoading:!1,balancesError:this.walletModalStep==="balances"?this.balancesError:null,onSelectBalance:n=>this.onSelectBalanceSymbol(n),onBack:()=>{this.walletModalStep="connect"},onSelect:n=>this.connectWithWallet(n),onClose:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-cancelled",{detail:{reason:"user_cancelled"}}))}catch{}},onDismiss:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1},onCreditCard:this.config?.onramp?.enabled===!0&&this.config?.onrampDisabled!==!0?()=>this.startOnramp():void 0,creditCardLabel:this.config?.onramp?.creditCardLabel||"Pay with credit card",showCreditCard:this.config?.onramp?.enabled===!0&&this.config?.onrampDisabled!==!0,creditCardTooltip:(()=>{let i=Number(this.config?.priceUsd||0);return i>0&&i<5&&this.config?.onramp?.enabled===!0&&this.config?.onrampDisabled!==!0?`Note: Minimum card amount is $5. You will pay about $${(5-i).toFixed(2)} more.`:null})(),oisyReadyToPay:this.oisyReadyToPay,onOisyPay:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1,this.unlock()},theme:a})})()}
1698
1698
 
1699
- ${(()=>{let e=this.config?.theme?typeof this.config.theme=="string"?this.config.theme:this.config.theme.mode||"light":void 0;return ve`
1699
+ ${(()=>{let e=this.config?.theme?typeof this.config.theme=="string"?this.config.theme:this.config.theme.mode||"light":void 0;return be`
1700
1700
  ${Z({visible:this.showBalanceModal,isLoading:this.balancesLoading,error:this.balancesError,balances:this.walletBalances,onSelect:t=>this.onSelectBalanceSymbol(t),onClose:()=>{this.showBalanceModal=!1},theme:e})}
1701
1701
 
1702
1702
  ${H({visible:this.showOnrampModal,url:this.onrampUrl||void 0,errorMessage:this.onrampErrorMessage||void 0,width:this.config?.onramp?.width,height:this.config?.onramp?.height,onClose:()=>{this.showOnrampModal=!1},onBack:()=>{this.showOnrampModal=!1,this.showWalletModal=!0},title:"Pay with credit card",theme:e})}
@@ -1705,7 +1705,7 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
1705
1705
  <a href="https://icpay.org" target="_blank" rel="noopener noreferrer">Powered by icpay</a>
1706
1706
  </div>
1707
1707
  </div>
1708
- `:ve`<div class="icpay-card icpay-section">Loading...</div>`}};C.styles=[K,Wt`
1708
+ `:be`<div class="icpay-card icpay-section">Loading...</div>`}};C.styles=[K,Wt`
1709
1709
  .container { background: var(--icpay-surface-alt); border: 1px solid var(--icpay-border); border-radius: 16px; padding: 16px; margin-bottom: 16px; }
1710
1710
  .title { color: var(--icpay-text); font-weight: 700; margin-bottom: 8px; }
1711
1711
  .preview { color: var(--icpay-muted-foreground); margin-bottom: 12px; line-height: 1.6; }
@@ -1737,9 +1737,9 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
1737
1737
  border-color: var(--icpay-error-border);
1738
1738
  color: var(--icpay-error-text);
1739
1739
  }
1740
- `],s([Oe({type:Object})],C.prototype,"config",2),s([Oe({type:String})],C.prototype,"title",2),s([Oe({type:String})],C.prototype,"preview",2),s([Oe({type:String})],C.prototype,"lockedContent",2),s([B()],C.prototype,"selectedSymbol",2),s([B()],C.prototype,"unlocked",2),s([B()],C.prototype,"succeeded",2),s([B()],C.prototype,"processing",2),s([B()],C.prototype,"errorMessage",2),s([B()],C.prototype,"errorSeverity",2),s([B()],C.prototype,"errorAction",2),s([B()],C.prototype,"walletConnected",2),s([B()],C.prototype,"pendingAction",2),s([B()],C.prototype,"showWalletModal",2),s([B()],C.prototype,"walletModalStep",2),s([B()],C.prototype,"oisyReadyToPay",2),s([B()],C.prototype,"lastWalletId",2),s([B()],C.prototype,"showOnrampModal",2),s([B()],C.prototype,"onrampUrl",2),s([B()],C.prototype,"onrampPaymentIntentId",2),s([B()],C.prototype,"onrampErrorMessage",2),s([B()],C.prototype,"showBalanceModal",2),s([B()],C.prototype,"balancesLoading",2),s([B()],C.prototype,"balancesError",2),s([B()],C.prototype,"walletBalances",2),C=s([At("icpay-article-paywall")],C);import{LitElement as Pt,html as he,css as Tt}from"lit";import{customElement as Lt,property as Ot,state as F}from"lit/decorators.js";var Ke=typeof window<"u",we=null;function Se(r,l,e){r&&(e!==void 0?console.log(`[ICPay Widget] ${l}`,e):console.log(`[ICPay Widget] ${l}`))}var L=class extends Pt{constructor(){super(...arguments);this.selectedIndex=0;this.selectedSymbol=null;this.processing=!1;this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.walletModalStep="connect";this.oisyReadyToPay=!1;this.lastWalletId=null;this.pnp=null;this.showOnrampModal=!1;this.onrampUrl=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.transakMessageHandlerBound=null;this.onrampPollTimer=null;this.onrampPollingActive=!1;this.onrampNotifyController=null;this.sdk=null;this.showBalanceModal=!1;this.balancesLoading=!1;this.balancesError=null;this.walletBalances=[];this.onSwitchAccount=async e=>{try{if(this.pnp)try{await this.pnp.disconnect()}catch{}this.walletConnected=!1,this.config={...this.config,actorProvider:void 0,connectedWallet:void 0},this.pendingAction="order",this.showWalletModal=!0,this.requestUpdate();try{let t=Number(this.selectedItem?.priceUsd||0),n=this.selectedSymbol||"ICP";window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"order",type:"sendUsd",amount:t,currency:n}}))}catch{}}catch{}};this.onSelectBalanceSymbol=async e=>{let t=(this.walletBalances||[]).find(a=>a?.tokenShortcode===e);if(t?.ledgerSymbol&&(this.selectedSymbol=t.ledgerSymbol),this.showBalanceModal=!1,this.showWalletModal=!1,q(this.lastWalletId)){let a=(this.walletBalances||[]).find(o=>o?.tokenShortcode===e),i=a?.chainId;X(i,{provider:this.pnp?.getEvmProvider?.()||this.config?.evmProvider,chainName:a?.chainName,rpcUrlPublic:a?.rpcUrlPublic,nativeSymbol:a?.ledgerSymbol,decimals:a?.decimals}).then(async()=>{try{let o=E(this.config),c=Number(this.selectedItem?.priceUsd||0);if(a?.x402Accepts&&!J(this.lastWalletId))try{await o.client.createPaymentX402Usd({usdAmount:c,tokenShortcode:a?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:"evm",icpay_ledger_id:a?.ledgerId,icpay_context:"coffee:x402",item:this.selectedItem?.name}},recipientAddress:(this.config?.recipientAddresses||{})?.evm||"0x0000000000000000000000000000000000000000",fiat_currency:this.config?.fiat_currency}),this.showBalanceModal=!1;return}catch(d){f(d,{onError:p=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:p,bubbles:!0})),v(p)&&(this.errorMessage=g(p),this.errorSeverity=b(p),this.errorAction=w(p))}})}await o.client.createPaymentUsd({usdAmount:c,tokenShortcode:a?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:"evm",icpay_ledger_id:a?.ledgerId,item:this.selectedItem?.name}},recipientAddress:(this.config?.recipientAddresses||{})?.evm||"0x0000000000000000000000000000000000000000"}).catch(d=>{throw d})}catch(o){f(o,{onError:c=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:c,bubbles:!0})),v(c)&&(this.errorMessage=g(c),this.errorSeverity=b(c),this.errorAction=w(c))}})}this.showBalanceModal=!1});return}let n=this.pendingAction;if(this.pendingAction=null,n==="order")try{let a=(this.walletBalances||[]).find(u=>u?.tokenShortcode===e),i=E(this.config),o=Number(this.selectedItem?.priceUsd||0),c=String(a?.ledgerName||a?.chainName||"").toLowerCase(),d=c.includes("sol"),p=c.includes("ic"),y=this.config?.recipientAddresses||{},h=d&&y.sol||y.ic;if(a?.x402Accepts)try{await i.client.createPaymentX402Usd({usdAmount:o,tokenShortcode:a?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:d?"sol":p?"ic":this.config?.icpay_network,icpay_ledger_id:a?.ledgerId,icpay_context:"coffee:x402",item:this.selectedItem?.name}},recipientAddress:h||"",fiat_currency:this.config?.fiat_currency});return}catch(u){f(u,{onError:m=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:m,bubbles:!0})),v(m)&&(this.errorMessage=g(m),this.errorSeverity=b(m),this.errorAction=w(m))}});return}await i.client.createPaymentUsd({usdAmount:o,tokenShortcode:a?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:"ic",icpay_ledger_id:a?.ledgerId,item:this.selectedItem?.name}},recipientAddress:h||"0x0000000000000000000000000000000000000000"}).catch(u=>{throw u})}catch(a){f(a,{onError:i=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:i,bubbles:!0})),v(i)&&(this.errorMessage=g(i),this.errorSeverity=b(i),this.errorAction=w(i))}})}}}connectedCallback(){if(super.connectedCallback(),!!Ke){Se(this.config?.debug||!1,"Coffee shop connected",{config:this.config}),this.config&&typeof this.config.defaultItemIndex=="number"&&(this.selectedIndex=this.config.defaultItemIndex);try{window.addEventListener("icpay-switch-account",this.onSwitchAccount)}catch{}try{window.addEventListener("icpay-sdk-transaction-created",(()=>{this.showWalletModal=!1,this.requestUpdate()}))}catch{}}}updated(e){if(e.has("config")&&this.pendingAction&&this.config?.actorProvider){let t=this.pendingAction;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}this.walletModalStep!=="balances"&&!this.oisyReadyToPay&&(this.pendingAction=null,setTimeout(()=>{t==="order"&&this.order()},0))}}selectItem(e){this.selectedIndex=e}selectSymbol(e){this.selectedSymbol=e}get selectedItem(){return this.config?.items?.[this.selectedIndex]||{name:"Loading...",priceUsd:0}}async getOrCreatePnp(){if(this.pnp)return this.pnp;we||(we=(await import("./wallet-select-VE5FSSFG.js")).WalletSelect);let e=!!(this.config?.openOisyInNewTab||this.config?.plugNPlay?.openOisyInNewTab),t={...this.config?.plugNPlay||{}},n=this.config?.recipientAddresses;if(n&&(n.ic||n.evm||n.sol)){let i=[];n.ic&&i.push("ic"),n.evm&&i.push("evm"),n.sol&&i.push("sol"),i.length&&(t.chainTypes=i)}else this.config?.chainTypes&&(t.chainTypes=this.config.chainTypes);let a=e?I(t):t;try{if(typeof window<"u"){let{resolveDerivationOrigin:i}=await import("./origin-44ZEXSX4.js");a.derivationOrigin=this.config?.derivationOrigin||i()}}catch{}return this.pnp=new we(a),this.pnp}async generateWalletConnectQr(e){try{let t=await this.getOrCreatePnp();return!t||typeof t.generateWalletConnectQr!="function"?null:await t.generateWalletConnectQr({onConnected:n=>{this.walletConnected=!0,this.lastWalletId="walletconnect";let a=x(this.pnp,n),i=this.pnp?.getEvmProvider?.(),o=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:a,actorProvider:(c,d)=>this.pnp.getActor({canisterId:c,idl:d,requiresSigning:!0,anon:!1}),...i?{evmProvider:i}:{},...o?{solanaProvider:o}:{}},this.sdk=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"walletconnect"}}))}catch{}try{e?.onConnected?.()}catch{}this.requestUpdate()}})}catch{return null}}async checkCoinbaseConnection(){try{return(await this.getOrCreatePnp())?.hasCoinbaseAccounts?.()??!1}catch{return!1}}async connectWallet(e){let t=await this.getOrCreatePnp();if(!t||!e)throw new Error("Wallet not available");let n=(e||"").toLowerCase(),a=await t.connect(n);if(!!!(a&&(a.connected===!0||a.principal||a.owner||t.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0,this.lastWalletId=n;let o=x(this.pnp,a),c=this.pnp?.getEvmProvider?.(),d=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:o,actorProvider:(p,y)=>this.pnp.getActor({canisterId:p,idl:y,requiresSigning:!0,anon:!1}),...c?{evmProvider:c}:{},...d?{solanaProvider:d}:{}},this.sdk=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:n}}))}catch{}this.requestUpdate()}resetPaymentFlow(){ee(this,{pendingAction:"order"})}async order(){if(Ke){this.resetPaymentFlow(),Se(this.config?.debug||!1,"Coffee order started",{selectedItem:this.selectedItem,selectedSymbol:this.selectedSymbol,useOwnWallet:this.config.useOwnWallet});try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"order",type:"sendUsd",amount:this.selectedItem.priceUsd,currency:this.selectedSymbol||"ICP"}}))}catch{}this.processing=!0;try{if(this.config.useOwnWallet){if(!this.config.actorProvider){this.pendingAction="order",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0}));return}}else if(!this.walletConnected){Se(this.config?.debug||!1,"Connecting to wallet via Plug N Play");try{we||(we=(await import("./wallet-select-VE5FSSFG.js")).WalletSelect);let t=!!(this.config?.openOisyInNewTab||this.config?.plugNPlay?.openOisyInNewTab)?I({...this.config?.plugNPlay||{}}):{...this.config?.plugNPlay||{}},n=this.config?.recipientAddresses;if(n&&(n.ic||n.evm||n.sol)){let i=[];n.ic&&i.push("ic"),n.evm&&i.push("evm"),n.sol&&i.push("sol"),i.length&&(t.chainTypes=i)}else this.config?.chainTypes&&(t.chainTypes=this.config.chainTypes);try{if(typeof window<"u"){let{resolveDerivationOrigin:i}=await import("./origin-44ZEXSX4.js");t.derivationOrigin=this.config?.derivationOrigin||i()}}catch{}this.pnp=new we(t);try{let i=await ae(this.pnp);if(i){this.walletConnected=!0;let o=x(this.pnp,{owner:i,principal:i,connected:!0}),c=this.pnp?.getEvmProvider?.();this.config={...this.config,connectedWallet:o,actorProvider:(d,p)=>this.pnp.getActor({canisterId:d,idl:p,requiresSigning:!0,anon:!1}),...c?{evmProvider:c}:{}},this.sdk=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"oisy"}}))}catch{}this.order();return}}catch{}let a=this.pnp.getEnabledWallets();if(Se(this.config?.debug||!1,"Available wallets",a),!a?.length)throw new Error("No wallets available");this.pendingAction="order",this.showWalletModal=!0;return}catch(e){Se(this.config?.debug||!1,"Wallet connection error:",e),this.errorMessage=e instanceof Error?e.message:"Wallet connection failed",this.errorSeverity="error";return}}this.pendingAction="order",this.showWalletModal=!0,await this.fetchAndShowBalances();return}catch(e){f(e,{onError:t=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:t,bubbles:!0})),v(t)&&(this.errorMessage=g(t),this.errorSeverity=b(t),this.errorAction=w(t))}});try{!this.config.useOwnWallet&&this.pnp&&(await this.pnp.disconnect?.(),this.walletConnected=!1,this.config={...this.config,actorProvider:void 0,connectedWallet:void 0})}catch{}}finally{this.processing=!1}}}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=e=>this.onTransakMessage(e);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(e){let t=e?.data,n=t?.event_id||t?.eventId||t?.id;if(!(!n||typeof n!="string")&&n==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;this.showOnrampModal=!1;let a=t?.data?.id||t?.id||t?.webhookData?.id||null;this.startOnrampPolling(a||void 0)}}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"createPaymentUsd",type:"onramp"}}))}catch{}this.showWalletModal=!1,setTimeout(()=>this.createOnrampIntent(),0)}async createOnrampIntent(){try{let t=await E(this.config).startOnrampUsd(this.selectedItem.priceUsd,void 0,{context:"coffee:onramp",onrampPayment:!0,item:this.selectedItem.name,onrampProvider:"coinbase"}),n=t?.metadata?.onramp?.url||t?.onramp?.url||t?.metadata?.icpay_onramp?.url||t?.paymentIntent?.metadata?.icpay?.onrampUrl||t?.metadata?.icpay?.onrampUrl||null,a=t?.metadata?.icpay_payment_intent_id||t?.metadata?.paymentIntentId||t?.paymentIntentId||null,i=t?.metadata?.icpay_onramp?.errorMessage||t?.metadata?.onramp?.errorMessage||t?.paymentIntent?.metadata?.icpay?.onrampError||t?.paymentIntent?.metadata?.icpay?.errorMessage||t?.metadata?.icpay?.onrampError||t?.metadata?.icpay?.errorMessage||null;if(this.onrampPaymentIntentId=a,n){this.onrampUrl=n,this.onrampErrorMessage=null;try{window.open(n,"icpay_onramp","noopener,noreferrer");try{window.dispatchEvent(new CustomEvent("icpay-onramp-opened",{detail:{url:n}}))}catch{}}catch{}this.startOnrampPolling()}else this.onrampUrl=null,this.onrampErrorMessage=i||"Failed to obtain onramp URL",this.showOnrampModal=!0}catch(e){this.onrampUrl=null,this.onrampErrorMessage=e?.message||"Failed to obtain onramp URL",this.showOnrampModal=!0}}startOnrampPolling(e){if(this.onrampPollTimer){try{clearInterval(this.onrampPollTimer)}catch{}this.onrampPollTimer=null}if(this.onrampNotifyController){try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null}let t=this.onrampPaymentIntentId;if(!t)return;let n=E(this.config),a=()=>{if(this.onrampNotifyController)try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null,this.onrampPollingActive=!1};try{window.addEventListener("icpay-sdk-transaction-completed",(()=>a()),{once:!0})}catch{}this.onrampPollingActive=!0,this.onrampNotifyController=n.notifyIntentUntilComplete(t,5e3,e),this.onrampPollTimer=1}getWalletId(e){return e&&(e.id||e.provider||e.key)||""}getWalletLabel(e){return e&&(e.label||e.name||e.title||e.id)||"Wallet"}getWalletIcon(e){return e&&(e.icon||e.logo||e.image)||null}connectWithWallet(e){if(this.pnp)try{if(!e)throw new Error("No wallet ID provided");this.lastWalletId=(e||"").toLowerCase(),this.pnp.connect(e).then(n=>{if(!!!(n&&(n.connected===!0||n.principal||n.owner||this.pnp?.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:e}}))}catch{}let i=x(this.pnp,n),o=this.pnp?.getEvmProvider?.(),c=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:i,actorProvider:(d,p)=>this.pnp.getActor({canisterId:d,idl:p,requiresSigning:!0,anon:!1}),...o?{evmProvider:o}:{},...c?{solanaProvider:c}:{}},this.sdk=null,this.walletModalStep="balances",this.showBalanceModal=!1,this.showWalletModal=!0,this.fetchAndShowBalances()}).catch(n=>{this.errorMessage=n instanceof Error?n.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-error",{detail:{message:this.errorMessage,code:"WALLET_CONNECT_ERROR"}}))}catch{}})}catch(t){this.errorMessage=t instanceof Error?t.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-error",{detail:{message:this.errorMessage,code:"WALLET_CONNECT_ERROR"}}))}catch{}}}async fetchAndShowBalances(){try{this.balancesLoading=!0,this.balancesError=null,this.walletModalStep="balances",this.showBalanceModal=!1;let e=E(this.config),{balances:t}=await Y({sdk:e,lastWalletId:this.lastWalletId,connectedWallet:this.config?.connectedWallet,amountUsd:Number(this.selectedItem?.priceUsd??0),fiatCurrency:this.config?.fiat_currency,chainShortcodes:this.config?.chainShortcodes,tokenShortcodes:this.config?.tokenShortcodes});this.walletBalances=t}catch(e){this.walletBalances=[],this.balancesError=e&&(e.message||String(e))||"Failed to load balances"}finally{this.balancesLoading=!1}}render(){return this.config?he`
1740
+ `],c([Le({type:Object})],C.prototype,"config",2),c([Le({type:String})],C.prototype,"title",2),c([Le({type:String})],C.prototype,"preview",2),c([Le({type:String})],C.prototype,"lockedContent",2),c([F()],C.prototype,"selectedSymbol",2),c([F()],C.prototype,"unlocked",2),c([F()],C.prototype,"succeeded",2),c([F()],C.prototype,"processing",2),c([F()],C.prototype,"errorMessage",2),c([F()],C.prototype,"errorSeverity",2),c([F()],C.prototype,"errorAction",2),c([F()],C.prototype,"walletConnected",2),c([F()],C.prototype,"pendingAction",2),c([F()],C.prototype,"showWalletModal",2),c([F()],C.prototype,"walletModalStep",2),c([F()],C.prototype,"oisyReadyToPay",2),c([F()],C.prototype,"lastWalletId",2),c([F()],C.prototype,"showOnrampModal",2),c([F()],C.prototype,"onrampUrl",2),c([F()],C.prototype,"onrampPaymentIntentId",2),c([F()],C.prototype,"onrampErrorMessage",2),c([F()],C.prototype,"showBalanceModal",2),c([F()],C.prototype,"balancesLoading",2),c([F()],C.prototype,"balancesError",2),c([F()],C.prototype,"walletBalances",2),C=c([At("icpay-article-paywall")],C);import{LitElement as Pt,html as ue,css as Tt}from"lit";import{customElement as It,property as Lt,state as D}from"lit/decorators.js";var Xe=typeof window<"u",Ee=null;function Me(r,l,e){r&&(e!==void 0?console.log(`[ICPay Widget] ${l}`,e):console.log(`[ICPay Widget] ${l}`))}var L=class extends Pt{constructor(){super(...arguments);this.selectedIndex=0;this.selectedSymbol=null;this.processing=!1;this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.walletModalStep="connect";this.oisyReadyToPay=!1;this.lastWalletId=null;this.pnp=null;this.showOnrampModal=!1;this.onrampUrl=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.transakMessageHandlerBound=null;this.onrampPollTimer=null;this.onrampPollingActive=!1;this.onrampNotifyController=null;this.sdk=null;this.showBalanceModal=!1;this.balancesLoading=!1;this.balancesError=null;this.walletBalances=[];this.onSwitchAccount=async e=>{try{if(this.pnp)try{await this.pnp.disconnect()}catch{}this.walletConnected=!1,this.config={...this.config,actorProvider:void 0,connectedWallet:void 0},this.pendingAction="order",this.showWalletModal=!0,this.requestUpdate();try{let t=Number(this.selectedItem?.priceUsd||0),a=this.selectedSymbol||"ICP";window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"order",type:"sendUsd",amount:t,currency:a}}))}catch{}}catch{}};this.onSelectBalanceSymbol=async e=>{let t=(this.walletBalances||[]).find(n=>n?.tokenShortcode===e);if(t?.ledgerSymbol&&(this.selectedSymbol=t.ledgerSymbol),this.showBalanceModal=!1,this.showWalletModal=!1,j(this.lastWalletId)){let n=(this.walletBalances||[]).find(s=>s?.tokenShortcode===e),i=n?.chainId;V(i,{provider:this.pnp?.getEvmProvider?.()||this.config?.evmProvider,chainName:n?.chainName,rpcUrlPublic:n?.rpcUrlPublic,nativeSymbol:n?.ledgerSymbol,decimals:n?.decimals}).then(async()=>{try{let s=E(this.config),o=Number(this.selectedItem?.priceUsd||0);if(n?.x402Accepts&&!J(this.lastWalletId))try{await s.client.createPaymentX402Usd({usdAmount:o,tokenShortcode:n?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:"evm",icpay_ledger_id:n?.ledgerId,icpay_context:"coffee:x402",item:this.selectedItem?.name}},recipientAddress:(this.config?.recipientAddresses||{})?.evm||"0x0000000000000000000000000000000000000000",fiat_currency:this.config?.fiat_currency}),this.showBalanceModal=!1;return}catch(d){f(d,{onError:p=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:p,bubbles:!0})),w(p)&&(this.errorMessage=m(p),this.errorSeverity=v(p),this.errorAction=b(p))}})}await s.client.createPaymentUsd({usdAmount:o,tokenShortcode:n?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:"evm",icpay_ledger_id:n?.ledgerId,item:this.selectedItem?.name}},recipientAddress:(this.config?.recipientAddresses||{})?.evm||"0x0000000000000000000000000000000000000000"}).catch(d=>{throw d})}catch(s){f(s,{onError:o=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:o,bubbles:!0})),w(o)&&(this.errorMessage=m(o),this.errorSeverity=v(o),this.errorAction=b(o))}})}this.showBalanceModal=!1});return}let a=this.pendingAction;if(this.pendingAction=null,a==="order")try{let n=(this.walletBalances||[]).find(u=>u?.tokenShortcode===e),i=E(this.config),s=Number(this.selectedItem?.priceUsd||0),o=String(n?.ledgerName||n?.chainName||"").toLowerCase(),d=o.includes("sol"),p=o.includes("ic"),y=this.config?.recipientAddresses||{},h=d&&y.sol||y.ic;if(n?.x402Accepts)try{await i.client.createPaymentX402Usd({usdAmount:s,tokenShortcode:n?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:d?"sol":p?"ic":this.config?.icpay_network,icpay_ledger_id:n?.ledgerId,icpay_context:"coffee:x402",item:this.selectedItem?.name}},recipientAddress:h||"",fiat_currency:this.config?.fiat_currency});return}catch(u){f(u,{onError:g=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:g,bubbles:!0})),w(g)&&(this.errorMessage=m(g),this.errorSeverity=v(g),this.errorAction=b(g))}});return}await i.client.createPaymentUsd({usdAmount:s,tokenShortcode:n?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:"ic",icpay_ledger_id:n?.ledgerId,item:this.selectedItem?.name}},recipientAddress:h||"0x0000000000000000000000000000000000000000"}).catch(u=>{throw u})}catch(n){f(n,{onError:i=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:i,bubbles:!0})),w(i)&&(this.errorMessage=m(i),this.errorSeverity=v(i),this.errorAction=b(i))}})}}}connectedCallback(){if(super.connectedCallback(),!!Xe){Me(this.config?.debug||!1,"Coffee shop connected",{config:this.config}),this.config&&typeof this.config.defaultItemIndex=="number"&&(this.selectedIndex=this.config.defaultItemIndex);try{window.addEventListener("icpay-switch-account",this.onSwitchAccount)}catch{}try{window.addEventListener("icpay-sdk-transaction-created",(()=>{this.showWalletModal=!1,this.requestUpdate()}))}catch{}}}updated(e){if(e.has("config")&&this.pendingAction&&this.config?.actorProvider){let t=this.pendingAction;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}this.walletModalStep!=="balances"&&!this.oisyReadyToPay&&(this.pendingAction=null,setTimeout(()=>{t==="order"&&this.order()},0))}}selectItem(e){this.selectedIndex=e}selectSymbol(e){this.selectedSymbol=e}get selectedItem(){return this.config?.items?.[this.selectedIndex]||{name:"Loading...",priceUsd:0}}async getOrCreatePnp(){if(this.pnp)return this.pnp;Ee||(Ee=(await import("./wallet-select-3A5Z7KZJ.js")).WalletSelect);let e=!!(this.config?.openOisyInNewTab||this.config?.plugNPlay?.openOisyInNewTab),t={...this.config?.plugNPlay||{}},a=this.config?.recipientAddresses;if(a&&(a.ic||a.evm||a.sol)){let i=[];a.ic&&i.push("ic"),a.evm&&i.push("evm"),a.sol&&i.push("sol"),i.length&&(t.chainTypes=i)}else this.config?.chainTypes&&(t.chainTypes=this.config.chainTypes);let n=e?O(t):t;try{if(typeof window<"u"){let{resolveDerivationOrigin:i}=await import("./origin-44ZEXSX4.js");n.derivationOrigin=this.config?.derivationOrigin||i()}}catch{}return this.pnp=new Ee(n),this.pnp}async generateWalletConnectQr(e){try{let t=await this.getOrCreatePnp();return!t||typeof t.generateWalletConnectQr!="function"?null:await t.generateWalletConnectQr({onConnected:a=>{this.walletConnected=!0,this.lastWalletId="walletconnect";let n=x(this.pnp,a),i=this.pnp?.getEvmProvider?.(),s=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:n,actorProvider:(o,d)=>this.pnp.getActor({canisterId:o,idl:d,requiresSigning:!0,anon:!1}),...i?{evmProvider:i}:{},...s?{solanaProvider:s}:{}},this.sdk=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"walletconnect"}}))}catch{}try{e?.onConnected?.()}catch{}this.requestUpdate()}})}catch{return null}}async checkCoinbaseConnection(){try{return(await this.getOrCreatePnp())?.hasCoinbaseAccounts?.()??!1}catch{return!1}}async connectWallet(e){let t=await this.getOrCreatePnp();if(!t||!e)throw new Error("Wallet not available");let a=(e||"").toLowerCase(),n=await t.connect(a);if(!!!(n&&(n.connected===!0||n.principal||n.owner||t.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0,this.lastWalletId=a;let s=x(this.pnp,n),o=this.pnp?.getEvmProvider?.(),d=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:s,actorProvider:(p,y)=>this.pnp.getActor({canisterId:p,idl:y,requiresSigning:!0,anon:!1}),...o?{evmProvider:o}:{},...d?{solanaProvider:d}:{}},this.sdk=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:a}}))}catch{}this.requestUpdate()}resetPaymentFlow(){ee(this,{pendingAction:"order"})}async order(){if(Xe){this.resetPaymentFlow(),Me(this.config?.debug||!1,"Coffee order started",{selectedItem:this.selectedItem,selectedSymbol:this.selectedSymbol,useOwnWallet:this.config.useOwnWallet});try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"order",type:"sendUsd",amount:this.selectedItem.priceUsd,currency:this.selectedSymbol||"ICP"}}))}catch{}this.processing=!0;try{if(this.config.useOwnWallet){if(!this.config.actorProvider){this.pendingAction="order",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0}));return}}else if(!this.walletConnected){Me(this.config?.debug||!1,"Connecting to wallet via Plug N Play");try{Ee||(Ee=(await import("./wallet-select-3A5Z7KZJ.js")).WalletSelect);let t=!!(this.config?.openOisyInNewTab||this.config?.plugNPlay?.openOisyInNewTab)?O({...this.config?.plugNPlay||{}}):{...this.config?.plugNPlay||{}},a=this.config?.recipientAddresses;if(a&&(a.ic||a.evm||a.sol)){let i=[];a.ic&&i.push("ic"),a.evm&&i.push("evm"),a.sol&&i.push("sol"),i.length&&(t.chainTypes=i)}else this.config?.chainTypes&&(t.chainTypes=this.config.chainTypes);try{if(typeof window<"u"){let{resolveDerivationOrigin:i}=await import("./origin-44ZEXSX4.js");t.derivationOrigin=this.config?.derivationOrigin||i()}}catch{}this.pnp=new Ee(t);try{let i=await ie(this.pnp);if(i){this.walletConnected=!0;let s=x(this.pnp,{owner:i,principal:i,connected:!0}),o=this.pnp?.getEvmProvider?.();this.config={...this.config,connectedWallet:s,actorProvider:(d,p)=>this.pnp.getActor({canisterId:d,idl:p,requiresSigning:!0,anon:!1}),...o?{evmProvider:o}:{}},this.sdk=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"oisy"}}))}catch{}this.order();return}}catch{}let n=this.pnp.getEnabledWallets();if(Me(this.config?.debug||!1,"Available wallets",n),!n?.length)throw new Error("No wallets available");this.pendingAction="order",this.showWalletModal=!0;return}catch(e){Me(this.config?.debug||!1,"Wallet connection error:",e),this.errorMessage=e instanceof Error?e.message:"Wallet connection failed",this.errorSeverity="error";return}}this.pendingAction="order",this.showWalletModal=!0,await this.fetchAndShowBalances();return}catch(e){f(e,{onError:t=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:t,bubbles:!0})),w(t)&&(this.errorMessage=m(t),this.errorSeverity=v(t),this.errorAction=b(t))}});try{!this.config.useOwnWallet&&this.pnp&&(await this.pnp.disconnect?.(),this.walletConnected=!1,this.config={...this.config,actorProvider:void 0,connectedWallet:void 0})}catch{}}finally{this.processing=!1}}}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=e=>this.onTransakMessage(e);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(e){let t=e?.data,a=t?.event_id||t?.eventId||t?.id;if(!(!a||typeof a!="string")&&a==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;this.showOnrampModal=!1;let n=t?.data?.id||t?.id||t?.webhookData?.id||null;this.startOnrampPolling(n||void 0)}}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"createPaymentUsd",type:"onramp"}}))}catch{}this.showWalletModal=!1,setTimeout(()=>this.createOnrampIntent(),0)}async createOnrampIntent(){try{let t=await E(this.config).startOnrampUsd(this.selectedItem.priceUsd,void 0,{context:"coffee:onramp",onrampPayment:!0,item:this.selectedItem.name,onrampProvider:"coinbase"}),a=t?.metadata?.onramp?.url||t?.onramp?.url||t?.metadata?.icpay_onramp?.url||t?.paymentIntent?.metadata?.icpay?.onrampUrl||t?.metadata?.icpay?.onrampUrl||null,n=t?.metadata?.icpay_payment_intent_id||t?.metadata?.paymentIntentId||t?.paymentIntentId||null,i=t?.metadata?.icpay_onramp?.errorMessage||t?.metadata?.onramp?.errorMessage||t?.paymentIntent?.metadata?.icpay?.onrampError||t?.paymentIntent?.metadata?.icpay?.errorMessage||t?.metadata?.icpay?.onrampError||t?.metadata?.icpay?.errorMessage||null;if(this.onrampPaymentIntentId=n,a){this.onrampUrl=a,this.onrampErrorMessage=null;try{window.open(a,"icpay_onramp","noopener,noreferrer");try{window.dispatchEvent(new CustomEvent("icpay-onramp-opened",{detail:{url:a}}))}catch{}}catch{}this.startOnrampPolling()}else this.onrampUrl=null,this.onrampErrorMessage=i||"Failed to obtain onramp URL",this.showOnrampModal=!0}catch(e){this.onrampUrl=null,this.onrampErrorMessage=e?.message||"Failed to obtain onramp URL",this.showOnrampModal=!0}}startOnrampPolling(e){if(this.onrampPollTimer){try{clearInterval(this.onrampPollTimer)}catch{}this.onrampPollTimer=null}if(this.onrampNotifyController){try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null}let t=this.onrampPaymentIntentId;if(!t)return;let a=E(this.config),n=()=>{if(this.onrampNotifyController)try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null,this.onrampPollingActive=!1};try{window.addEventListener("icpay-sdk-transaction-completed",(()=>n()),{once:!0})}catch{}this.onrampPollingActive=!0,this.onrampNotifyController=a.notifyIntentUntilComplete(t,5e3,e),this.onrampPollTimer=1}getWalletId(e){return e&&(e.id||e.provider||e.key)||""}getWalletLabel(e){return e&&(e.label||e.name||e.title||e.id)||"Wallet"}getWalletIcon(e){return e&&(e.icon||e.logo||e.image)||null}connectWithWallet(e){if(this.pnp)try{if(!e)throw new Error("No wallet ID provided");this.lastWalletId=(e||"").toLowerCase(),this.pnp.connect(e).then(a=>{if(!!!(a&&(a.connected===!0||a.principal||a.owner||this.pnp?.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:e}}))}catch{}let i=x(this.pnp,a),s=this.pnp?.getEvmProvider?.(),o=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:i,actorProvider:(d,p)=>this.pnp.getActor({canisterId:d,idl:p,requiresSigning:!0,anon:!1}),...s?{evmProvider:s}:{},...o?{solanaProvider:o}:{}},this.sdk=null,this.walletModalStep="balances",this.showBalanceModal=!1,this.showWalletModal=!0,this.fetchAndShowBalances()}).catch(a=>{this.errorMessage=a instanceof Error?a.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-error",{detail:{message:this.errorMessage,code:"WALLET_CONNECT_ERROR"}}))}catch{}})}catch(t){this.errorMessage=t instanceof Error?t.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-error",{detail:{message:this.errorMessage,code:"WALLET_CONNECT_ERROR"}}))}catch{}}}async fetchAndShowBalances(){try{this.balancesLoading=!0,this.balancesError=null,this.walletModalStep="balances",this.showBalanceModal=!1;let e=E(this.config),{balances:t}=await Y({sdk:e,lastWalletId:this.lastWalletId,connectedWallet:this.config?.connectedWallet,amountUsd:Number(this.selectedItem?.priceUsd??0),fiatCurrency:this.config?.fiat_currency,chainShortcodes:this.config?.chainShortcodes,tokenShortcodes:this.config?.tokenShortcodes});this.walletBalances=t}catch(e){this.walletBalances=[],this.balancesError=e&&(e.message||String(e))||"Failed to load balances"}finally{this.balancesLoading=!1}}render(){return this.config?ue`
1741
1741
  <div class="icpay-card icpay-section icpay-widget-base">
1742
- ${this.config?.progressBar?.enabled!==!1?he`
1742
+ ${this.config?.progressBar?.enabled!==!1?ue`
1743
1743
  <icpay-progress-bar
1744
1744
  .debug=${!!this.config?.debug}
1745
1745
  .theme=${this.config?.theme}
@@ -1748,7 +1748,7 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
1748
1748
  ></icpay-progress-bar>
1749
1749
  `:null}
1750
1750
  <div class="menu">
1751
- ${this.config.items.map((e,t)=>he`
1751
+ ${this.config.items.map((e,t)=>ue`
1752
1752
  <div class="item ${this.selectedIndex===t?"selected":""}" @click=${()=>this.selectItem(t)}>
1753
1753
  <span>${e.name}</span>
1754
1754
  <span>$${Number(e?.priceUsd??0).toFixed(2)}</span>
@@ -1764,19 +1764,19 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
1764
1764
  ${this.processing?"Processing\u2026":`Order ${this.selectedItem.name}`}
1765
1765
  </button>
1766
1766
 
1767
- ${this.errorMessage?he`
1767
+ ${this.errorMessage?ue`
1768
1768
  <div class="error-message ${this.errorSeverity}" style="margin-top: 12px; padding: 8px 12px; border-radius: 6px; font-size: 14px; text-align: center;">
1769
1769
  ${this.errorMessage}
1770
- ${this.errorAction?he`
1770
+ ${this.errorAction?ue`
1771
1771
  <button style="margin-left: 8px; padding: 4px 8px; background: transparent; border: 1px solid currentColor; border-radius: 4px; font-size: 12px; cursor: pointer;">
1772
1772
  ${this.errorAction}
1773
1773
  </button>
1774
1774
  `:""}
1775
1775
  </div>
1776
1776
  `:""}
1777
- ${(()=>{let e=this.pnp?.getEnabledWallets?.()||[],t=V(e),n=this.config?.theme?typeof this.config.theme=="string"?this.config.theme:this.config.theme.mode||"light":void 0;return Q({visible:!!(this.showWalletModal&&this.pnp),wallets:t,isConnecting:!1,step:this.walletModalStep,balances:this.walletModalStep==="balances"?this.walletBalances:[],balancesLoading:this.walletModalStep==="balances"?this.balancesLoading:!1,balancesError:this.walletModalStep==="balances"?this.balancesError:null,onSelectBalance:a=>this.onSelectBalanceSymbol(a),onBack:()=>{this.walletModalStep="connect"},onSwitchAccount:()=>this.onSwitchAccount(null),onSelect:a=>this.connectWithWallet(a),onClose:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-cancelled",{detail:{reason:"user_cancelled"}}))}catch{}},onDismiss:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1},onCreditCard:this.config?.onramp?.enabled===!0&&this.config?.onrampDisabled!==!0?()=>this.startOnramp():void 0,creditCardLabel:this.config?.onramp?.creditCardLabel||"Pay with credit card",showCreditCard:this.config?.onramp?.enabled===!0&&this.config?.onrampDisabled!==!0,creditCardTooltip:(()=>{let i=this.config?.defaultItemIndex??0,o=Number(this.config?.items?.[i]?.priceUsd||0);return o>0&&o<5&&this.config?.onramp?.enabled===!0&&this.config?.onrampDisabled!==!0?`Note: Minimum card amount is $5. You will pay about $${(5-o).toFixed(2)} more.`:null})(),oisyReadyToPay:this.oisyReadyToPay,onOisyPay:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1,this.order()},theme:n})})()}
1777
+ ${(()=>{let e=this.pnp?.getEnabledWallets?.()||[],t=X(e),a=this.config?.theme?typeof this.config.theme=="string"?this.config.theme:this.config.theme.mode||"light":void 0;return Q({visible:!!(this.showWalletModal&&this.pnp),wallets:t,isConnecting:!1,step:this.walletModalStep,balances:this.walletModalStep==="balances"?this.walletBalances:[],balancesLoading:this.walletModalStep==="balances"?this.balancesLoading:!1,balancesError:this.walletModalStep==="balances"?this.balancesError:null,onSelectBalance:n=>this.onSelectBalanceSymbol(n),onBack:()=>{this.walletModalStep="connect"},onSwitchAccount:()=>this.onSwitchAccount(null),onSelect:n=>this.connectWithWallet(n),onClose:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-cancelled",{detail:{reason:"user_cancelled"}}))}catch{}},onDismiss:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1},onCreditCard:this.config?.onramp?.enabled===!0&&this.config?.onrampDisabled!==!0?()=>this.startOnramp():void 0,creditCardLabel:this.config?.onramp?.creditCardLabel||"Pay with credit card",showCreditCard:this.config?.onramp?.enabled===!0&&this.config?.onrampDisabled!==!0,creditCardTooltip:(()=>{let i=this.config?.defaultItemIndex??0,s=Number(this.config?.items?.[i]?.priceUsd||0);return s>0&&s<5&&this.config?.onramp?.enabled===!0&&this.config?.onrampDisabled!==!0?`Note: Minimum card amount is $5. You will pay about $${(5-s).toFixed(2)} more.`:null})(),oisyReadyToPay:this.oisyReadyToPay,onOisyPay:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1,this.order()},theme:a})})()}
1778
1778
 
1779
- ${(()=>{let e=this.config?.theme?typeof this.config.theme=="string"?this.config.theme:this.config.theme.mode||"light":void 0;return he`
1779
+ ${(()=>{let e=this.config?.theme?typeof this.config.theme=="string"?this.config.theme:this.config.theme.mode||"light":void 0;return ue`
1780
1780
  ${Z({visible:this.showBalanceModal,isLoading:this.balancesLoading,error:this.balancesError,balances:this.walletBalances,onSelect:t=>this.onSelectBalanceSymbol(t),onClose:()=>{this.showBalanceModal=!1},theme:e})}
1781
1781
 
1782
1782
  ${H({visible:this.showOnrampModal,url:this.onrampUrl||void 0,errorMessage:this.onrampErrorMessage||void 0,width:this.config?.onramp?.width,height:this.config?.onramp?.height,onClose:()=>{this.showOnrampModal=!1},onBack:()=>{this.showOnrampModal=!1,this.showWalletModal=!0},title:"Pay with credit card",theme:e})}
@@ -1785,7 +1785,7 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
1785
1785
  <a href="https://icpay.org" target="_blank" rel="noopener noreferrer">Powered by icpay</a>
1786
1786
  </div>
1787
1787
  </div>
1788
- `:he`<div class="icpay-card icpay-section">Loading...</div>`}};L.styles=[K,Tt`
1788
+ `:ue`<div class="icpay-card icpay-section">Loading...</div>`}};L.styles=[K,Tt`
1789
1789
  .menu { display: grid; gap: 8px; margin-bottom: 12px; }
1790
1790
  .item { background: var(--icpay-surface-alt); border: 2px solid var(--icpay-border); border-radius: 12px; padding: 16px; display:flex; justify-content: space-between; align-items:center; cursor: pointer; color: var(--icpay-text); font-weight: 600; }
1791
1791
  .item.selected { background: var(--icpay-primary); color: #111827; border-color: var(--icpay-primary); }
@@ -1816,9 +1816,9 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
1816
1816
  border-color: var(--icpay-error-border);
1817
1817
  color: var(--icpay-error-text);
1818
1818
  }
1819
- `],s([Ot({type:Object})],L.prototype,"config",2),s([F()],L.prototype,"selectedIndex",2),s([F()],L.prototype,"selectedSymbol",2),s([F()],L.prototype,"processing",2),s([F()],L.prototype,"errorMessage",2),s([F()],L.prototype,"errorSeverity",2),s([F()],L.prototype,"errorAction",2),s([F()],L.prototype,"walletConnected",2),s([F()],L.prototype,"pendingAction",2),s([F()],L.prototype,"showWalletModal",2),s([F()],L.prototype,"walletModalStep",2),s([F()],L.prototype,"oisyReadyToPay",2),s([F()],L.prototype,"lastWalletId",2),s([F()],L.prototype,"showOnrampModal",2),s([F()],L.prototype,"onrampUrl",2),s([F()],L.prototype,"onrampPaymentIntentId",2),s([F()],L.prototype,"onrampErrorMessage",2),s([F()],L.prototype,"showBalanceModal",2),s([F()],L.prototype,"balancesLoading",2),s([F()],L.prototype,"balancesError",2),s([F()],L.prototype,"walletBalances",2),L=s([Lt("icpay-coffee-shop")],L);import{LitElement as It,html as ye,css as Ut}from"lit";import{customElement as Nt,property as _t,state as N}from"lit/decorators.js";var He=typeof window<"u",oe=null;function Ce(r,l,e){r&&(e!==void 0?console.log(`[ICPay Widget] ${l}`,e):console.log(`[ICPay Widget] ${l}`))}var A=class extends It{constructor(){super(...arguments);this.selectedAmount=10;this.selectedSymbol=null;this.raised=0;this.processing=!1;this.succeeded=!1;this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.walletModalStep="connect";this.oisyReadyToPay=!1;this.lastWalletId=null;this.pnp=null;this.showOnrampModal=!1;this.onrampUrl=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.transakMessageHandlerBound=null;this.onrampPollTimer=null;this.onrampPollingActive=!1;this.onrampNotifyController=null;this.sdk=null;this.showBalanceModal=!1;this.balancesLoading=!1;this.balancesError=null;this.walletBalances=[];this.onSwitchAccount=async e=>{try{if(this.pnp)try{await this.pnp.disconnect()}catch{}this.walletConnected=!1,this.config={...this.config,actorProvider:void 0,connectedWallet:void 0},this.pendingAction="donate",this.showWalletModal=!0,this.requestUpdate();try{let t=Number(this.selectedAmount||0),n=this.selectedSymbol||"ICP";window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"donate",type:"sendUsd",amount:t,currency:n}}))}catch{}}catch{}};this.onSelectBalanceSymbol=async e=>{let t=(this.walletBalances||[]).find(a=>a?.tokenShortcode===e);if(t?.ledgerSymbol&&(this.selectedSymbol=t.ledgerSymbol),this.showBalanceModal=!1,this.showWalletModal=!1,q(this.lastWalletId)){let a=(this.walletBalances||[]).find(o=>o?.tokenShortcode===e),i=a?.chainId;X(i,{provider:this.pnp?.getEvmProvider?.()||this.config?.evmProvider,chainName:a?.chainName,rpcUrlPublic:a?.rpcUrlPublic,nativeSymbol:a?.ledgerSymbol,decimals:a?.decimals}).then(async()=>{try{let o=E(this.config),c=Number(this.selectedAmount||0);if(a?.x402Accepts&&!J(this.lastWalletId))try{await o.client.createPaymentX402Usd({usdAmount:c,tokenShortcode:a?.tokenShortcode,metadata:{...this.config?.metadata,icpay_network:"evm",icpay_ledger_id:a?.ledgerId,icpay_context:"donation:x402"},recipientAddress:(this.config?.recipientAddresses||{})?.evm||"0x0000000000000000000000000000000000000000",fiat_currency:this.config?.fiat_currency}),this.showBalanceModal=!1;return}catch(d){f(d,{onError:p=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:p,bubbles:!0})),v(p)&&(this.errorMessage=g(p),this.errorSeverity=b(p),this.errorAction=w(p))}})}await o.client.createPaymentUsd({usdAmount:c,tokenShortcode:a?.tokenShortcode,metadata:{...this.config?.metadata,icpay_network:"evm",icpay_ledger_id:a?.ledgerId},recipientAddress:(this.config?.recipientAddresses||{})?.evm||"0x0000000000000000000000000000000000000000"}).catch(d=>{throw d})}catch(o){f(o,{onError:c=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:c,bubbles:!0})),v(c)&&(this.errorMessage=g(c),this.errorSeverity=b(c),this.errorAction=w(c))}})}this.showBalanceModal=!1});return}let n=this.pendingAction;if(this.pendingAction=null,n==="donate")try{let a=(this.walletBalances||[]).find(h=>h?.tokenShortcode===e),i=E(this.config),o=Number(this.selectedAmount||0),d=String(a?.ledgerName||a?.chainName||"").toLowerCase().includes("sol"),p=this.config?.recipientAddresses||{},y=d&&p.sol||p.ic;if(d&&a?.x402Accepts)try{await i.client.createPaymentX402Usd({usdAmount:o,tokenShortcode:a?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:"sol",icpay_ledger_id:a?.ledgerId,icpay_context:"donation:x402"}},recipientAddress:y||"",fiat_currency:this.config?.fiat_currency});return}catch(h){f(h,{onError:u=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:u,bubbles:!0})),v(u)&&(this.errorMessage=g(u),this.errorSeverity=b(u),this.errorAction=w(u))}});return}await i.client.createPaymentUsd({usdAmount:o,tokenShortcode:a?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:"ic",icpay_ledger_id:a?.ledgerId}},recipientAddress:y||"0x0000000000000000000000000000000000000000"}).catch(h=>{throw h})}catch(a){f(a,{onError:i=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:i,bubbles:!0})),v(i)&&(this.errorMessage=g(i),this.errorSeverity=b(i),this.errorAction=w(i))}})}}}async tryAutoConnectPNP(){try{if(!this.config||this.config?.useOwnWallet)return;let e=localStorage.getItem("icpay:pnp");if(!e)return;let t=JSON.parse(e);if(!t?.provider||!t?.principal)return;oe||(oe=(await import("./wallet-select-VE5FSSFG.js")).WalletSelect);let n=I({...this.config?.plugNPlay||{}});try{if(typeof window<"u"){let{resolveDerivationOrigin:i}=await import("./origin-44ZEXSX4.js");n.derivationOrigin=this.config?.derivationOrigin||i()}}catch{}let a=new oe(n);this.walletConnected=!1,this.config={...this.config,connectedWallet:{owner:t.principal,principal:t.principal,connected:!1}}}catch{}}get amounts(){return this.config?.amountsUsd||[10,25,50,100,250,500]}async getOrCreatePnp(){if(this.pnp)return this.pnp;oe||(oe=(await import("./wallet-select-VE5FSSFG.js")).WalletSelect);let e=!!(this.config?.openOisyInNewTab||this.config?.plugNPlay?.openOisyInNewTab),t={...this.config?.plugNPlay||{}},n=this.config?.recipientAddresses;if(n&&(n.ic||n.evm||n.sol)){let i=[];n.ic&&i.push("ic"),n.evm&&i.push("evm"),n.sol&&i.push("sol"),i.length&&(t.chainTypes=i)}else this.config?.chainTypes&&(t.chainTypes=this.config.chainTypes);let a=e?I(t):t;try{if(typeof window<"u"){let{resolveDerivationOrigin:i}=await import("./origin-44ZEXSX4.js");a.derivationOrigin=this.config?.derivationOrigin||i()}}catch{}return this.pnp=new oe(a),this.pnp}async generateWalletConnectQr(e){try{let t=await this.getOrCreatePnp();return!t||typeof t.generateWalletConnectQr!="function"?null:await t.generateWalletConnectQr({onConnected:n=>{this.walletConnected=!0,this.lastWalletId="walletconnect";let a=x(this.pnp,n),i=this.pnp?.getEvmProvider?.(),o=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:a,actorProvider:(c,d)=>this.pnp.getActor({canisterId:c,idl:d,requiresSigning:!0,anon:!1}),...i?{evmProvider:i}:{},...o?{solanaProvider:o}:{}},this.sdk=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"walletconnect"}}))}catch{}try{e?.onConnected?.()}catch{}this.requestUpdate()}})}catch{return null}}async checkCoinbaseConnection(){try{return(await this.getOrCreatePnp())?.hasCoinbaseAccounts?.()??!1}catch{return!1}}async connectWallet(e){let t=await this.getOrCreatePnp();if(!t||!e)throw new Error("Wallet not available");let n=(e||"").toLowerCase(),a=await t.connect(n);if(!!!(a&&(a.connected===!0||a.principal||a.owner||t.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0,this.lastWalletId=n;let o=x(this.pnp,a),c=this.pnp?.getEvmProvider?.(),d=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:o,actorProvider:(p,y)=>this.pnp.getActor({canisterId:p,idl:y,requiresSigning:!0,anon:!1}),...c?{evmProvider:c}:{},...d?{solanaProvider:d}:{}},this.sdk=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:n}}))}catch{}this.requestUpdate()}connectedCallback(){if(super.connectedCallback(),!!He){Ce(this.config?.debug||!1,"Donation thermometer connected",{config:this.config}),this.config&&typeof this.config.defaultAmountUsd=="number"&&(this.selectedAmount=this.config.defaultAmountUsd),this.tryAutoConnectPNP();try{window.addEventListener("icpay-switch-account",this.onSwitchAccount)}catch{}try{window.addEventListener("icpay-sdk-transaction-created",(()=>{this.showWalletModal=!1,this.requestUpdate()}))}catch{}}}updated(e){if(e.has("config")&&this.pendingAction&&this.config?.actorProvider){let t=this.pendingAction;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}this.walletModalStep!=="balances"&&!this.oisyReadyToPay&&(this.pendingAction=null,setTimeout(()=>{t==="donate"&&this.donate()},0))}}selectAmount(e){this.selectedAmount=e}selectSymbol(e){this.selectedSymbol=e}get fillPercentage(){let e=Number(this.config?.goalUsd??1e3),t=e>0?e:1e3;return Math.min(this.raised/t*100,100)}resetPaymentFlow(){ee(this,{pendingAction:"donate"})}async donate(){if(He){this.resetPaymentFlow(),Ce(this.config?.debug||!1,"Donation started",{amount:this.selectedAmount,selectedSymbol:this.selectedSymbol,useOwnWallet:this.config.useOwnWallet});try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"donate",type:"sendUsd",amount:this.selectedAmount,currency:this.selectedSymbol||"ICP"}}))}catch{}this.processing=!0;try{if(this.config.useOwnWallet){if(!this.config.actorProvider){this.pendingAction="donate",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0}));return}}else if(!this.walletConnected){Ce(this.config?.debug||!1,"Connecting to wallet via Plug N Play");try{oe||(oe=(await import("./wallet-select-VE5FSSFG.js")).WalletSelect);let t=!!(this.config?.openOisyInNewTab||this.config?.plugNPlay?.openOisyInNewTab)?I({...this.config?.plugNPlay||{}}):{...this.config?.plugNPlay||{}};this.config?.chainTypes&&(t.chainTypes=this.config.chainTypes);try{if(typeof window<"u"){let{resolveDerivationOrigin:a}=await import("./origin-44ZEXSX4.js");t.derivationOrigin=this.config?.derivationOrigin||a()}}catch{}this.pnp=new oe(t);try{let a=await ae(this.pnp);if(a){this.walletConnected=!0;let i=x(this.pnp,{owner:a,principal:a,connected:!0}),o=this.pnp?.getEvmProvider?.();this.config={...this.config,connectedWallet:i,actorProvider:(c,d)=>this.pnp.getActor({canisterId:c,idl:d,requiresSigning:!0,anon:!1}),...o?{evmProvider:o}:{}},this.sdk=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"oisy"}}))}catch{}this.donate();return}}catch{}let n=this.pnp.getEnabledWallets();if(Ce(this.config?.debug||!1,"Available wallets",n),!n?.length)throw new Error("No wallets available");this.pendingAction="donate",this.showWalletModal=!0;return}catch(e){Ce(this.config?.debug||!1,"Wallet connection error:",e),this.errorMessage=e instanceof Error?e.message:"Wallet connection failed",this.errorSeverity="error";return}}this.showWalletModal=!0,await this.fetchAndShowBalances();return}catch(e){f(e,{onError:t=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:t,bubbles:!0})),v(t)&&(this.errorMessage=g(t),this.errorSeverity=b(t),this.errorAction=w(t))}});try{!this.config.useOwnWallet&&this.pnp&&(await this.pnp.disconnect?.(),this.walletConnected=!1,this.config={...this.config,actorProvider:void 0,connectedWallet:void 0})}catch{}}finally{this.processing=!1}}}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=e=>this.onTransakMessage(e);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(e){let t=e?.data,n=t?.event_id||t?.eventId||t?.id;if(!(!n||typeof n!="string")&&n==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;this.showOnrampModal=!1;let a=t?.data?.id||t?.id||t?.webhookData?.id||null;this.startOnrampPolling(a||void 0)}}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"createPaymentUsd",type:"onramp"}}))}catch{}this.showWalletModal=!1,setTimeout(()=>this.createOnrampIntent(),0)}async createOnrampIntent(){try{let t=await E(this.config).startOnrampUsd(this.selectedAmount,void 0,{context:"donation:onramp",onrampPayment:!0,onrampProvider:"coinbase"}),n=t?.metadata?.onramp?.url||t?.onramp?.url||t?.metadata?.icpay_onramp?.url||t?.paymentIntent?.metadata?.icpay?.onrampUrl||t?.metadata?.icpay?.onrampUrl||null,a=t?.metadata?.icpay_payment_intent_id||t?.metadata?.paymentIntentId||t?.paymentIntentId||null,i=t?.metadata?.icpay_onramp?.errorMessage||t?.metadata?.onramp?.errorMessage||t?.paymentIntent?.metadata?.icpay?.onrampError||t?.paymentIntent?.metadata?.icpay?.errorMessage||t?.metadata?.icpay?.onrampError||t?.metadata?.icpay?.errorMessage||null;if(this.onrampPaymentIntentId=a,n){this.onrampUrl=n,this.onrampErrorMessage=null;try{window.open(n,"icpay_onramp","noopener,noreferrer");try{window.dispatchEvent(new CustomEvent("icpay-onramp-opened",{detail:{url:n}}))}catch{}}catch{}this.startOnrampPolling()}else this.onrampUrl=null,this.onrampErrorMessage=i||"Failed to obtain onramp URL",this.showOnrampModal=!0}catch(e){this.onrampUrl=null,this.onrampErrorMessage=e?.message||"Failed to obtain onramp URL",this.showOnrampModal=!0}}startOnrampPolling(e){if(this.onrampPollTimer){try{clearInterval(this.onrampPollTimer)}catch{}this.onrampPollTimer=null}if(this.onrampNotifyController){try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null}let t=this.onrampPaymentIntentId;if(!t)return;let n=E(this.config),a=()=>{if(this.detachTransakMessageListener(),this.onrampNotifyController)try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null,this.onrampPollingActive=!1};try{window.addEventListener("icpay-sdk-transaction-completed",(()=>a()),{once:!0})}catch{}this.onrampPollingActive=!0,this.onrampNotifyController=n.notifyIntentUntilComplete(t,5e3,e),this.onrampPollTimer=1}getWalletId(e){return e&&(e.id||e.provider||e.key)||""}getWalletLabel(e){return e&&(e.label||e.name||e.title||e.id)||"Wallet"}getWalletIcon(e){return e&&(e.icon||e.logo||e.image)||null}connectWithWallet(e){if(this.pnp)try{if(!e)throw new Error("No wallet ID provided");this.lastWalletId=(e||"").toLowerCase(),this.pnp.connect(e).then(n=>{if(!!!(n&&(n.connected===!0||n.principal||n.owner||this.pnp?.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:e}}))}catch{}let i=x(this.pnp,n),o=this.pnp?.getEvmProvider?.(),c=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:i,actorProvider:(d,p)=>this.pnp.getActor({canisterId:d,idl:p,requiresSigning:!0,anon:!1}),...o?{evmProvider:o}:{},...c?{solanaProvider:c}:{}},this.sdk=null,this.walletModalStep="balances",this.showBalanceModal=!1,this.showWalletModal=!0,this.fetchAndShowBalances()}).catch(n=>{this.errorMessage=n instanceof Error?n.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-error",{detail:{message:this.errorMessage,code:"WALLET_CONNECT_ERROR"}}))}catch{}})}catch(t){this.errorMessage=t instanceof Error?t.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-error",{detail:{message:this.errorMessage,code:"WALLET_CONNECT_ERROR"}}))}catch{}}}async fetchAndShowBalances(){try{this.balancesLoading=!0,this.balancesError=null,this.walletModalStep="balances",this.showBalanceModal=!1;let e=E(this.config),{balances:t}=await Y({sdk:e,lastWalletId:this.lastWalletId,connectedWallet:this.config?.connectedWallet,amountUsd:Number(this.selectedAmount||0),fiatCurrency:this.config?.fiat_currency,chainShortcodes:this.config?.chainShortcodes,tokenShortcodes:this.config?.tokenShortcodes});this.walletBalances=t}catch(e){this.walletBalances=[],this.balancesError=e&&(e.message||String(e))||"Failed to load balances"}finally{this.balancesLoading=!1}}render(){return this.config?ye`
1819
+ `],c([Lt({type:Object})],L.prototype,"config",2),c([D()],L.prototype,"selectedIndex",2),c([D()],L.prototype,"selectedSymbol",2),c([D()],L.prototype,"processing",2),c([D()],L.prototype,"errorMessage",2),c([D()],L.prototype,"errorSeverity",2),c([D()],L.prototype,"errorAction",2),c([D()],L.prototype,"walletConnected",2),c([D()],L.prototype,"pendingAction",2),c([D()],L.prototype,"showWalletModal",2),c([D()],L.prototype,"walletModalStep",2),c([D()],L.prototype,"oisyReadyToPay",2),c([D()],L.prototype,"lastWalletId",2),c([D()],L.prototype,"showOnrampModal",2),c([D()],L.prototype,"onrampUrl",2),c([D()],L.prototype,"onrampPaymentIntentId",2),c([D()],L.prototype,"onrampErrorMessage",2),c([D()],L.prototype,"showBalanceModal",2),c([D()],L.prototype,"balancesLoading",2),c([D()],L.prototype,"balancesError",2),c([D()],L.prototype,"walletBalances",2),L=c([It("icpay-coffee-shop")],L);import{LitElement as Ut,html as ge,css as Ot}from"lit";import{customElement as Nt,property as _t,state as $}from"lit/decorators.js";var Ve=typeof window<"u",ce=null;function We(r,l,e){r&&(e!==void 0?console.log(`[ICPay Widget] ${l}`,e):console.log(`[ICPay Widget] ${l}`))}var P=class extends Ut{constructor(){super(...arguments);this.selectedAmount=10;this.selectedSymbol=null;this.raised=0;this.processing=!1;this.succeeded=!1;this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.walletModalStep="connect";this.oisyReadyToPay=!1;this.lastWalletId=null;this.pnp=null;this.showOnrampModal=!1;this.onrampUrl=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.transakMessageHandlerBound=null;this.onrampPollTimer=null;this.onrampPollingActive=!1;this.onrampNotifyController=null;this.sdk=null;this.showBalanceModal=!1;this.balancesLoading=!1;this.balancesError=null;this.walletBalances=[];this.onSwitchAccount=async e=>{try{if(this.pnp)try{await this.pnp.disconnect()}catch{}this.walletConnected=!1,this.config={...this.config,actorProvider:void 0,connectedWallet:void 0},this.pendingAction="donate",this.showWalletModal=!0,this.requestUpdate();try{let t=Number(this.selectedAmount||0),a=this.selectedSymbol||"ICP";window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"donate",type:"sendUsd",amount:t,currency:a}}))}catch{}}catch{}};this.onSelectBalanceSymbol=async e=>{let t=(this.walletBalances||[]).find(n=>n?.tokenShortcode===e);if(t?.ledgerSymbol&&(this.selectedSymbol=t.ledgerSymbol),this.showBalanceModal=!1,this.showWalletModal=!1,j(this.lastWalletId)){let n=(this.walletBalances||[]).find(s=>s?.tokenShortcode===e),i=n?.chainId;V(i,{provider:this.pnp?.getEvmProvider?.()||this.config?.evmProvider,chainName:n?.chainName,rpcUrlPublic:n?.rpcUrlPublic,nativeSymbol:n?.ledgerSymbol,decimals:n?.decimals}).then(async()=>{try{let s=E(this.config),o=Number(this.selectedAmount||0);if(n?.x402Accepts&&!J(this.lastWalletId))try{await s.client.createPaymentX402Usd({usdAmount:o,tokenShortcode:n?.tokenShortcode,metadata:{...this.config?.metadata,icpay_network:"evm",icpay_ledger_id:n?.ledgerId,icpay_context:"donation:x402"},recipientAddress:(this.config?.recipientAddresses||{})?.evm||"0x0000000000000000000000000000000000000000",fiat_currency:this.config?.fiat_currency}),this.showBalanceModal=!1;return}catch(d){f(d,{onError:p=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:p,bubbles:!0})),w(p)&&(this.errorMessage=m(p),this.errorSeverity=v(p),this.errorAction=b(p))}})}await s.client.createPaymentUsd({usdAmount:o,tokenShortcode:n?.tokenShortcode,metadata:{...this.config?.metadata,icpay_network:"evm",icpay_ledger_id:n?.ledgerId},recipientAddress:(this.config?.recipientAddresses||{})?.evm||"0x0000000000000000000000000000000000000000"}).catch(d=>{throw d})}catch(s){f(s,{onError:o=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:o,bubbles:!0})),w(o)&&(this.errorMessage=m(o),this.errorSeverity=v(o),this.errorAction=b(o))}})}this.showBalanceModal=!1});return}let a=this.pendingAction;if(this.pendingAction=null,a==="donate")try{let n=(this.walletBalances||[]).find(h=>h?.tokenShortcode===e),i=E(this.config),s=Number(this.selectedAmount||0),d=String(n?.ledgerName||n?.chainName||"").toLowerCase().includes("sol"),p=this.config?.recipientAddresses||{},y=d&&p.sol||p.ic;if(d&&n?.x402Accepts)try{await i.client.createPaymentX402Usd({usdAmount:s,tokenShortcode:n?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:"sol",icpay_ledger_id:n?.ledgerId,icpay_context:"donation:x402"}},recipientAddress:y||"",fiat_currency:this.config?.fiat_currency});return}catch(h){f(h,{onError:u=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:u,bubbles:!0})),w(u)&&(this.errorMessage=m(u),this.errorSeverity=v(u),this.errorAction=b(u))}});return}await i.client.createPaymentUsd({usdAmount:s,tokenShortcode:n?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:"ic",icpay_ledger_id:n?.ledgerId}},recipientAddress:y||"0x0000000000000000000000000000000000000000"}).catch(h=>{throw h})}catch(n){f(n,{onError:i=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:i,bubbles:!0})),w(i)&&(this.errorMessage=m(i),this.errorSeverity=v(i),this.errorAction=b(i))}})}}}async tryAutoConnectPNP(){try{if(!this.config||this.config?.useOwnWallet)return;let e=localStorage.getItem("icpay:pnp");if(!e)return;let t=JSON.parse(e);if(!t?.provider||!t?.principal)return;ce||(ce=(await import("./wallet-select-3A5Z7KZJ.js")).WalletSelect);let a=O({...this.config?.plugNPlay||{}});try{if(typeof window<"u"){let{resolveDerivationOrigin:i}=await import("./origin-44ZEXSX4.js");a.derivationOrigin=this.config?.derivationOrigin||i()}}catch{}let n=new ce(a);this.walletConnected=!1,this.config={...this.config,connectedWallet:{owner:t.principal,principal:t.principal,connected:!1}}}catch{}}get amounts(){return this.config?.amountsUsd||[10,25,50,100,250,500]}async getOrCreatePnp(){if(this.pnp)return this.pnp;ce||(ce=(await import("./wallet-select-3A5Z7KZJ.js")).WalletSelect);let e=!!(this.config?.openOisyInNewTab||this.config?.plugNPlay?.openOisyInNewTab),t={...this.config?.plugNPlay||{}},a=this.config?.recipientAddresses;if(a&&(a.ic||a.evm||a.sol)){let i=[];a.ic&&i.push("ic"),a.evm&&i.push("evm"),a.sol&&i.push("sol"),i.length&&(t.chainTypes=i)}else this.config?.chainTypes&&(t.chainTypes=this.config.chainTypes);let n=e?O(t):t;try{if(typeof window<"u"){let{resolveDerivationOrigin:i}=await import("./origin-44ZEXSX4.js");n.derivationOrigin=this.config?.derivationOrigin||i()}}catch{}return this.pnp=new ce(n),this.pnp}async generateWalletConnectQr(e){try{let t=await this.getOrCreatePnp();return!t||typeof t.generateWalletConnectQr!="function"?null:await t.generateWalletConnectQr({onConnected:a=>{this.walletConnected=!0,this.lastWalletId="walletconnect";let n=x(this.pnp,a),i=this.pnp?.getEvmProvider?.(),s=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:n,actorProvider:(o,d)=>this.pnp.getActor({canisterId:o,idl:d,requiresSigning:!0,anon:!1}),...i?{evmProvider:i}:{},...s?{solanaProvider:s}:{}},this.sdk=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"walletconnect"}}))}catch{}try{e?.onConnected?.()}catch{}this.requestUpdate()}})}catch{return null}}async checkCoinbaseConnection(){try{return(await this.getOrCreatePnp())?.hasCoinbaseAccounts?.()??!1}catch{return!1}}async connectWallet(e){let t=await this.getOrCreatePnp();if(!t||!e)throw new Error("Wallet not available");let a=(e||"").toLowerCase(),n=await t.connect(a);if(!!!(n&&(n.connected===!0||n.principal||n.owner||t.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0,this.lastWalletId=a;let s=x(this.pnp,n),o=this.pnp?.getEvmProvider?.(),d=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:s,actorProvider:(p,y)=>this.pnp.getActor({canisterId:p,idl:y,requiresSigning:!0,anon:!1}),...o?{evmProvider:o}:{},...d?{solanaProvider:d}:{}},this.sdk=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:a}}))}catch{}this.requestUpdate()}connectedCallback(){if(super.connectedCallback(),!!Ve){We(this.config?.debug||!1,"Donation thermometer connected",{config:this.config}),this.config&&typeof this.config.defaultAmountUsd=="number"&&(this.selectedAmount=this.config.defaultAmountUsd),this.tryAutoConnectPNP();try{window.addEventListener("icpay-switch-account",this.onSwitchAccount)}catch{}try{window.addEventListener("icpay-sdk-transaction-created",(()=>{this.showWalletModal=!1,this.requestUpdate()}))}catch{}}}updated(e){if(e.has("config")&&this.pendingAction&&this.config?.actorProvider){let t=this.pendingAction;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}this.walletModalStep!=="balances"&&!this.oisyReadyToPay&&(this.pendingAction=null,setTimeout(()=>{t==="donate"&&this.donate()},0))}}selectAmount(e){this.selectedAmount=e}selectSymbol(e){this.selectedSymbol=e}get fillPercentage(){let e=Number(this.config?.goalUsd??1e3),t=e>0?e:1e3;return Math.min(this.raised/t*100,100)}resetPaymentFlow(){ee(this,{pendingAction:"donate"})}async donate(){if(Ve){this.resetPaymentFlow(),We(this.config?.debug||!1,"Donation started",{amount:this.selectedAmount,selectedSymbol:this.selectedSymbol,useOwnWallet:this.config.useOwnWallet});try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"donate",type:"sendUsd",amount:this.selectedAmount,currency:this.selectedSymbol||"ICP"}}))}catch{}this.processing=!0;try{if(this.config.useOwnWallet){if(!this.config.actorProvider){this.pendingAction="donate",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0}));return}}else if(!this.walletConnected){We(this.config?.debug||!1,"Connecting to wallet via Plug N Play");try{ce||(ce=(await import("./wallet-select-3A5Z7KZJ.js")).WalletSelect);let t=!!(this.config?.openOisyInNewTab||this.config?.plugNPlay?.openOisyInNewTab)?O({...this.config?.plugNPlay||{}}):{...this.config?.plugNPlay||{}};this.config?.chainTypes&&(t.chainTypes=this.config.chainTypes);try{if(typeof window<"u"){let{resolveDerivationOrigin:n}=await import("./origin-44ZEXSX4.js");t.derivationOrigin=this.config?.derivationOrigin||n()}}catch{}this.pnp=new ce(t);try{let n=await ie(this.pnp);if(n){this.walletConnected=!0;let i=x(this.pnp,{owner:n,principal:n,connected:!0}),s=this.pnp?.getEvmProvider?.();this.config={...this.config,connectedWallet:i,actorProvider:(o,d)=>this.pnp.getActor({canisterId:o,idl:d,requiresSigning:!0,anon:!1}),...s?{evmProvider:s}:{}},this.sdk=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"oisy"}}))}catch{}this.donate();return}}catch{}let a=this.pnp.getEnabledWallets();if(We(this.config?.debug||!1,"Available wallets",a),!a?.length)throw new Error("No wallets available");this.pendingAction="donate",this.showWalletModal=!0;return}catch(e){We(this.config?.debug||!1,"Wallet connection error:",e),this.errorMessage=e instanceof Error?e.message:"Wallet connection failed",this.errorSeverity="error";return}}this.showWalletModal=!0,await this.fetchAndShowBalances();return}catch(e){f(e,{onError:t=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:t,bubbles:!0})),w(t)&&(this.errorMessage=m(t),this.errorSeverity=v(t),this.errorAction=b(t))}});try{!this.config.useOwnWallet&&this.pnp&&(await this.pnp.disconnect?.(),this.walletConnected=!1,this.config={...this.config,actorProvider:void 0,connectedWallet:void 0})}catch{}}finally{this.processing=!1}}}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=e=>this.onTransakMessage(e);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(e){let t=e?.data,a=t?.event_id||t?.eventId||t?.id;if(!(!a||typeof a!="string")&&a==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;this.showOnrampModal=!1;let n=t?.data?.id||t?.id||t?.webhookData?.id||null;this.startOnrampPolling(n||void 0)}}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"createPaymentUsd",type:"onramp"}}))}catch{}this.showWalletModal=!1,setTimeout(()=>this.createOnrampIntent(),0)}async createOnrampIntent(){try{let t=await E(this.config).startOnrampUsd(this.selectedAmount,void 0,{context:"donation:onramp",onrampPayment:!0,onrampProvider:"coinbase"}),a=t?.metadata?.onramp?.url||t?.onramp?.url||t?.metadata?.icpay_onramp?.url||t?.paymentIntent?.metadata?.icpay?.onrampUrl||t?.metadata?.icpay?.onrampUrl||null,n=t?.metadata?.icpay_payment_intent_id||t?.metadata?.paymentIntentId||t?.paymentIntentId||null,i=t?.metadata?.icpay_onramp?.errorMessage||t?.metadata?.onramp?.errorMessage||t?.paymentIntent?.metadata?.icpay?.onrampError||t?.paymentIntent?.metadata?.icpay?.errorMessage||t?.metadata?.icpay?.onrampError||t?.metadata?.icpay?.errorMessage||null;if(this.onrampPaymentIntentId=n,a){this.onrampUrl=a,this.onrampErrorMessage=null;try{window.open(a,"icpay_onramp","noopener,noreferrer");try{window.dispatchEvent(new CustomEvent("icpay-onramp-opened",{detail:{url:a}}))}catch{}}catch{}this.startOnrampPolling()}else this.onrampUrl=null,this.onrampErrorMessage=i||"Failed to obtain onramp URL",this.showOnrampModal=!0}catch(e){this.onrampUrl=null,this.onrampErrorMessage=e?.message||"Failed to obtain onramp URL",this.showOnrampModal=!0}}startOnrampPolling(e){if(this.onrampPollTimer){try{clearInterval(this.onrampPollTimer)}catch{}this.onrampPollTimer=null}if(this.onrampNotifyController){try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null}let t=this.onrampPaymentIntentId;if(!t)return;let a=E(this.config),n=()=>{if(this.detachTransakMessageListener(),this.onrampNotifyController)try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null,this.onrampPollingActive=!1};try{window.addEventListener("icpay-sdk-transaction-completed",(()=>n()),{once:!0})}catch{}this.onrampPollingActive=!0,this.onrampNotifyController=a.notifyIntentUntilComplete(t,5e3,e),this.onrampPollTimer=1}getWalletId(e){return e&&(e.id||e.provider||e.key)||""}getWalletLabel(e){return e&&(e.label||e.name||e.title||e.id)||"Wallet"}getWalletIcon(e){return e&&(e.icon||e.logo||e.image)||null}connectWithWallet(e){if(this.pnp)try{if(!e)throw new Error("No wallet ID provided");this.lastWalletId=(e||"").toLowerCase(),this.pnp.connect(e).then(a=>{if(!!!(a&&(a.connected===!0||a.principal||a.owner||this.pnp?.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:e}}))}catch{}let i=x(this.pnp,a),s=this.pnp?.getEvmProvider?.(),o=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:i,actorProvider:(d,p)=>this.pnp.getActor({canisterId:d,idl:p,requiresSigning:!0,anon:!1}),...s?{evmProvider:s}:{},...o?{solanaProvider:o}:{}},this.sdk=null,this.walletModalStep="balances",this.showBalanceModal=!1,this.showWalletModal=!0,this.fetchAndShowBalances()}).catch(a=>{this.errorMessage=a instanceof Error?a.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-error",{detail:{message:this.errorMessage,code:"WALLET_CONNECT_ERROR"}}))}catch{}})}catch(t){this.errorMessage=t instanceof Error?t.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-error",{detail:{message:this.errorMessage,code:"WALLET_CONNECT_ERROR"}}))}catch{}}}async fetchAndShowBalances(){try{this.balancesLoading=!0,this.balancesError=null,this.walletModalStep="balances",this.showBalanceModal=!1;let e=E(this.config),{balances:t}=await Y({sdk:e,lastWalletId:this.lastWalletId,connectedWallet:this.config?.connectedWallet,amountUsd:Number(this.selectedAmount||0),fiatCurrency:this.config?.fiat_currency,chainShortcodes:this.config?.chainShortcodes,tokenShortcodes:this.config?.tokenShortcodes});this.walletBalances=t}catch(e){this.walletBalances=[],this.balancesError=e&&(e.message||String(e))||"Failed to load balances"}finally{this.balancesLoading=!1}}render(){return this.config?ge`
1820
1820
  <div class="icpay-card icpay-section icpay-widget-base" style="text-align:center;">
1821
- ${this.config?.progressBar?.enabled!==!1?ye`
1821
+ ${this.config?.progressBar?.enabled!==!1?ge`
1822
1822
  <icpay-progress-bar
1823
1823
  .debug=${!!this.config?.debug}
1824
1824
  .theme=${this.config?.theme}
@@ -1830,7 +1830,7 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
1830
1830
  <div class="total">$${Number(this.raised).toFixed(0)} / $${Number(this.config?.goalUsd??0).toFixed(2)}</div>
1831
1831
 
1832
1832
  <div class="amounts">
1833
- ${this.amounts.map(e=>ye`<div class="chip ${this.selectedAmount===e?"selected":""}" @click=${()=>this.selectAmount(e)}>$${e}</div>`)}
1833
+ ${this.amounts.map(e=>ge`<div class="chip ${this.selectedAmount===e?"selected":""}" @click=${()=>this.selectAmount(e)}>$${e}</div>`)}
1834
1834
  </div>
1835
1835
 
1836
1836
 
@@ -1841,19 +1841,19 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
1841
1841
  ${this.succeeded&&this.config?.disableAfterSuccess?"Donated":this.processing?"Processing\u2026":(this.config?.buttonLabel||"Donate {amount} with crypto").replace("{amount}",`${this.selectedAmount}`).replace("{symbol}",this.selectedSymbol||"ICP")}
1842
1842
  </button>
1843
1843
 
1844
- ${this.errorMessage?ye`
1844
+ ${this.errorMessage?ge`
1845
1845
  <div class="error-message ${this.errorSeverity}" style="margin-top: 12px; padding: 8px 12px; border-radius: 6px; font-size: 14px; text-align: center;">
1846
1846
  ${this.errorMessage}
1847
- ${this.errorAction?ye`
1847
+ ${this.errorAction?ge`
1848
1848
  <button style="margin-left: 8px; padding: 4px 8px; background: transparent; border: 1px solid currentColor; border-radius: 4px; font-size: 12px; cursor: pointer;">
1849
1849
  ${this.errorAction}
1850
1850
  </button>
1851
1851
  `:""}
1852
1852
  </div>
1853
1853
  `:""}
1854
- ${(()=>{let e=this.pnp?.getEnabledWallets?.()||[],t=V(e),n=this.config?.theme?typeof this.config.theme=="string"?this.config.theme:this.config.theme.mode||"light":void 0;return Q({visible:!!(this.showWalletModal&&this.pnp),wallets:t,isConnecting:!1,step:this.walletModalStep,balances:this.walletModalStep==="balances"?this.walletBalances:[],balancesLoading:this.walletModalStep==="balances"?this.balancesLoading:!1,balancesError:this.walletModalStep==="balances"?this.balancesError:null,onSelectBalance:a=>this.onSelectBalanceSymbol(a),onBack:()=>{this.walletModalStep="connect"},onSwitchAccount:()=>this.onSwitchAccount(null),onSelect:a=>this.connectWithWallet(a),onClose:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-cancelled",{detail:{reason:"user_cancelled"}}))}catch{}},onDismiss:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1},onCreditCard:this.config?.onramp?.enabled===!0&&this.config?.onrampDisabled!==!0?()=>this.startOnramp():void 0,creditCardLabel:this.config?.onramp?.creditCardLabel||"Pay with credit card",showCreditCard:this.config?.onramp?.enabled===!0&&this.config?.onrampDisabled!==!0,creditCardTooltip:(()=>{let i=Number(this.selectedAmount||this.config?.defaultAmountUsd||0);return i>0&&i<5&&this.config?.onramp?.enabled===!0&&this.config?.onrampDisabled!==!0?`Note: Minimum card amount is $5. You will pay about $${(5-i).toFixed(2)} more.`:null})(),oisyReadyToPay:this.oisyReadyToPay,onOisyPay:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1,this.donate()},theme:n})})()}
1854
+ ${(()=>{let e=this.pnp?.getEnabledWallets?.()||[],t=X(e),a=this.config?.theme?typeof this.config.theme=="string"?this.config.theme:this.config.theme.mode||"light":void 0;return Q({visible:!!(this.showWalletModal&&this.pnp),wallets:t,isConnecting:!1,step:this.walletModalStep,balances:this.walletModalStep==="balances"?this.walletBalances:[],balancesLoading:this.walletModalStep==="balances"?this.balancesLoading:!1,balancesError:this.walletModalStep==="balances"?this.balancesError:null,onSelectBalance:n=>this.onSelectBalanceSymbol(n),onBack:()=>{this.walletModalStep="connect"},onSwitchAccount:()=>this.onSwitchAccount(null),onSelect:n=>this.connectWithWallet(n),onClose:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-cancelled",{detail:{reason:"user_cancelled"}}))}catch{}},onDismiss:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1},onCreditCard:this.config?.onramp?.enabled===!0&&this.config?.onrampDisabled!==!0?()=>this.startOnramp():void 0,creditCardLabel:this.config?.onramp?.creditCardLabel||"Pay with credit card",showCreditCard:this.config?.onramp?.enabled===!0&&this.config?.onrampDisabled!==!0,creditCardTooltip:(()=>{let i=Number(this.selectedAmount||this.config?.defaultAmountUsd||0);return i>0&&i<5&&this.config?.onramp?.enabled===!0&&this.config?.onrampDisabled!==!0?`Note: Minimum card amount is $5. You will pay about $${(5-i).toFixed(2)} more.`:null})(),oisyReadyToPay:this.oisyReadyToPay,onOisyPay:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1,this.donate()},theme:a})})()}
1855
1855
 
1856
- ${(()=>{let e=this.config?.theme?typeof this.config.theme=="string"?this.config.theme:this.config.theme.mode||"light":void 0;return ye`
1856
+ ${(()=>{let e=this.config?.theme?typeof this.config.theme=="string"?this.config.theme:this.config.theme.mode||"light":void 0;return ge`
1857
1857
  ${Z({visible:this.showBalanceModal,isLoading:this.balancesLoading,error:this.balancesError,balances:this.walletBalances,onSelect:t=>this.onSelectBalanceSymbol(t),onClose:()=>{this.showBalanceModal=!1},theme:e})}
1858
1858
 
1859
1859
  ${H({visible:this.showOnrampModal,url:this.onrampUrl||void 0,errorMessage:this.onrampErrorMessage||void 0,width:this.config?.onramp?.width,height:this.config?.onramp?.height,onClose:()=>{this.showOnrampModal=!1},onBack:()=>{this.showOnrampModal=!1,this.showWalletModal=!0},title:"Pay with credit card",theme:e})}
@@ -1862,7 +1862,7 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
1862
1862
  <a href="https://icpay.org" target="_blank" rel="noopener noreferrer">Powered by icpay</a>
1863
1863
  </div>
1864
1864
  </div>
1865
- `:ye`<div class="icpay-card icpay-section">Loading...</div>`}};A.styles=[K,Ut`
1865
+ `:ge`<div class="icpay-card icpay-section">Loading...</div>`}};P.styles=[K,Ot`
1866
1866
  .thermo { width: 60px; height: 200px; background: var(--icpay-surface-alt); border: 3px solid #6b7280; border-radius: 30px; margin: 0 auto 12px; position: relative; overflow: hidden; }
1867
1867
  .fill { position: absolute; bottom: 0; left: 0; right: 0; background: linear-gradient(135deg, #d1d5db 0%, #9ca3af 100%); transition: height 0.8s ease; height: 0%; border-radius: 0 0 27px 27px; }
1868
1868
  .amounts { display: grid; grid-template-columns: repeat(3,1fr); gap: 8px; margin: 12px 0; }
@@ -1894,7 +1894,7 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
1894
1894
  border-color: var(--icpay-error-border);
1895
1895
  color: var(--icpay-error-text);
1896
1896
  }
1897
- `],s([_t({type:Object})],A.prototype,"config",2),s([N()],A.prototype,"selectedAmount",2),s([N()],A.prototype,"selectedSymbol",2),s([N()],A.prototype,"raised",2),s([N()],A.prototype,"processing",2),s([N()],A.prototype,"succeeded",2),s([N()],A.prototype,"errorMessage",2),s([N()],A.prototype,"errorSeverity",2),s([N()],A.prototype,"errorAction",2),s([N()],A.prototype,"walletConnected",2),s([N()],A.prototype,"pendingAction",2),s([N()],A.prototype,"showWalletModal",2),s([N()],A.prototype,"walletModalStep",2),s([N()],A.prototype,"oisyReadyToPay",2),s([N()],A.prototype,"lastWalletId",2),s([N()],A.prototype,"showOnrampModal",2),s([N()],A.prototype,"onrampUrl",2),s([N()],A.prototype,"onrampPaymentIntentId",2),s([N()],A.prototype,"onrampErrorMessage",2),s([N()],A.prototype,"showBalanceModal",2),s([N()],A.prototype,"balancesLoading",2),s([N()],A.prototype,"balancesError",2),s([N()],A.prototype,"walletBalances",2),A=s([Nt("icpay-donation-thermometer")],A);import{LitElement as Rt,html as ue,css as Ft}from"lit";import{customElement as Dt,property as zt,state as O}from"lit/decorators.js";import{html as Ie}from"lit";function $t(r){if(r==="light"||r==="dark")return r;if(typeof document>"u")return"light";let l=document.documentElement.getAttribute("data-icpay-theme");if(l==="light"||l==="dark")return l;let e=document.documentElement.getAttribute("data-theme");return e==="light"||e==="dark"?e:"light"}function Ve(r){if(!r.visible)return null;let l=r.providers||[],e=$t(r.theme);return Ie`
1897
+ `],c([_t({type:Object})],P.prototype,"config",2),c([$()],P.prototype,"selectedAmount",2),c([$()],P.prototype,"selectedSymbol",2),c([$()],P.prototype,"raised",2),c([$()],P.prototype,"processing",2),c([$()],P.prototype,"succeeded",2),c([$()],P.prototype,"errorMessage",2),c([$()],P.prototype,"errorSeverity",2),c([$()],P.prototype,"errorAction",2),c([$()],P.prototype,"walletConnected",2),c([$()],P.prototype,"pendingAction",2),c([$()],P.prototype,"showWalletModal",2),c([$()],P.prototype,"walletModalStep",2),c([$()],P.prototype,"oisyReadyToPay",2),c([$()],P.prototype,"lastWalletId",2),c([$()],P.prototype,"showOnrampModal",2),c([$()],P.prototype,"onrampUrl",2),c([$()],P.prototype,"onrampPaymentIntentId",2),c([$()],P.prototype,"onrampErrorMessage",2),c([$()],P.prototype,"showBalanceModal",2),c([$()],P.prototype,"balancesLoading",2),c([$()],P.prototype,"balancesError",2),c([$()],P.prototype,"walletBalances",2),P=c([Nt("icpay-donation-thermometer")],P);import{LitElement as Rt,html as me,css as Ft}from"lit";import{customElement as Dt,property as zt,state as U}from"lit/decorators.js";import{html as Ue}from"lit";function $t(r){if(r==="light"||r==="dark")return r;if(typeof document>"u")return"light";let l=document.documentElement.getAttribute("data-icpay-theme");if(l==="light"||l==="dark")return l;let e=document.documentElement.getAttribute("data-theme");return e==="light"||e==="dark"?e:"light"}function Ye(r){if(!r.visible)return null;let l=r.providers||[],e=$t(r.theme);return Ue`
1898
1898
  <style>
1899
1899
  /* Theme-aware color variables - Light mode defaults */
1900
1900
  .icpay-onramp-overlay {
@@ -1988,21 +1988,21 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
1988
1988
  <button @click=${r.onClose} style="position:absolute;right:12px;top:12px;background:transparent;border:none;color:var(--icpay-foreground);cursor:pointer;font-size:20px;opacity:0.8">×</button>
1989
1989
  <div style="color:var(--icpay-foreground);font-weight:600;font-size:16px;margin-bottom:12px">${r.title||"Choose a provider"}</div>
1990
1990
  <div style="display:flex;flex-direction:column;gap:10px">
1991
- ${l.map(t=>Ie`
1991
+ ${l.map(t=>Ue`
1992
1992
  <button
1993
1993
  class="icpay-onramp-provider-btn"
1994
1994
  @click=${()=>r.onSelect(t.slug)}
1995
1995
  >
1996
- ${t.logoUrl?Ie`<img src="${t.logoUrl}" style="width:24px;height:24px;border-radius:4px" />`:Ie`<div style="width:24px;height:24px;border-radius:4px;background:var(--icpay-secondary)"></div>`}
1996
+ ${t.logoUrl?Ue`<img src="${t.logoUrl}" style="width:24px;height:24px;border-radius:4px" />`:Ue`<div style="width:24px;height:24px;border-radius:4px;background:var(--icpay-secondary)"></div>`}
1997
1997
  <span style="font-size:14px">${t.name}</span>
1998
1998
  </button>
1999
1999
  `)}
2000
2000
  </div>
2001
2001
  </div>
2002
2002
  </div>
2003
- `}var Bt=typeof window<"u";async function Xe(r,l,e,t=!1){if(!Bt||!e||!l)return null;let a=`${(r||"https://api.icpay.org").replace(/\/$/,"")}/sdk/public/payments/intents/${encodeURIComponent(e)}`;try{t&&console.log("[ICPay Widget] Fetching payment intent",{intentId:e,url:a.replace(l,"***")});let i=await fetch(a,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`}});if(!i.ok)return t&&console.log("[ICPay Widget] Fetch payment intent failed",i.status,await i.text()),null;let o=await i.json();return o?.paymentIntent?.id?o:null}catch(i){return t&&console.log("[ICPay Widget] Fetch payment intent error",i),null}}function Ye(r){if(!r)return!1;let l=String(r).toLowerCase();return l==="succeeded"||l==="completed"}var Ge=typeof window<"u",ce=null;function R(r,l,e){r&&(e!==void 0?console.log(`[ICPay Widget] ${l}`,e):console.log(`[ICPay Widget] ${l}`))}var k=class extends Rt{constructor(){super(...arguments);this.selectedSymbol=null;this.processing=!1;this.succeeded=!1;this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.walletModalStep="connect";this.showOnrampModal=!1;this.onrampUrl=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.showProviderPicker=!1;this.selectedOnrampProvider=null;this.oisyReadyToPay=!1;this.oisySignerPreopened=!1;this.skipDisconnectOnce=!1;this.lastWalletId=null;this.showBalanceModal=!1;this.balancesLoading=!1;this.balancesError=null;this.walletBalances=[];this.loadedPaymentIntent=null;this.paymentIntentLoading=!1;this.onrampPollTimer=null;this.pnp=null;this.oisyConnectRetriedNewTab=!1;this.sdk=null;this.onrampPollingActive=!1;this.onrampNotifyController=null;this.onTransactionCompleted=null;this.onSwitchAccount=async e=>{try{if(this.pnp)try{await this.pnp.disconnect()}catch{}this.walletConnected=!1,this.config={...this.config,actorProvider:void 0,connectedWallet:void 0},this.pendingAction="pay",this.walletModalStep="connect",this.showWalletModal=!0,this.oisyReadyToPay=!1,this.lastWalletId=null,this.requestUpdate();try{let t=Number(this.config?.amountUsd||0),n=this.selectedSymbol||"ICP";window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"pay",type:"sendUsd",amount:t,currency:n}}))}catch{}}catch{}};this.onSelectBalanceSymbol=async e=>{let t=(this.walletBalances||[]).find(a=>a?.tokenShortcode===e);if(t?.ledgerSymbol&&(this.selectedSymbol=t.ledgerSymbol),this.showBalanceModal=!1,this.showWalletModal=!1,q(this.lastWalletId)){R(this.config?.debug||!1,"EVM selection made",{selectedSymbol:this.selectedSymbol,selPresent:!!t,selSnapshot:t?{ledgerId:t?.ledgerId,ledgerSymbol:t?.ledgerSymbol,ledgerName:t?.ledgerName,chainUuid:t?.chainUuid,chainId:t?.chainId,chainName:t?.chainName,x402Accepts:t?.x402Accepts,requiredAmount:t?.requiredAmount,hasSufficientBalance:t?.hasSufficientBalance}:null});let a=t?.chainId;X(a,{provider:this.pnp?.getEvmProvider?.()||this.config?.evmProvider,chainName:t?.chainName,rpcUrlPublic:t?.rpcUrlPublic,nativeSymbol:t?.ledgerSymbol,decimals:t?.decimals}).then(async()=>{try{let i=this.getSdk(),o=Number(this.config?.amountUsd??0),c=t?.ledgerSymbol,d=J(this.lastWalletId),p=!!(t&&t.x402Accepts)&&!d;if(R(this.config?.debug||!1,"EVM post-ensure chain snapshot",{targetChain:a,amountUsd:o,symbolNow:c,tryX402:p,skipX402BaseIos:d,x402Accepts:t?.x402Accepts}),p)try{let h=this.config?.recipientAddresses?.evm||"0x0000000000000000000000000000000000000000";R(this.config?.debug||!1,"Using recipientAddress (x402)",{recipientAddress:h});let u={...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:"evm",icpay_ledger_id:t?.ledgerId,icpay_context:"pay-button:x402"}};R(this.config?.debug||!1,"Attempting X402 flow (EVM selection)",{amountUsd:o,tokenShortcode:t?.tokenShortcode,x402Accepts:t?.x402Accepts}),await i.client.createPaymentX402Usd({usdAmount:o,tokenShortcode:t?.tokenShortcode,metadata:u,recipientAddress:h,fiat_currency:this.config?.fiat_currency});return}catch(h){R(this.config?.debug||!1,"X402 payment failed (EVM selection), falling back",{message:h?.message,code:h?.code,data:h?.details||h?.data})}else R(this.config?.debug||!1,"Skipping X402 path",{reason:t?t.x402Accepts?"unknown":"x402Accepts false":"no selection",selPresent:!!t,x402Accepts:t?.x402Accepts});R(this.config?.debug||!1,"Falling back to normal EVM wallet flow",{amountUsd:o,tokenShortcode:t?.tokenShortcode});let y=this.config?.recipientAddresses?.evm||"0x0000000000000000000000000000000000000000";R(this.config?.debug||!1,"Using recipientAddress (normal)",{recipientAddress:y}),await i.client.createPaymentUsd({usdAmount:o,tokenShortcode:t?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:"evm",icpay_ledger_id:t?.ledgerId}},recipientAddress:y}).catch(h=>{throw h})}catch(i){f(i,{onError:o=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:o,bubbles:!0})),v(o)&&(this.errorMessage=g(o),this.errorSeverity=b(o),this.errorAction=w(o))}})}});return}let n=this.pendingAction;if(this.pendingAction=null,n==="pay")try{let a=(this.walletBalances||[]).find(u=>u?.tokenShortcode===e),i=this.getSdk(),o=Number(this.config?.amountUsd??0);R(this.config?.debug||!1,"IC selection made",{selectedSymbol:this.selectedSymbol,selPresent:!!a,selSnapshot:a?{ledgerId:a?.ledgerId,ledgerSymbol:a?.ledgerSymbol,ledgerName:a?.ledgerName,requiredAmount:a?.requiredAmount,hasSufficientBalance:a?.hasSufficientBalance,tokenShortcode:a?.tokenShortcode}:null});let c=String(a?.chainName||"").toLowerCase(),d=c.includes("sol"),p=this.config?.recipientAddresses||{},y=d?p.sol||p.ic||this.config?.recipientAddress:p.ic||this.config?.recipientAddress,h=c.includes("ic");if(a?.x402Accepts)try{let u={...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:d?"sol":h?"ic":this.config?.icpay_network,icpay_ledger_id:a?.ledgerId,icpay_context:"pay-button:x402"}};await i.client.createPaymentX402Usd({usdAmount:o,tokenShortcode:a?.tokenShortcode,metadata:u,recipientAddress:y||"",fiat_currency:this.config?.fiat_currency});return}catch(u){R(this.config?.debug||!1,"X402 payment failed (SOL selection), falling back",{message:u?.message,code:u?.code,data:u?.details||u?.data});return}await i.client.createPaymentUsd({usdAmount:o,tokenShortcode:a?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:"ic",icpay_ledger_id:a?.ledgerId}},recipientAddress:y||"0x0000000000000000000000000000000000000000"}).catch(u=>{throw u})}catch(a){f(a,{onError:i=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:i,bubbles:!0})),v(i)&&(this.errorMessage=g(i),this.errorSeverity=b(i),this.errorAction=w(i))}})}}}getSdk(){if(!this.sdk){let e=this.config;if((this.lastWalletId==="walletconnect"||this.lastWalletId==="coinbase")&&this.pnp){let n=this.pnp.getEvmProvider?.();n&&(e={...e,evmProvider:n})}this.loadedPaymentIntent?.paymentIntent?e={...e,paymentIntent:this.loadedPaymentIntent.paymentIntent}:this.config?.paymentIntent!=null&&typeof this.config.paymentIntent=="object"&&(e={...e,paymentIntent:this.config.paymentIntent}),!e.paymentIntent&&(this.loadedPaymentIntent?.paymentIntentId??this.config?.paymentIntentId)&&(e={...e,paymentIntentId:this.loadedPaymentIntent?.paymentIntentId??this.config.paymentIntentId}),this.sdk=E(e)}return this.sdk}async getOrCreatePnp(){if(this.pnp)return this.pnp;ce||(ce=(await import("./wallet-select-VE5FSSFG.js")).WalletSelect);let e=!!(this.config?.openOisyInNewTab||this.config?.plugNPlay?.openOisyInNewTab),t={...this.config?.plugNPlay||{}},n=this.config?.recipientAddresses;if(n&&(n.ic||n.evm||n.sol)){let i=[];n.ic&&i.push("ic"),n.evm&&i.push("evm"),n.sol&&i.push("sol"),i.length&&(t.chainTypes=i)}else this.config?.chainTypes&&(t.chainTypes=this.config.chainTypes);let a=e?I(t):t;try{if(typeof window<"u"){let{resolveDerivationOrigin:i}=await import("./origin-44ZEXSX4.js");a.derivationOrigin=this.config?.derivationOrigin||i()}}catch{}return this.pnp=new ce(a),this.pnp}async generateWalletConnectQr(e){try{let t=await this.getOrCreatePnp();return!t||typeof t.generateWalletConnectQr!="function"?null:await t.generateWalletConnectQr({onConnected:n=>{this.walletConnected=!0,this.lastWalletId="walletconnect";let a=x(this.pnp,n),i=this.pnp?.getEvmProvider?.(),o=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:a,actorProvider:(c,d)=>this.pnp.getActor({canisterId:c,idl:d,requiresSigning:!0,anon:!1}),...i?{evmProvider:i}:{},...o?{solanaProvider:o}:{}},this.sdk=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"walletconnect"}}))}catch{}try{e?.onConnected?.()}catch{}this.requestUpdate()}})}catch{return null}}async checkCoinbaseConnection(){try{return(await this.getOrCreatePnp())?.hasCoinbaseAccounts?.()??!1}catch{return!1}}async connectWallet(e){let t=await this.getOrCreatePnp();if(!t||!e)throw new Error("Wallet not available");let n=(e||"").toLowerCase(),a=await t.connect(n);if(!!!(a&&(a.connected===!0||a.principal||a.owner||t.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0,this.lastWalletId=n;let o=x(this.pnp,a),c=this.pnp?.getEvmProvider?.(),d=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:o,actorProvider:(p,y)=>this.pnp.getActor({canisterId:p,idl:y,requiresSigning:!0,anon:!1}),...c?{evmProvider:c}:{},...d?{solanaProvider:d}:{}},this.sdk=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:n}}))}catch{}this.requestUpdate()}connectedCallback(){if(super.connectedCallback(),!!Ge){R(this.config?.debug||!1,"Pay button connected",{config:this.config}),this.config?.theme&&ge(this,this.config.theme);try{window.addEventListener("icpay-switch-account",this.onSwitchAccount)}catch{}try{window.addEventListener("icpay-sdk-transaction-created",(e=>{R(this.config?.debug||!1,"SDK transaction created",{detail:e?.detail}),this.showWalletModal=!1,this.showBalanceModal=!1,this.requestUpdate()}))}catch{}this.onTransactionCompleted=()=>{this.succeeded=!0,this.processing=!1,this.requestUpdate()};try{window.addEventListener("icpay-sdk-transaction-completed",this.onTransactionCompleted)}catch{}this.loadPaymentIntentIfNeeded()}}disconnectedCallback(){if(super.disconnectedCallback(),this.onTransactionCompleted)try{window.removeEventListener("icpay-sdk-transaction-completed",this.onTransactionCompleted)}catch{}}async loadPaymentIntentIfNeeded(){let e=this.config?.paymentIntentId;if(!e||typeof e!="string"||e.trim()===""||this.loadedPaymentIntent!=null)return;let t=this.config?.publishableKey,n=this.config?.apiUrl||"https://api.icpay.org";if(t){this.paymentIntentLoading=!0,this.requestUpdate();try{let a=await Xe(n,t,e.trim(),!!this.config?.debug);if(this.loadedPaymentIntent=a??null,a?.paymentIntent)if(Ye(a.paymentIntent.status))this.succeeded=!0,this.requestUpdate();else{let i=a.paymentIntent;this.config={...this.config,paymentIntent:i,amountUsd:typeof i.amountUsd=="number"?i.amountUsd:this.config?.amountUsd??0,fiat_currency:i.fiatCurrencyCode??this.config?.fiat_currency??void 0},this.sdk=null,this.requestUpdate()}}catch(a){R(this.config?.debug||!1,"Load payment intent error",a)}finally{this.paymentIntentLoading=!1,this.requestUpdate()}}}updated(e){if(e.has("config")&&this.config?.theme&&ge(this,this.config.theme),e.has("config")){let t=this.config?.paymentIntentId;this.loadedPaymentIntent&&this.loadedPaymentIntent.paymentIntentId!==t&&(this.loadedPaymentIntent=null,this.sdk=null),t&&this.loadedPaymentIntent==null&&!this.paymentIntentLoading&&this.loadPaymentIntentIfNeeded()}if(e.has("config")&&this.pendingAction&&this.config?.actorProvider){let t=this.pendingAction;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}this.walletModalStep!=="balances"&&!this.oisyReadyToPay&&(this.pendingAction=null,setTimeout(()=>{t==="pay"&&this.pay()},0))}e.has("config")&&(this.sdk=null)}selectSymbol(e){this.selectedSymbol=e}async ensureWallet(){if(this.config.useOwnWallet)return this.config.actorProvider?!0:(this.pendingAction="pay",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0})),!1);if(this.walletConnected)return!0;try{ce||(ce=(await import("./wallet-select-VE5FSSFG.js")).WalletSelect);let e=!!(this.config?.openOisyInNewTab||this.config?.plugNPlay?.openOisyInNewTab),t={...this.config?.plugNPlay||{}},n=this.config?.recipientAddresses;if(n&&(n.ic||n.evm||n.sol)){let o=[];n.ic&&o.push("ic"),n.evm&&o.push("evm"),n.sol&&o.push("sol"),o.length&&(t.chainTypes=o)}else this.config?.chainTypes&&(t.chainTypes=this.config.chainTypes);let a=e?I(t):t;try{if(typeof window<"u"){let{resolveDerivationOrigin:o}=await import("./origin-44ZEXSX4.js");a.derivationOrigin=this.config?.derivationOrigin||o()}}catch{}this.pnp=new ce(a);let i=this.pnp.getEnabledWallets();if(R(this.config?.debug||!1,"Available wallets",i),!i?.length)throw new Error("No wallets available");return this.pendingAction="pay",this.showWalletModal=!0,!1}catch(e){return this.errorMessage=e instanceof Error?e.message:"Wallet connection failed",this.errorSeverity="error",!1}}getWalletId(e){return e&&(e.id||e.provider||e.key)||""}getWalletLabel(e){return e&&(e.label||e.name||e.title||e.id)||"Wallet"}getWalletIcon(e){return e&&(e.icon||e.logo||e.image)||null}connectWithWallet(e){if(this.pnp)try{if(!e)throw new Error("No wallet ID provided");this.lastWalletId=(e||"").toLowerCase(),this.lastWalletId==="oisy"&&(this.oisyConnectRetriedNewTab=!1),this.pnp.connect(e).then(n=>{if(R(this.config?.debug||!1,"Wallet connect result",n),!!!(n&&(n.connected===!0||n.principal||n.owner||this.pnp?.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:e}}))}catch{}let i=x(this.pnp,n),o=this.pnp?.getEvmProvider?.(),c=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:i,actorProvider:(d,p)=>this.pnp.getActor({canisterId:d,idl:p,requiresSigning:!0,anon:!1}),...o?{evmProvider:o}:{},...c?{solanaProvider:c}:{}},this.sdk=null,this.walletModalStep="balances",this.fetchAndShowBalances("pay")}).catch(n=>{R(this.config?.debug||!1,"Wallet connection error",n);let a=(e||"").toLowerCase()==="oisy",i=n&&(n.message||String(n))||"";if(a&&!this.oisyConnectRetriedNewTab&&(i.includes("Signer window could not be opened")||i.includes("Communication channel could not be established"))){this.oisyConnectRetriedNewTab=!0,(async()=>{try{ce||(ce=(await import("./wallet-select-VE5FSSFG.js")).WalletSelect);let c={...this.config?.plugNPlay||{}},d=this.config?.recipientAddresses;if(d&&(d.ic||d.evm||d.sol)){let h=[];d.ic&&h.push("ic"),d.evm&&h.push("evm"),d.sol&&h.push("sol"),h.length&&(c.chainTypes=h)}else this.config?.chainTypes&&(c.chainTypes=this.config.chainTypes);let p=I(c);try{if(typeof window<"u"){let{resolveDerivationOrigin:h}=await import("./origin-44ZEXSX4.js");p.derivationOrigin=this.config?.derivationOrigin||h()}}catch{}this.pnp=new ce(p),this.pnp.connect("oisy").then(h=>{if(!!!(h&&(h.connected===!0||h.principal||h.owner||this.pnp?.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"oisy"}}))}catch{}let m=x(this.pnp,h),j=this.pnp?.getEvmProvider?.();this.config={...this.config,connectedWallet:m,actorProvider:(Me,We)=>this.pnp.getActor({canisterId:Me,idl:We,requiresSigning:!0,anon:!1}),...j?{evmProvider:j}:{}},this.sdk=null,this.walletModalStep="balances",this.fetchAndShowBalances("pay")}).catch(h=>{R(this.config?.debug||!1,"Oisy retry connect (new tab) failed",h),this.errorMessage=h instanceof Error?h.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-error",{detail:{message:this.errorMessage,code:"WALLET_CONNECT_ERROR"}}))}catch{}})}catch(c){R(this.config?.debug||!1,"Oisy new-tab init failed",c),this.errorMessage=c instanceof Error?c.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-error",{detail:{message:this.errorMessage,code:"WALLET_CONNECT_ERROR"}}))}catch{}}})();return}this.errorMessage=n instanceof Error?n.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-error",{detail:{message:this.errorMessage,code:"WALLET_CONNECT_ERROR"}}))}catch{}})}catch(t){R(this.config?.debug||!1,"Wallet connection error (sync)",t),this.errorMessage=t instanceof Error?t.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-error",{detail:{message:this.errorMessage,code:"WALLET_CONNECT_ERROR"}}))}catch{}}}async fetchAndShowBalances(e){try{this.balancesLoading=!0,this.balancesError=null,this.walletModalStep="balances",this.showBalanceModal=!1;let t=this.getSdk(),{balances:n}=await Y({sdk:t,lastWalletId:this.lastWalletId,connectedWallet:this.config?.connectedWallet,amountUsd:Number(this.config?.amountUsd??0),fiatCurrency:this.config?.fiat_currency,chainShortcodes:this.config?.chainShortcodes,tokenShortcodes:this.config?.tokenShortcodes});this.walletBalances=n,this.pendingAction=e}catch(t){this.walletBalances=[],this.balancesError=t&&(t.message||String(t))||"Failed to load balances"}finally{this.balancesLoading=!1}}renderWalletModal(){if(!this.showWalletModal||!this.pnp)return null;let e=this.pnp.getEnabledWallets()||[],t=V(e),n=this.config?.onramp?.enabled===!0&&this.config?.onrampDisabled!==!0,a=2,i=Number(this.config?.amountUsd??0),o=n&&i>0&&i<a,c=Math.max(0,a-i),d=o?`Note: Minimum card amount is $${a}. You will pay about $${c.toFixed(2)} more.`:null,p=this.config?.theme?typeof this.config.theme=="string"?this.config.theme:this.config.theme.mode||"light":void 0;return Q({visible:this.showWalletModal,wallets:t,isConnecting:!1,onSwitchAccount:()=>this.onSwitchAccount(null),step:this.walletModalStep,balances:this.walletModalStep==="balances"?this.walletBalances||[]:[],balancesLoading:this.walletModalStep==="balances"?this.balancesLoading:!1,balancesError:this.walletModalStep==="balances"?this.balancesError:null,onSelectBalance:y=>this.onSelectBalanceSymbol(y),onBack:()=>{this.walletModalStep="connect"},onSelect:y=>{this.connectWithWallet(y)},onClose:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-cancelled",{detail:{reason:"user_cancelled"}}))}catch{}},onDismiss:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1},onCreditCard:n?()=>this.startOnramp():void 0,creditCardLabel:this.config?.onramp?.creditCardLabel||"Pay with credit card",showCreditCard:n,creditCardTooltip:d,oisyReadyToPay:this.oisyReadyToPay,onOisyPay:()=>{this.showWalletModal=!1,this.skipDisconnectOnce=!0,this.oisyReadyToPay=!1,this.pay()},theme:p})}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"createPaymentUsd",type:"onramp"}}))}catch{}this.showWalletModal=!1;let e=Array.isArray(this.config?.onramp?.providers)?this.config.onramp.providers.filter(n=>n&&n.enabled!==!1):[],t=e.length?e:[{slug:"coinbase",name:"Coinbase",enabled:!0}];t.length>1?this.showProviderPicker=!0:(this.selectedOnrampProvider=t[0]?.slug||"coinbase",setTimeout(()=>this.createOnrampIntent(),0))}async createOnrampIntent(){try{let e=Number(this.config?.amountUsd??0),t=this.getSdk();this.selectedSymbol||(this.selectedSymbol="ICP");let n=await t.startOnrampUsd(e,void 0,{context:"pay-button:onramp",onrampPayment:!0,onrampProvider:this.selectedOnrampProvider||"coinbase"}),a=n?.metadata?.onramp?.url||n?.onramp?.url||n?.metadata?.icpay_onramp?.url||n?.paymentIntent?.metadata?.icpay?.onrampUrl||n?.metadata?.icpay?.onrampUrl||null,i=n?.metadata?.icpay_onramp?.errorMessage||n?.metadata?.onramp?.errorMessage||n?.paymentIntent?.metadata?.icpay?.onrampError||n?.paymentIntent?.metadata?.icpay?.errorMessage||n?.metadata?.icpay?.onrampError||n?.metadata?.icpay?.errorMessage||null;this.onrampErrorMessage=i||null;let o=n?.metadata?.icpay_payment_intent_id||n?.metadata?.paymentIntentId||n?.paymentIntentId||null;if(this.onrampPaymentIntentId=o,a){this.onrampUrl=a;try{window.open(a,"icpay_onramp","noopener,noreferrer");try{window.dispatchEvent(new CustomEvent("icpay-onramp-opened",{detail:{url:a}}))}catch{}}catch{}this.startOnrampPolling(void 0)}else this.onrampUrl=null,this.showOnrampModal=!0}catch(e){this.onrampUrl=null,this.onrampErrorMessage=e?.message||null,this.showOnrampModal=!0,f(e,{onError:t=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:t,bubbles:!0})),v(t)&&(this.errorMessage=g(t),this.errorSeverity=b(t),this.errorAction=w(t))}})}}startOnrampPolling(e){if(this.onrampPollTimer){try{clearInterval(this.onrampPollTimer)}catch{}this.onrampPollTimer=null}if(this.onrampNotifyController){try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null}let t=this.onrampPaymentIntentId;if(!t)return;let n=this.getSdk(),a=()=>{if(this.onrampNotifyController)try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null,this.onrampPollingActive=!1},i=o=>{a()};try{window.addEventListener("icpay-sdk-transaction-completed",i,{once:!0})}catch{}this.onrampPollingActive=!0,this.onrampNotifyController=n.notifyIntentUntilComplete(t,5e3,e),this.onrampPollTimer=1}resetPaymentFlow(e=!1){ee(this,{pendingAction:"pay",keepWalletConnected:e})}async pay(){if(Ge){this.resetPaymentFlow(this.walletConnected);try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"pay",type:"sendUsd",amount:this.config?.amountUsd,currency:this.selectedSymbol||"ICP"}}))}catch{}this.processing=!0;try{if(!await this.ensureWallet())return;let t=this.getSdk();try{let n=this.config?.connectedWallet,a=this?.pnp?.account;R(this.config?.debug||!1,"Wallet state before payment",{connectedWallet:n,pnpAccount:a,principal:n?.owner||n?.principal||a?.owner||a?.principal||null})}catch{}this.walletModalStep="balances",this.showWalletModal=!0,await this.fetchAndShowBalances("pay");return}catch(e){R(this.config?.debug||!1,"Payment error",{message:e?.message,code:e?.code,details:e?.details,stack:e?.stack}),f(e,{onError:t=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:t,bubbles:!0})),v(t)&&(this.errorMessage=g(t),this.errorSeverity=b(t),this.errorAction=w(t))}});try{!this.config.useOwnWallet&&this.pnp&&(await this.pnp.disconnect?.(),this.walletConnected=!1,this.config={...this.config,actorProvider:void 0,connectedWallet:void 0})}catch{}}finally{this.processing=!1}}}render(){if(!this.config)return ue`<div class="icpay-card icpay-section">Loading...</div>`;if(this.paymentIntentLoading&&this.config?.paymentIntentId)return ue`<div class="icpay-card icpay-section">Loading payment...</div>`;let e=this.selectedSymbol||"ICP",t=typeof this.config?.amountUsd=="number"?this.config.amountUsd:this.loadedPaymentIntent?.paymentIntent?.amountUsd!=null?Number(this.loadedPaymentIntent.paymentIntent.amountUsd):void 0,n=typeof t=="number"?`${Number(t).toFixed(2)}`:"",i=(this.config?.buttonLabel||(typeof t=="number"?"Pay with crypto":"Pay with {symbol}")).replace("{amount}",n||"$0.00").replace("{symbol}",e),c=this.config?.progressBar?.enabled!==!1,d=this.showWalletModal||this.showBalanceModal;return ue`
2003
+ `}var Bt=typeof window<"u";async function Ne(r,l,e,t=!1){if(!Bt||!e||!l)return null;let n=`${(r||"https://api.icpay.org").replace(/\/$/,"")}/sdk/public/payments/intents/${encodeURIComponent(e)}`;try{t&&console.log("[ICPay Widget] Fetching payment intent",{intentId:e,url:n.replace(l,"***")});let i=await fetch(n,{method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${l}`}});if(!i.ok)return t&&console.log("[ICPay Widget] Fetch payment intent failed",i.status,await i.text()),null;let s=await i.json();return s?.paymentIntent?.id?s:null}catch(i){return t&&console.log("[ICPay Widget] Fetch payment intent error",i),null}}function _e(r){if(!r)return!1;let l=String(r).toLowerCase();return l==="succeeded"||l==="completed"}var Ge=typeof window<"u",le=null;function N(r,l,e){r&&(e!==void 0?console.log(`[ICPay Widget] ${l}`,e):console.log(`[ICPay Widget] ${l}`))}var k=class extends Rt{constructor(){super(...arguments);this.selectedSymbol=null;this.processing=!1;this.succeeded=!1;this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.walletModalStep="connect";this.showOnrampModal=!1;this.onrampUrl=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.showProviderPicker=!1;this.selectedOnrampProvider=null;this.oisyReadyToPay=!1;this.oisySignerPreopened=!1;this.skipDisconnectOnce=!1;this.lastWalletId=null;this.showBalanceModal=!1;this.balancesLoading=!1;this.balancesError=null;this.walletBalances=[];this.loadedPaymentIntent=null;this.paymentIntentLoading=!1;this.onrampPollTimer=null;this.pnp=null;this.oisyConnectRetriedNewTab=!1;this.sdk=null;this.onrampPollingActive=!1;this.onrampNotifyController=null;this.onTransactionCompleted=null;this.onSwitchAccount=async e=>{try{if(this.pnp)try{await this.pnp.disconnect()}catch{}this.walletConnected=!1,this.config={...this.config,actorProvider:void 0,connectedWallet:void 0},this.pendingAction="pay",this.walletModalStep="connect",this.showWalletModal=!0,this.oisyReadyToPay=!1,this.lastWalletId=null,this.requestUpdate();try{let t=Number(this.config?.amountUsd||0),a=this.selectedSymbol||"ICP";window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"pay",type:"sendUsd",amount:t,currency:a}}))}catch{}}catch{}};this.onSelectBalanceSymbol=async e=>{let t=(this.walletBalances||[]).find(n=>n?.tokenShortcode===e);if(t?.ledgerSymbol&&(this.selectedSymbol=t.ledgerSymbol),this.showBalanceModal=!1,this.showWalletModal=!1,e==="stripe_usd"||(this.lastWalletId||"").toLowerCase()==="stripe"){try{let n=this.getSdk(),i=Number(this.config?.amountUsd??0),s=await n.client.createPayment({amountUsd:i,networkType:"stripe",metadata:this.config?.metadata||{},fiat_currency:this.config?.fiat_currency,returnUrl:typeof window<"u"?window.location.href:void 0}),o=s?.checkoutUrl,d=s?.paymentIntentId;try{window.dispatchEvent(new CustomEvent("icpay-stripe-intent-created",{detail:{checkoutUrl:o,paymentIntentId:d,amountUsd:i},bubbles:!0}))}catch{}if(this.dispatchEvent(new CustomEvent("icpay-stripe-intent-created",{detail:{checkoutUrl:o,paymentIntentId:d,amountUsd:i},bubbles:!0})),o&&typeof window<"u")try{window.open(o,"_blank","noopener,noreferrer");try{window.dispatchEvent(new CustomEvent("icpay-stripe-newtab-opened",{detail:{checkoutUrl:o,paymentIntentId:d},bubbles:!0}))}catch{}}catch(p){this.errorMessage=p?.message||"Could not open Stripe checkout page",this.errorSeverity="error"}else this.errorMessage="Stripe checkout session created; check icpay-stripe-intent-created event for checkoutUrl.",this.errorSeverity="info"}catch(n){f(n,{onError:i=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:i,bubbles:!0})),this.errorMessage=m(i),this.errorSeverity=v(i)}})}return}if(j(this.lastWalletId)){N(this.config?.debug||!1,"EVM selection made",{selectedSymbol:this.selectedSymbol,selPresent:!!t,selSnapshot:t?{ledgerId:t?.ledgerId,ledgerSymbol:t?.ledgerSymbol,ledgerName:t?.ledgerName,chainUuid:t?.chainUuid,chainId:t?.chainId,chainName:t?.chainName,x402Accepts:t?.x402Accepts,requiredAmount:t?.requiredAmount,hasSufficientBalance:t?.hasSufficientBalance}:null});let n=t?.chainId;V(n,{provider:this.pnp?.getEvmProvider?.()||this.config?.evmProvider,chainName:t?.chainName,rpcUrlPublic:t?.rpcUrlPublic,nativeSymbol:t?.ledgerSymbol,decimals:t?.decimals}).then(async()=>{try{let i=this.getSdk(),s=Number(this.config?.amountUsd??0),o=t?.ledgerSymbol,d=J(this.lastWalletId),p=!!(t&&t.x402Accepts)&&!d;if(N(this.config?.debug||!1,"EVM post-ensure chain snapshot",{targetChain:n,amountUsd:s,symbolNow:o,tryX402:p,skipX402BaseIos:d,x402Accepts:t?.x402Accepts}),p)try{let h=this.config?.recipientAddresses?.evm||"0x0000000000000000000000000000000000000000";N(this.config?.debug||!1,"Using recipientAddress (x402)",{recipientAddress:h});let u={...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:"evm",icpay_ledger_id:t?.ledgerId,icpay_context:"pay-button:x402"}};N(this.config?.debug||!1,"Attempting X402 flow (EVM selection)",{amountUsd:s,tokenShortcode:t?.tokenShortcode,x402Accepts:t?.x402Accepts});let g=await i.client.createPaymentX402Usd({usdAmount:s,tokenShortcode:t?.tokenShortcode,metadata:u,recipientAddress:h,fiat_currency:this.config?.fiat_currency,x402Upto:!!this.config?.x402Upto});if(this.config?.x402Upto&&typeof this.config?.onX402UptoIntent=="function")try{let M=g?.payment||{},te=g?.paymentIntentId||M?.paymentIntentId||M?.intentId||"",de=Array.isArray(M?.accepts)?M.accepts:[];this.config.onX402UptoIntent({paymentIntentId:te,amountUsd:s,metadata:u,accepts:de}),te&&await this.pollUntilIntentTerminal(te)}catch(M){N(this.config?.debug||!1,"onX402UptoIntent callback failed",{error:String(M)})}return}catch(h){N(this.config?.debug||!1,"X402 payment failed (EVM selection), falling back",{message:h?.message,code:h?.code,data:h?.details||h?.data})}else N(this.config?.debug||!1,"Skipping X402 path",{reason:t?t.x402Accepts?"unknown":"x402Accepts false":"no selection",selPresent:!!t,x402Accepts:t?.x402Accepts});N(this.config?.debug||!1,"Falling back to normal EVM wallet flow",{amountUsd:s,tokenShortcode:t?.tokenShortcode});let y=this.config?.recipientAddresses?.evm||"0x0000000000000000000000000000000000000000";N(this.config?.debug||!1,"Using recipientAddress (normal)",{recipientAddress:y}),await i.client.createPaymentUsd({usdAmount:s,tokenShortcode:t?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:"evm",icpay_ledger_id:t?.ledgerId}},recipientAddress:y}).catch(h=>{throw h})}catch(i){f(i,{onError:s=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:s,bubbles:!0})),w(s)&&(this.errorMessage=m(s),this.errorSeverity=v(s),this.errorAction=b(s))}})}});return}let a=this.pendingAction;if(this.pendingAction=null,a==="pay")try{let n=(this.walletBalances||[]).find(u=>u?.tokenShortcode===e),i=this.getSdk(),s=Number(this.config?.amountUsd??0);N(this.config?.debug||!1,"IC selection made",{selectedSymbol:this.selectedSymbol,selPresent:!!n,selSnapshot:n?{ledgerId:n?.ledgerId,ledgerSymbol:n?.ledgerSymbol,ledgerName:n?.ledgerName,requiredAmount:n?.requiredAmount,hasSufficientBalance:n?.hasSufficientBalance,tokenShortcode:n?.tokenShortcode}:null});let o=String(n?.chainName||"").toLowerCase(),d=o.includes("sol"),p=this.config?.recipientAddresses||{},y=d?p.sol||p.ic||this.config?.recipientAddress:p.ic||this.config?.recipientAddress,h=o.includes("ic");if(n?.x402Accepts)try{let u={...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:d?"sol":h?"ic":this.config?.icpay_network,icpay_ledger_id:n?.ledgerId,icpay_context:"pay-button:x402"}},g=await i.client.createPaymentX402Usd({usdAmount:s,tokenShortcode:n?.tokenShortcode,metadata:u,recipientAddress:y||"",fiat_currency:this.config?.fiat_currency,x402Upto:!!this.config?.x402Upto});if(this.config?.x402Upto&&typeof this.config?.onX402UptoIntent=="function")try{let M=g?.payment||{},te=g?.paymentIntentId||M?.paymentIntentId||M?.intentId||"",de=Array.isArray(M?.accepts)?M.accepts:[];this.config.onX402UptoIntent({paymentIntentId:te,amountUsd:s,metadata:u,accepts:de}),te&&await this.pollUntilIntentTerminal(te)}catch(M){N(this.config?.debug||!1,"onX402UptoIntent callback failed",{error:String(M)})}return}catch(u){N(this.config?.debug||!1,"X402 payment failed (SOL selection), falling back",{message:u?.message,code:u?.code,data:u?.details||u?.data});return}await i.client.createPaymentUsd({usdAmount:s,tokenShortcode:n?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:"ic",icpay_ledger_id:n?.ledgerId}},recipientAddress:y||"0x0000000000000000000000000000000000000000"}).catch(u=>{throw u})}catch(n){f(n,{onError:i=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:i,bubbles:!0})),w(i)&&(this.errorMessage=m(i),this.errorSeverity=v(i),this.errorAction=b(i))}})}}}getSdk(){if(!this.sdk){let e=this.config;if((this.lastWalletId==="walletconnect"||this.lastWalletId==="coinbase")&&this.pnp){let a=this.pnp.getEvmProvider?.();a&&(e={...e,evmProvider:a})}this.loadedPaymentIntent?.paymentIntent?e={...e,paymentIntent:this.loadedPaymentIntent.paymentIntent}:this.config?.paymentIntent!=null&&typeof this.config.paymentIntent=="object"&&(e={...e,paymentIntent:this.config.paymentIntent}),!e.paymentIntent&&(this.loadedPaymentIntent?.paymentIntentId??this.config?.paymentIntentId)&&(e={...e,paymentIntentId:this.loadedPaymentIntent?.paymentIntentId??this.config.paymentIntentId}),this.sdk=E(e)}return this.sdk}async getOrCreatePnp(){if(this.pnp)return this.pnp;le||(le=(await import("./wallet-select-3A5Z7KZJ.js")).WalletSelect);let e=!!(this.config?.openOisyInNewTab||this.config?.plugNPlay?.openOisyInNewTab),t={...this.config?.plugNPlay||{}},a=this.config?.recipientAddresses;if(a&&(a.ic||a.evm||a.sol)){let i=[];a.ic&&i.push("ic"),a.evm&&i.push("evm"),a.sol&&i.push("sol"),i.length&&(t.chainTypes=i)}else this.config?.chainTypes&&(t.chainTypes=this.config.chainTypes);let n=e?O(t):t;try{if(typeof window<"u"){let{resolveDerivationOrigin:i}=await import("./origin-44ZEXSX4.js");n.derivationOrigin=this.config?.derivationOrigin||i()}}catch{}return this.pnp=new le(n),this.pnp}async generateWalletConnectQr(e){try{let t=await this.getOrCreatePnp();return!t||typeof t.generateWalletConnectQr!="function"?null:await t.generateWalletConnectQr({onConnected:a=>{this.walletConnected=!0,this.lastWalletId="walletconnect";let n=x(this.pnp,a),i=this.pnp?.getEvmProvider?.(),s=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:n,actorProvider:(o,d)=>this.pnp.getActor({canisterId:o,idl:d,requiresSigning:!0,anon:!1}),...i?{evmProvider:i}:{},...s?{solanaProvider:s}:{}},this.sdk=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"walletconnect"}}))}catch{}try{e?.onConnected?.()}catch{}this.requestUpdate()}})}catch{return null}}async pollUntilIntentTerminal(e){if(!e||!this.config?.publishableKey)return;let t=30,a=2e3,n=!!this.config?.debug,i=this.config?.apiUrl||"",s=0;for(;s<t;){s++;try{let o=await Ne(i,this.config.publishableKey,e,n),d=o?.paymentIntent?.status;if(_e(d)){this.succeeded=!0,this.processing=!1;try{this.config.onSuccess?.({id:0,status:"completed"})}catch{}return}!o||o.paymentIntent}catch(o){n&&console.log("[ICPay Widget] pollUntilIntentTerminal error",o)}await new Promise(o=>setTimeout(o,a))}}async checkCoinbaseConnection(){try{return(await this.getOrCreatePnp())?.hasCoinbaseAccounts?.()??!1}catch{return!1}}async connectWallet(e){let t=await this.getOrCreatePnp();if(!t||!e)throw new Error("Wallet not available");let a=(e||"").toLowerCase(),n=await t.connect(a);if(!!!(n&&(n.connected===!0||n.principal||n.owner||t.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0,this.lastWalletId=a;let s=x(this.pnp,n),o=this.pnp?.getEvmProvider?.(),d=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:s,actorProvider:(p,y)=>this.pnp.getActor({canisterId:p,idl:y,requiresSigning:!0,anon:!1}),...o?{evmProvider:o}:{},...d?{solanaProvider:d}:{}},this.sdk=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:a}}))}catch{}this.requestUpdate()}connectedCallback(){if(super.connectedCallback(),!!Ge){N(this.config?.debug||!1,"Pay button connected",{config:this.config}),this.config?.theme&&fe(this,this.config.theme);try{window.addEventListener("icpay-switch-account",this.onSwitchAccount)}catch{}try{window.addEventListener("icpay-sdk-transaction-created",(e=>{N(this.config?.debug||!1,"SDK transaction created",{detail:e?.detail}),this.showWalletModal=!1,this.showBalanceModal=!1,this.requestUpdate()}))}catch{}this.onTransactionCompleted=()=>{this.succeeded=!0,this.processing=!1,this.requestUpdate()};try{window.addEventListener("icpay-sdk-transaction-completed",this.onTransactionCompleted)}catch{}this.loadPaymentIntentIfNeeded()}}disconnectedCallback(){if(super.disconnectedCallback(),this.onTransactionCompleted)try{window.removeEventListener("icpay-sdk-transaction-completed",this.onTransactionCompleted)}catch{}}async loadPaymentIntentIfNeeded(){let e=this.config?.paymentIntentId;if(!e||typeof e!="string"||e.trim()===""||this.loadedPaymentIntent!=null)return;let t=this.config?.publishableKey,a=this.config?.apiUrl||"https://api.icpay.org";if(t){this.paymentIntentLoading=!0,this.requestUpdate();try{let n=await Ne(a,t,e.trim(),!!this.config?.debug);if(this.loadedPaymentIntent=n??null,n?.paymentIntent)if(_e(n.paymentIntent.status))this.succeeded=!0,this.requestUpdate();else{let i=n.paymentIntent;this.config={...this.config,paymentIntent:i,amountUsd:typeof i.amountUsd=="number"?i.amountUsd:this.config?.amountUsd??0,fiat_currency:i.fiatCurrencyCode??this.config?.fiat_currency??void 0},this.sdk=null,this.requestUpdate()}}catch(n){N(this.config?.debug||!1,"Load payment intent error",n)}finally{this.paymentIntentLoading=!1,this.requestUpdate()}}}updated(e){if(e.has("config")&&this.config?.theme&&fe(this,this.config.theme),e.has("config")){let t=this.config?.paymentIntentId;this.loadedPaymentIntent&&this.loadedPaymentIntent.paymentIntentId!==t&&(this.loadedPaymentIntent=null,this.sdk=null),t&&this.loadedPaymentIntent==null&&!this.paymentIntentLoading&&this.loadPaymentIntentIfNeeded()}if(e.has("config")&&this.pendingAction&&this.config?.actorProvider){let t=this.pendingAction;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}this.walletModalStep!=="balances"&&!this.oisyReadyToPay&&(this.pendingAction=null,setTimeout(()=>{t==="pay"&&this.pay()},0))}e.has("config")&&(this.sdk=null)}selectSymbol(e){this.selectedSymbol=e}async ensureWallet(){if(this.config.useOwnWallet)return this.config.actorProvider?!0:(this.pendingAction="pay",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0})),!1);if(this.walletConnected)return!0;try{le||(le=(await import("./wallet-select-3A5Z7KZJ.js")).WalletSelect);let e=!!(this.config?.openOisyInNewTab||this.config?.plugNPlay?.openOisyInNewTab),t={...this.config?.plugNPlay||{}},a=this.config?.recipientAddresses;if(a&&(a.ic||a.evm||a.sol)){let s=[];a.ic&&s.push("ic"),a.evm&&s.push("evm"),a.sol&&s.push("sol"),s.length&&(t.chainTypes=s)}else this.config?.chainTypes&&(t.chainTypes=this.config.chainTypes);let n=e?O(t):t;try{if(typeof window<"u"){let{resolveDerivationOrigin:s}=await import("./origin-44ZEXSX4.js");n.derivationOrigin=this.config?.derivationOrigin||s()}}catch{}this.pnp=new le(n);let i=this.pnp.getEnabledWallets();if(N(this.config?.debug||!1,"Available wallets",i),!i?.length)throw new Error("No wallets available");return this.pendingAction="pay",this.showWalletModal=!0,!1}catch(e){return this.errorMessage=e instanceof Error?e.message:"Wallet connection failed",this.errorSeverity="error",!1}}getWalletId(e){return e&&(e.id||e.provider||e.key)||""}getWalletLabel(e){return e&&(e.label||e.name||e.title||e.id)||"Wallet"}getWalletIcon(e){return e&&(e.icon||e.logo||e.image)||null}connectWithWallet(e){if(this.pnp)try{if(!e)throw new Error("No wallet ID provided");this.lastWalletId=(e||"").toLowerCase(),this.lastWalletId==="oisy"&&(this.oisyConnectRetriedNewTab=!1),this.pnp.connect(e).then(a=>{if(N(this.config?.debug||!1,"Wallet connect result",a),!!!(a&&(a.connected===!0||a.principal||a.owner||this.pnp?.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:e}}))}catch{}let i=x(this.pnp,a),s=this.pnp?.getEvmProvider?.(),o=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:i,actorProvider:(d,p)=>this.pnp.getActor({canisterId:d,idl:p,requiresSigning:!0,anon:!1}),...s?{evmProvider:s}:{},...o?{solanaProvider:o}:{}},this.sdk=null,this.walletModalStep="balances",this.fetchAndShowBalances("pay")}).catch(a=>{N(this.config?.debug||!1,"Wallet connection error",a);let n=(e||"").toLowerCase()==="oisy",i=a&&(a.message||String(a))||"";if(n&&!this.oisyConnectRetriedNewTab&&(i.includes("Signer window could not be opened")||i.includes("Communication channel could not be established"))){this.oisyConnectRetriedNewTab=!0,(async()=>{try{le||(le=(await import("./wallet-select-3A5Z7KZJ.js")).WalletSelect);let o={...this.config?.plugNPlay||{}},d=this.config?.recipientAddresses;if(d&&(d.ic||d.evm||d.sol)){let h=[];d.ic&&h.push("ic"),d.evm&&h.push("evm"),d.sol&&h.push("sol"),h.length&&(o.chainTypes=h)}else this.config?.chainTypes&&(o.chainTypes=this.config.chainTypes);let p=O(o);try{if(typeof window<"u"){let{resolveDerivationOrigin:h}=await import("./origin-44ZEXSX4.js");p.derivationOrigin=this.config?.derivationOrigin||h()}}catch{}this.pnp=new le(p),this.pnp.connect("oisy").then(h=>{if(!!!(h&&(h.connected===!0||h.principal||h.owner||this.pnp?.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"oisy"}}))}catch{}let g=x(this.pnp,h),M=this.pnp?.getEvmProvider?.();this.config={...this.config,connectedWallet:g,actorProvider:(te,de)=>this.pnp.getActor({canisterId:te,idl:de,requiresSigning:!0,anon:!1}),...M?{evmProvider:M}:{}},this.sdk=null,this.walletModalStep="balances",this.fetchAndShowBalances("pay")}).catch(h=>{N(this.config?.debug||!1,"Oisy retry connect (new tab) failed",h),this.errorMessage=h instanceof Error?h.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-error",{detail:{message:this.errorMessage,code:"WALLET_CONNECT_ERROR"}}))}catch{}})}catch(o){N(this.config?.debug||!1,"Oisy new-tab init failed",o),this.errorMessage=o instanceof Error?o.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-error",{detail:{message:this.errorMessage,code:"WALLET_CONNECT_ERROR"}}))}catch{}}})();return}this.errorMessage=a instanceof Error?a.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-error",{detail:{message:this.errorMessage,code:"WALLET_CONNECT_ERROR"}}))}catch{}})}catch(t){N(this.config?.debug||!1,"Wallet connection error (sync)",t),this.errorMessage=t instanceof Error?t.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-error",{detail:{message:this.errorMessage,code:"WALLET_CONNECT_ERROR"}}))}catch{}}}async fetchAndShowBalances(e){try{if(this.balancesLoading=!0,this.balancesError=null,this.walletModalStep="balances",this.showBalanceModal=!1,(this.lastWalletId||"").toLowerCase()==="stripe"){let n=Number(this.config?.amountUsd??0);this.walletBalances=[{ledgerId:"",ledgerName:"US Dollar",ledgerSymbol:"USD",tokenShortcode:"stripe_usd",canisterId:"stripe_usd",balance:"0",formattedBalance:"0",decimals:2,lastUpdated:new Date,requiredAmount:String(Math.round(n*100)),requiredAmountFormatted:n.toFixed(2),hasSufficientBalance:!0}],this.pendingAction=e,this.balancesLoading=!1;return}let t=this.getSdk(),{balances:a}=await Y({sdk:t,lastWalletId:this.lastWalletId,connectedWallet:this.config?.connectedWallet,amountUsd:Number(this.config?.amountUsd??0),fiatCurrency:this.config?.fiat_currency,chainShortcodes:this.config?.chainShortcodes,tokenShortcodes:this.config?.tokenShortcodes});this.walletBalances=a,this.pendingAction=e}catch(t){this.walletBalances=[],this.balancesError=t&&(t.message||String(t))||"Failed to load balances"}finally{this.balancesLoading=!1}}renderWalletModal(){if(!this.showWalletModal||!this.pnp)return null;let e=this.pnp.getEnabledWallets()||[],t=X(e),a=this.config?.onramp?.enabled===!0&&this.config?.onrampDisabled!==!0,n=2,i=Number(this.config?.amountUsd??0),s=a&&i>0&&i<n,o=Math.max(0,n-i),d=s?`Note: Minimum card amount is $${n}. You will pay about $${o.toFixed(2)} more.`:null,p=this.config?.theme?typeof this.config.theme=="string"?this.config.theme:this.config.theme.mode||"light":void 0;return Q({visible:this.showWalletModal,wallets:t,isConnecting:!1,onSwitchAccount:()=>this.onSwitchAccount(null),step:this.walletModalStep,balances:this.walletModalStep==="balances"?this.walletBalances||[]:[],balancesLoading:this.walletModalStep==="balances"?this.balancesLoading:!1,balancesError:this.walletModalStep==="balances"?this.balancesError:null,onSelectBalance:y=>this.onSelectBalanceSymbol(y),onBack:()=>{this.walletModalStep="connect"},onSelect:y=>{this.connectWithWallet(y)},onClose:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-cancelled",{detail:{reason:"user_cancelled"}}))}catch{}},onDismiss:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1},onCreditCard:a?()=>this.startOnramp():void 0,creditCardLabel:this.config?.onramp?.creditCardLabel||"Pay with credit card",showCreditCard:a,creditCardTooltip:d,oisyReadyToPay:this.oisyReadyToPay,onOisyPay:()=>{this.showWalletModal=!1,this.skipDisconnectOnce=!0,this.oisyReadyToPay=!1,this.pay()},theme:p})}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"createPaymentUsd",type:"onramp"}}))}catch{}this.showWalletModal=!1;let e=Array.isArray(this.config?.onramp?.providers)?this.config.onramp.providers.filter(a=>a&&a.enabled!==!1):[],t=e.length?e:[{slug:"coinbase",name:"Coinbase",enabled:!0}];t.length>1?this.showProviderPicker=!0:(this.selectedOnrampProvider=t[0]?.slug||"coinbase",setTimeout(()=>this.createOnrampIntent(),0))}async createOnrampIntent(){try{let e=Number(this.config?.amountUsd??0),t=this.getSdk();this.selectedSymbol||(this.selectedSymbol="ICP");let a=await t.startOnrampUsd(e,void 0,{context:"pay-button:onramp",onrampPayment:!0,onrampProvider:this.selectedOnrampProvider||"coinbase"}),n=a?.metadata?.onramp?.url||a?.onramp?.url||a?.metadata?.icpay_onramp?.url||a?.paymentIntent?.metadata?.icpay?.onrampUrl||a?.metadata?.icpay?.onrampUrl||null,i=a?.metadata?.icpay_onramp?.errorMessage||a?.metadata?.onramp?.errorMessage||a?.paymentIntent?.metadata?.icpay?.onrampError||a?.paymentIntent?.metadata?.icpay?.errorMessage||a?.metadata?.icpay?.onrampError||a?.metadata?.icpay?.errorMessage||null;this.onrampErrorMessage=i||null;let s=a?.metadata?.icpay_payment_intent_id||a?.metadata?.paymentIntentId||a?.paymentIntentId||null;if(this.onrampPaymentIntentId=s,n){this.onrampUrl=n;try{window.open(n,"icpay_onramp","noopener,noreferrer");try{window.dispatchEvent(new CustomEvent("icpay-onramp-opened",{detail:{url:n}}))}catch{}}catch{}this.startOnrampPolling(void 0)}else this.onrampUrl=null,this.showOnrampModal=!0}catch(e){this.onrampUrl=null,this.onrampErrorMessage=e?.message||null,this.showOnrampModal=!0,f(e,{onError:t=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:t,bubbles:!0})),w(t)&&(this.errorMessage=m(t),this.errorSeverity=v(t),this.errorAction=b(t))}})}}startOnrampPolling(e){if(this.onrampPollTimer){try{clearInterval(this.onrampPollTimer)}catch{}this.onrampPollTimer=null}if(this.onrampNotifyController){try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null}let t=this.onrampPaymentIntentId;if(!t)return;let a=this.getSdk(),n=()=>{if(this.onrampNotifyController)try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null,this.onrampPollingActive=!1},i=s=>{n()};try{window.addEventListener("icpay-sdk-transaction-completed",i,{once:!0})}catch{}this.onrampPollingActive=!0,this.onrampNotifyController=a.notifyIntentUntilComplete(t,5e3,e),this.onrampPollTimer=1}resetPaymentFlow(e=!1){ee(this,{pendingAction:"pay",keepWalletConnected:e})}async pay(){if(Ge){this.resetPaymentFlow(this.walletConnected);try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"pay",type:"sendUsd",amount:this.config?.amountUsd,currency:this.selectedSymbol||"ICP"}}))}catch{}this.processing=!0;try{if(!await this.ensureWallet())return;let t=this.getSdk();try{let a=this.config?.connectedWallet,n=this?.pnp?.account;N(this.config?.debug||!1,"Wallet state before payment",{connectedWallet:a,pnpAccount:n,principal:a?.owner||a?.principal||n?.owner||n?.principal||null})}catch{}this.walletModalStep="balances",this.showWalletModal=!0,await this.fetchAndShowBalances("pay");return}catch(e){N(this.config?.debug||!1,"Payment error",{message:e?.message,code:e?.code,details:e?.details,stack:e?.stack}),f(e,{onError:t=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:t,bubbles:!0})),w(t)&&(this.errorMessage=m(t),this.errorSeverity=v(t),this.errorAction=b(t))}});try{!this.config.useOwnWallet&&this.pnp&&(await this.pnp.disconnect?.(),this.walletConnected=!1,this.config={...this.config,actorProvider:void 0,connectedWallet:void 0})}catch{}}finally{this.processing=!1}}}render(){if(!this.config)return me`<div class="icpay-card icpay-section">Loading...</div>`;if(this.paymentIntentLoading&&this.config?.paymentIntentId)return me`<div class="icpay-card icpay-section">Loading payment...</div>`;let e=this.selectedSymbol||"ICP",t=typeof this.config?.amountUsd=="number"?this.config.amountUsd:this.loadedPaymentIntent?.paymentIntent?.amountUsd!=null?Number(this.loadedPaymentIntent.paymentIntent.amountUsd):void 0,a=typeof t=="number"?`${Number(t).toFixed(2)}`:"",i=(this.config?.buttonLabel||(typeof t=="number"?"Pay with crypto":"Pay with {symbol}")).replace("{amount}",a||"$0.00").replace("{symbol}",e),o=this.config?.progressBar?.enabled!==!1,d=this.showWalletModal||this.showBalanceModal;return me`
2004
2004
  <div class="icpay-card icpay-section icpay-widget-base">
2005
- ${c?ue`
2005
+ ${o?me`
2006
2006
  <icpay-progress-bar
2007
2007
  .debug=${!!this.config?.debug}
2008
2008
  .theme=${this.config?.theme}
@@ -2020,17 +2020,17 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
2020
2020
  </button>
2021
2021
  </div>
2022
2022
 
2023
- ${this.errorMessage?ue`
2023
+ ${this.errorMessage?me`
2024
2024
  <div class="error-message ${this.errorSeverity}" style="margin-top: 12px; padding: 8px 12px; border-radius: 6px; font-size: 14px; text-align: center;">
2025
2025
  ${this.errorMessage}
2026
- ${this.errorAction?ue`<button style="margin-left: 8px; padding: 4px 8px; background: transparent; border: 1px solid currentColor; border-radius: 4px; font-size: 12px; cursor: pointer;">${this.errorAction}</button>`:""}
2026
+ ${this.errorAction?me`<button style="margin-left: 8px; padding: 4px 8px; background: transparent; border: 1px solid currentColor; border-radius: 4px; font-size: 12px; cursor: pointer;">${this.errorAction}</button>`:""}
2027
2027
  </div>
2028
2028
  `:""}
2029
2029
  ${this.renderWalletModal()}
2030
- ${(()=>{let p=this.config?.theme?typeof this.config.theme=="string"?this.config.theme:this.config.theme.mode||"light":void 0;return ue`
2030
+ ${(()=>{let p=this.config?.theme?typeof this.config.theme=="string"?this.config.theme:this.config.theme.mode||"light":void 0;return me`
2031
2031
  ${Z({visible:this.showBalanceModal,isLoading:this.balancesLoading,error:this.balancesError,balances:this.walletBalances,onSelect:y=>this.onSelectBalanceSymbol(y),onClose:()=>{this.showBalanceModal=!1},theme:p})}
2032
2032
  ${H({visible:this.showOnrampModal,url:this.onrampUrl||void 0,errorMessage:this.onrampErrorMessage||void 0,width:this.config?.onramp?.width,height:this.config?.onramp?.height,onClose:()=>{this.showOnrampModal=!1},onBack:()=>{this.showOnrampModal=!1,this.showWalletModal=!0},title:"Pay with credit card",theme:p})}
2033
- ${Ve({visible:this.showProviderPicker,providers:(()=>{let y=Array.isArray(this.config?.onramp?.providers)?this.config.onramp.providers.filter(u=>u&&u.enabled!==!1):[];return(y.length?y:[{slug:"coinbase",name:"Coinbase",enabled:!0}]).map(u=>({slug:u.slug,name:u.name||(u.slug==="coinbase"?"Coinbase":u.slug),logoUrl:u.logoUrl||null}))})(),onSelect:y=>{this.selectedOnrampProvider=y,this.showProviderPicker=!1,setTimeout(()=>this.createOnrampIntent(),0)},onClose:()=>{this.showProviderPicker=!1},title:"Choose onramp provider",theme:p})}
2033
+ ${Ye({visible:this.showProviderPicker,providers:(()=>{let y=Array.isArray(this.config?.onramp?.providers)?this.config.onramp.providers.filter(u=>u&&u.enabled!==!1):[];return(y.length?y:[{slug:"coinbase",name:"Coinbase",enabled:!0}]).map(u=>({slug:u.slug,name:u.name||(u.slug==="coinbase"?"Coinbase":u.slug),logoUrl:u.logoUrl||null}))})(),onSelect:y=>{this.selectedOnrampProvider=y,this.showProviderPicker=!1,setTimeout(()=>this.createOnrampIntent(),0)},onClose:()=>{this.showProviderPicker=!1},title:"Choose onramp provider",theme:p})}
2034
2034
  `})()}
2035
2035
  <div class="icpay-powered-by">
2036
2036
  <a href="https://icpay.org" target="_blank" rel="noopener noreferrer">Powered by icpay</a>
@@ -2044,9 +2044,9 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
2044
2044
  .error-message.info { background: var(--icpay-processing-bg); border-color: var(--icpay-processing-border); color: var(--icpay-processing-text); }
2045
2045
  .error-message.warning { background: var(--icpay-warning-bg); border-color: var(--icpay-warning-border); color: var(--icpay-warning-text); }
2046
2046
  .error-message.error { background: var(--icpay-error-bg); border-color: var(--icpay-error-border); color: var(--icpay-error-text); }
2047
- `],s([zt({type:Object})],k.prototype,"config",2),s([O()],k.prototype,"selectedSymbol",2),s([O()],k.prototype,"processing",2),s([O()],k.prototype,"succeeded",2),s([O()],k.prototype,"errorMessage",2),s([O()],k.prototype,"errorSeverity",2),s([O()],k.prototype,"errorAction",2),s([O()],k.prototype,"walletConnected",2),s([O()],k.prototype,"pendingAction",2),s([O()],k.prototype,"showWalletModal",2),s([O()],k.prototype,"walletModalStep",2),s([O()],k.prototype,"showOnrampModal",2),s([O()],k.prototype,"onrampUrl",2),s([O()],k.prototype,"onrampPaymentIntentId",2),s([O()],k.prototype,"onrampErrorMessage",2),s([O()],k.prototype,"showProviderPicker",2),s([O()],k.prototype,"selectedOnrampProvider",2),s([O()],k.prototype,"oisyReadyToPay",2),s([O()],k.prototype,"oisySignerPreopened",2),s([O()],k.prototype,"skipDisconnectOnce",2),s([O()],k.prototype,"lastWalletId",2),s([O()],k.prototype,"showBalanceModal",2),s([O()],k.prototype,"balancesLoading",2),s([O()],k.prototype,"balancesError",2),s([O()],k.prototype,"walletBalances",2),s([O()],k.prototype,"loadedPaymentIntent",2),s([O()],k.prototype,"paymentIntentLoading",2),k=s([Dt("icpay-pay-button")],k);import{LitElement as qt,html as be,css as jt}from"lit";import{customElement as Kt,property as Ht,state as _}from"lit/decorators.js";var Qe=typeof window<"u",Ne=null;function Vt(r,l,e){r&&(e!==void 0?console.log(`[ICPay Widget] ${l}`,e):console.log(`[ICPay Widget] ${l}`))}var P=class extends qt{constructor(){super(...arguments);this.amountUsd=0;this.hasUserAmount=!1;this.selectedSymbol=null;this.processing=!1;this.succeeded=!1;this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.walletModalStep="connect";this.showOnrampModal=!1;this.onrampUrl=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.oisyReadyToPay=!1;this.lastWalletId=null;this.pnp=null;this.transakMessageHandlerBound=null;this.onrampPollTimer=null;this.onrampPollingActive=!1;this.onrampNotifyController=null;this.showBalanceModal=!1;this.balancesLoading=!1;this.balancesError=null;this.walletBalances=[];this.sdk=null;this.onSwitchAccount=async e=>{try{if(this.pnp)try{await this.pnp.disconnect()}catch{}this.walletConnected=!1,this.config={...this.config,actorProvider:void 0,connectedWallet:void 0},this.pendingAction="pay",this.showWalletModal=!0,this.requestUpdate();try{let t=Number(this.amountUsd||0),n=this.selectedSymbol||"ICP";window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"pay",type:"sendUsd",amount:t,currency:n}}))}catch{}}catch{}};this.onSelectBalanceSymbol=async e=>{let t=(this.walletBalances||[]).find(a=>a?.tokenShortcode===e);if(t?.ledgerSymbol&&(this.selectedSymbol=t.ledgerSymbol),this.showBalanceModal=!1,this.showWalletModal=!1,q(this.lastWalletId)){let a=(this.walletBalances||[]).find(o=>o?.tokenShortcode===e),i=a?.chainId;X(i,{provider:this.pnp?.getEvmProvider?.()||this.config?.evmProvider,chainName:a?.chainName,rpcUrlPublic:a?.rpcUrlPublic,nativeSymbol:a?.ledgerSymbol,decimals:a?.decimals}).then(async()=>{try{let o=E(this.config),c=Number(this.amountUsd||0);if(a?.x402Accepts&&!J(this.lastWalletId))try{await o.client.createPaymentX402Usd({usdAmount:c,tokenShortcode:a?.tokenShortcode,metadata:{...this.config?.metadata,icpay_network:"evm",icpay_ledger_id:a?.ledgerId,icpay_context:"amount-input:x402"},recipientAddress:(this.config?.recipientAddresses||{})?.evm||"0x0000000000000000000000000000000000000000",fiat_currency:this.config?.fiat_currency}),this.showBalanceModal=!1;return}catch(d){f(d,{onError:p=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:p,bubbles:!0})),v(p)&&(this.errorMessage=g(p),this.errorSeverity=b(p),this.errorAction=w(p))}})}await o.client.createPaymentUsd({usdAmount:c,tokenShortcode:a?.tokenShortcode,metadata:{...this.config?.metadata,icpay_network:"evm",icpay_ledger_id:a?.ledgerId},recipientAddress:(this.config?.recipientAddresses||{})?.evm||"0x0000000000000000000000000000000000000000"}).catch(d=>{throw d})}catch(o){f(o,{onError:c=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:c,bubbles:!0})),v(c)&&(this.errorMessage=g(c),this.errorSeverity=b(c),this.errorAction=w(c))}})}this.showBalanceModal=!1});return}let n=this.pendingAction;if(this.pendingAction=null,n==="pay")try{let a=(this.walletBalances||[]).find(u=>u?.tokenShortcode===e),i=E(this.config),o=Number(this.amountUsd||0),c=String(a?.ledgerName||a?.chainName||"").toLowerCase(),d=c.includes("sol"),p=c.includes("ic"),y=this.config?.recipientAddresses||{},h=d&&y.sol||y.ic;if(a?.x402Accepts)try{let u={...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:d?"sol":p?"ic":this.config?.icpay_network,icpay_ledger_id:a?.ledgerId,icpay_context:"amount-input:x402"}};await i.client.createPaymentX402Usd({usdAmount:o,tokenShortcode:a?.tokenShortcode,metadata:u,recipientAddress:h||"",fiat_currency:this.config?.fiat_currency});return}catch(u){f(u,{onError:m=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:m,bubbles:!0})),v(m)&&(this.errorMessage=g(m),this.errorSeverity=b(m),this.errorAction=w(m))}});return}await i.client.createPaymentUsd({usdAmount:o,tokenShortcode:a?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:"ic",icpay_ledger_id:a?.ledgerId}},recipientAddress:h||"0x0000000000000000000000000000000000000000"}).catch(u=>{throw u})}catch(a){f(a,{onError:i=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:i,bubbles:!0})),v(i)&&(this.errorMessage=g(i),this.errorSeverity=b(i),this.errorAction=w(i))}})}}}connectedCallback(){if(super.connectedCallback(),!!Qe){Vt(this.config?.debug||!1,"Amount input connected",{config:this.config}),this.amountUsd=Number(this.config?.defaultAmountUsd??0),this.hasUserAmount=!1;try{window.addEventListener("icpay-switch-account",this.onSwitchAccount)}catch{}try{window.addEventListener("icpay-sdk-transaction-created",(()=>{this.showWalletModal=!1,this.requestUpdate()}))}catch{}}}updated(e){if(e.has("config")&&(!this.hasUserAmount&&typeof this.config?.defaultAmountUsd=="number"&&(this.amountUsd===0||this.amountUsd==null||Number.isNaN(this.amountUsd))&&(this.amountUsd=Number(this.config.defaultAmountUsd)),this.pendingAction&&this.config?.actorProvider)){let t=this.pendingAction;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}this.walletModalStep!=="balances"&&(this.pendingAction=null,setTimeout(()=>{t==="pay"&&this.pay()},0))}}onInputChange(e){let t=Number(this.config?.stepUsd??.5),n=Math.max(0,Number(e.target.value||0)),a=Math.round(n/t)*t;this.amountUsd=Number(a.toFixed(2)),this.hasUserAmount=!0}selectSymbol(e){this.selectedSymbol=e}isValidAmount(){let e=Number(this.config?.minUsd??.5),t=this.config?.maxUsd!==void 0?Number(this.config.maxUsd):1/0;return this.amountUsd>=e&&this.amountUsd<=t}async getOrCreatePnp(){if(this.pnp)return this.pnp;Ne||(Ne=(await import("./wallet-select-VE5FSSFG.js")).WalletSelect);let e=!!(this.config?.openOisyInNewTab||this.config?.plugNPlay?.openOisyInNewTab),t={...this.config?.plugNPlay||{}},n=this.config?.recipientAddresses;if(n&&(n.ic||n.evm||n.sol)){let i=[];n.ic&&i.push("ic"),n.evm&&i.push("evm"),n.sol&&i.push("sol"),i.length&&(t.chainTypes=i)}else this.config?.chainTypes&&(t.chainTypes=this.config.chainTypes);let a=e?I(t):t;try{if(typeof window<"u"){let{resolveDerivationOrigin:i}=await import("./origin-44ZEXSX4.js");a.derivationOrigin=this.config?.derivationOrigin||i()}}catch{}return this.pnp=new Ne(a),this.pnp}async generateWalletConnectQr(e){try{let t=await this.getOrCreatePnp();return!t||typeof t.generateWalletConnectQr!="function"?null:await t.generateWalletConnectQr({onConnected:n=>{this.walletConnected=!0,this.lastWalletId="walletconnect";let a=x(this.pnp,n),i=this.pnp?.getEvmProvider?.(),o=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:a,actorProvider:(c,d)=>this.pnp.getActor({canisterId:c,idl:d,requiresSigning:!0,anon:!1}),...i?{evmProvider:i}:{},...o?{solanaProvider:o}:{}},this.sdk=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"walletconnect"}}))}catch{}try{e?.onConnected?.()}catch{}this.requestUpdate()}})}catch{return null}}async checkCoinbaseConnection(){try{return(await this.getOrCreatePnp())?.hasCoinbaseAccounts?.()??!1}catch{return!1}}async connectWallet(e){let t=await this.getOrCreatePnp();if(!t||!e)throw new Error("Wallet not available");let n=(e||"").toLowerCase(),a=await t.connect(n);if(!!!(a&&(a.connected===!0||a.principal||a.owner||t.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0,this.lastWalletId=n;let o=x(this.pnp,a),c=this.pnp?.getEvmProvider?.(),d=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:o,actorProvider:(p,y)=>this.pnp.getActor({canisterId:p,idl:y,requiresSigning:!0,anon:!1}),...c?{evmProvider:c}:{},...d?{solanaProvider:d}:{}},this.sdk=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:n}}))}catch{}this.requestUpdate()}async ensureWallet(){if(this.config.useOwnWallet)return this.config.actorProvider?!0:(this.pendingAction="pay",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0})),!1);if(this.walletConnected)return!0;try{if(!(await this.getOrCreatePnp()).getEnabledWallets()?.length)throw new Error("No wallets available");return this.pendingAction="pay",this.showWalletModal=!0,!1}catch(e){return this.errorMessage=e instanceof Error?e.message:"Wallet connection failed",this.errorSeverity="error",!1}}getWalletId(e){return e&&(e.id||e.provider||e.key)||""}getWalletLabel(e){return e&&(e.label||e.name||e.title||e.id)||"Wallet"}getWalletIcon(e){return e&&(e.icon||e.logo||e.image)||null}connectWithWallet(e){if(this.pnp)try{if(!e)throw new Error("No wallet ID provided");this.lastWalletId=(e||"").toLowerCase(),this.pnp.connect(e).then(n=>{if(!!!(n&&(n.connected===!0||n.principal||n.owner||this.pnp?.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:e}}))}catch{}let i=x(this.pnp,n),o=this.pnp?.getEvmProvider?.(),c=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:i,actorProvider:(d,p)=>this.pnp.getActor({canisterId:d,idl:p,requiresSigning:!0,anon:!1}),...o?{evmProvider:o}:{},...c?{solanaProvider:c}:{}},this.sdk=null,this.walletModalStep="balances",this.showBalanceModal=!1,this.showWalletModal=!0,this.fetchAndShowBalances()}).catch(n=>{this.errorMessage=n instanceof Error?n.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-error",{detail:{message:this.errorMessage,code:"WALLET_CONNECT_ERROR"}}))}catch{}})}catch(t){this.errorMessage=t instanceof Error?t.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-error",{detail:{message:this.errorMessage,code:"WALLET_CONNECT_ERROR"}}))}catch{}}}async fetchAndShowBalances(){try{this.balancesLoading=!0,this.balancesError=null,this.walletModalStep="balances",this.showBalanceModal=!1;let e=E(this.config),{balances:t}=await Y({sdk:e,lastWalletId:this.lastWalletId,connectedWallet:this.config?.connectedWallet,amountUsd:Number(this.amountUsd??0),fiatCurrency:this.config?.fiat_currency,chainShortcodes:this.config?.chainShortcodes,tokenShortcodes:this.config?.tokenShortcodes});this.walletBalances=t}catch(e){this.walletBalances=[],this.balancesError=e&&(e.message||String(e))||"Failed to load balances"}finally{this.balancesLoading=!1}}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=e=>this.onTransakMessage(e);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(e){let t=e?.data,n=t?.event_id||t?.eventId||t?.id;if(!(!n||typeof n!="string")&&n==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;this.showOnrampModal=!1;let a=t?.data?.id||t?.id||t?.webhookData?.id||null;this.startOnrampPolling(a||void 0)}}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"createPaymentUsd",type:"onramp"}}))}catch{}this.showWalletModal=!1,setTimeout(()=>this.createOnrampIntent(),0)}async createOnrampIntent(){try{let e=E(this.config),t=Number(this.amountUsd),n=await e.startOnrampUsd(t,void 0,{context:"amount-input:onramp",onrampPayment:!0,onrampProvider:this?.selectedOnrampProvider||"coinbase"}),a=n?.metadata?.onramp?.url||n?.onramp?.url||n?.metadata?.icpay_onramp?.url||n?.paymentIntent?.metadata?.icpay?.onrampUrl||n?.metadata?.icpay?.onrampUrl||null,i=n?.metadata?.icpay_payment_intent_id||n?.metadata?.paymentIntentId||n?.paymentIntentId||null,o=n?.metadata?.icpay_onramp?.errorMessage||n?.metadata?.onramp?.errorMessage||null;if(this.onrampPaymentIntentId=i,a){this.onrampUrl=a,this.onrampErrorMessage=null;try{window.open(a,"icpay_onramp","noopener,noreferrer");try{window.dispatchEvent(new CustomEvent("icpay-onramp-opened",{detail:{url:a}}))}catch{}}catch{}this.startOnrampPolling()}else this.onrampUrl=null,this.onrampErrorMessage=o||"Failed to obtain onramp sessionId",this.showOnrampModal=!0}catch(e){this.onrampUrl=null,this.onrampErrorMessage=e?.message||"Failed to obtain onramp sessionId",this.showOnrampModal=!0}}startOnrampPolling(e){if(this.onrampPollTimer){try{clearInterval(this.onrampPollTimer)}catch{}this.onrampPollTimer=null}if(this.onrampNotifyController){try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null}let t=this.onrampPaymentIntentId;if(!t)return;let n=E(this.config),a=()=>{if(this.detachTransakMessageListener(),this.onrampNotifyController)try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null,this.onrampPollingActive=!1};try{window.addEventListener("icpay-sdk-transaction-completed",(()=>a()),{once:!0})}catch{}this.onrampPollingActive=!0,this.onrampNotifyController=n.notifyIntentUntilComplete(t,5e3,e),this.onrampPollTimer=1}resetPaymentFlow(){ee(this,{pendingAction:"pay"})}async pay(){if(Qe){if(this.resetPaymentFlow(),!this.isValidAmount()){this.errorMessage="Please enter a valid amount",this.errorSeverity="warning";return}try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"pay",type:"sendUsd",amount:this.amountUsd,currency:this.selectedSymbol||"ICP"}}))}catch{}this.processing=!0;try{if(!await this.ensureWallet())return;this.showWalletModal=!0,await this.fetchAndShowBalances();return}catch(e){f(e,{onError:t=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:t,bubbles:!0})),v(t)&&(this.errorMessage=g(t),this.errorSeverity=b(t),this.errorAction=w(t))}});try{!this.config.useOwnWallet&&this.pnp&&(await this.pnp.disconnect?.(),this.walletConnected=!1,this.config={...this.config,actorProvider:void 0,connectedWallet:void 0})}catch{}}finally{this.processing=!1}}}render(){if(!this.config)return be`<div class="icpay-card icpay-section">Loading...</div>`;let e=this.config?.placeholder||"Enter amount in USD",n=(this.config?.buttonLabel||"Pay with crypto").replace("{amount}",this.amountUsd?`${Number(this.amountUsd).toFixed(2)}`:"$0.00").replace("{symbol}",this.selectedSymbol||"ICP"),a=this.selectedSymbol||"ICP",o=this.config?.progressBar?.enabled!==!1;return be`
2047
+ `],c([zt({type:Object})],k.prototype,"config",2),c([U()],k.prototype,"selectedSymbol",2),c([U()],k.prototype,"processing",2),c([U()],k.prototype,"succeeded",2),c([U()],k.prototype,"errorMessage",2),c([U()],k.prototype,"errorSeverity",2),c([U()],k.prototype,"errorAction",2),c([U()],k.prototype,"walletConnected",2),c([U()],k.prototype,"pendingAction",2),c([U()],k.prototype,"showWalletModal",2),c([U()],k.prototype,"walletModalStep",2),c([U()],k.prototype,"showOnrampModal",2),c([U()],k.prototype,"onrampUrl",2),c([U()],k.prototype,"onrampPaymentIntentId",2),c([U()],k.prototype,"onrampErrorMessage",2),c([U()],k.prototype,"showProviderPicker",2),c([U()],k.prototype,"selectedOnrampProvider",2),c([U()],k.prototype,"oisyReadyToPay",2),c([U()],k.prototype,"oisySignerPreopened",2),c([U()],k.prototype,"skipDisconnectOnce",2),c([U()],k.prototype,"lastWalletId",2),c([U()],k.prototype,"showBalanceModal",2),c([U()],k.prototype,"balancesLoading",2),c([U()],k.prototype,"balancesError",2),c([U()],k.prototype,"walletBalances",2),c([U()],k.prototype,"loadedPaymentIntent",2),c([U()],k.prototype,"paymentIntentLoading",2),k=c([Dt("icpay-pay-button")],k);import{LitElement as qt,html as xe,css as jt}from"lit";import{customElement as Kt,property as Ht,state as B}from"lit/decorators.js";var Qe=typeof window<"u",$e=null;function Xt(r,l,e){r&&(e!==void 0?console.log(`[ICPay Widget] ${l}`,e):console.log(`[ICPay Widget] ${l}`))}var T=class extends qt{constructor(){super(...arguments);this.amountUsd=0;this.hasUserAmount=!1;this.selectedSymbol=null;this.processing=!1;this.succeeded=!1;this.errorMessage=null;this.errorSeverity=null;this.errorAction=null;this.walletConnected=!1;this.pendingAction=null;this.showWalletModal=!1;this.walletModalStep="connect";this.showOnrampModal=!1;this.onrampUrl=null;this.onrampPaymentIntentId=null;this.onrampErrorMessage=null;this.oisyReadyToPay=!1;this.lastWalletId=null;this.pnp=null;this.transakMessageHandlerBound=null;this.onrampPollTimer=null;this.onrampPollingActive=!1;this.onrampNotifyController=null;this.showBalanceModal=!1;this.balancesLoading=!1;this.balancesError=null;this.walletBalances=[];this.sdk=null;this.onSwitchAccount=async e=>{try{if(this.pnp)try{await this.pnp.disconnect()}catch{}this.walletConnected=!1,this.config={...this.config,actorProvider:void 0,connectedWallet:void 0},this.pendingAction="pay",this.showWalletModal=!0,this.requestUpdate();try{let t=Number(this.amountUsd||0),a=this.selectedSymbol||"ICP";window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"pay",type:"sendUsd",amount:t,currency:a}}))}catch{}}catch{}};this.onSelectBalanceSymbol=async e=>{let t=(this.walletBalances||[]).find(n=>n?.tokenShortcode===e);if(t?.ledgerSymbol&&(this.selectedSymbol=t.ledgerSymbol),this.showBalanceModal=!1,this.showWalletModal=!1,j(this.lastWalletId)){let n=(this.walletBalances||[]).find(s=>s?.tokenShortcode===e),i=n?.chainId;V(i,{provider:this.pnp?.getEvmProvider?.()||this.config?.evmProvider,chainName:n?.chainName,rpcUrlPublic:n?.rpcUrlPublic,nativeSymbol:n?.ledgerSymbol,decimals:n?.decimals}).then(async()=>{try{let s=E(this.config),o=Number(this.amountUsd||0);if(n?.x402Accepts&&!J(this.lastWalletId))try{await s.client.createPaymentX402Usd({usdAmount:o,tokenShortcode:n?.tokenShortcode,metadata:{...this.config?.metadata,icpay_network:"evm",icpay_ledger_id:n?.ledgerId,icpay_context:"amount-input:x402"},recipientAddress:(this.config?.recipientAddresses||{})?.evm||"0x0000000000000000000000000000000000000000",fiat_currency:this.config?.fiat_currency}),this.showBalanceModal=!1;return}catch(d){f(d,{onError:p=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:p,bubbles:!0})),w(p)&&(this.errorMessage=m(p),this.errorSeverity=v(p),this.errorAction=b(p))}})}await s.client.createPaymentUsd({usdAmount:o,tokenShortcode:n?.tokenShortcode,metadata:{...this.config?.metadata,icpay_network:"evm",icpay_ledger_id:n?.ledgerId},recipientAddress:(this.config?.recipientAddresses||{})?.evm||"0x0000000000000000000000000000000000000000"}).catch(d=>{throw d})}catch(s){f(s,{onError:o=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:o,bubbles:!0})),w(o)&&(this.errorMessage=m(o),this.errorSeverity=v(o),this.errorAction=b(o))}})}this.showBalanceModal=!1});return}let a=this.pendingAction;if(this.pendingAction=null,a==="pay")try{let n=(this.walletBalances||[]).find(u=>u?.tokenShortcode===e),i=E(this.config),s=Number(this.amountUsd||0),o=String(n?.ledgerName||n?.chainName||"").toLowerCase(),d=o.includes("sol"),p=o.includes("ic"),y=this.config?.recipientAddresses||{},h=d&&y.sol||y.ic;if(n?.x402Accepts)try{let u={...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:d?"sol":p?"ic":this.config?.icpay_network,icpay_ledger_id:n?.ledgerId,icpay_context:"amount-input:x402"}};await i.client.createPaymentX402Usd({usdAmount:s,tokenShortcode:n?.tokenShortcode,metadata:u,recipientAddress:h||"",fiat_currency:this.config?.fiat_currency});return}catch(u){f(u,{onError:g=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:g,bubbles:!0})),w(g)&&(this.errorMessage=m(g),this.errorSeverity=v(g),this.errorAction=b(g))}});return}await i.client.createPaymentUsd({usdAmount:s,tokenShortcode:n?.tokenShortcode,metadata:{...this.config?.metadata,icpay:{...(this.config?.metadata||{})?.icpay||{},icpay_network:"ic",icpay_ledger_id:n?.ledgerId}},recipientAddress:h||"0x0000000000000000000000000000000000000000"}).catch(u=>{throw u})}catch(n){f(n,{onError:i=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:i,bubbles:!0})),w(i)&&(this.errorMessage=m(i),this.errorSeverity=v(i),this.errorAction=b(i))}})}}}connectedCallback(){if(super.connectedCallback(),!!Qe){Xt(this.config?.debug||!1,"Amount input connected",{config:this.config}),this.amountUsd=Number(this.config?.defaultAmountUsd??0),this.hasUserAmount=!1;try{window.addEventListener("icpay-switch-account",this.onSwitchAccount)}catch{}try{window.addEventListener("icpay-sdk-transaction-created",(()=>{this.showWalletModal=!1,this.requestUpdate()}))}catch{}}}updated(e){if(e.has("config")&&(!this.hasUserAmount&&typeof this.config?.defaultAmountUsd=="number"&&(this.amountUsd===0||this.amountUsd==null||Number.isNaN(this.amountUsd))&&(this.amountUsd=Number(this.config.defaultAmountUsd)),this.pendingAction&&this.config?.actorProvider)){let t=this.pendingAction;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"external"}}))}catch{}this.walletModalStep!=="balances"&&(this.pendingAction=null,setTimeout(()=>{t==="pay"&&this.pay()},0))}}onInputChange(e){let t=Number(this.config?.stepUsd??.5),a=Math.max(0,Number(e.target.value||0)),n=Math.round(a/t)*t;this.amountUsd=Number(n.toFixed(2)),this.hasUserAmount=!0}selectSymbol(e){this.selectedSymbol=e}isValidAmount(){let e=Number(this.config?.minUsd??.5),t=this.config?.maxUsd!==void 0?Number(this.config.maxUsd):1/0;return this.amountUsd>=e&&this.amountUsd<=t}async getOrCreatePnp(){if(this.pnp)return this.pnp;$e||($e=(await import("./wallet-select-3A5Z7KZJ.js")).WalletSelect);let e=!!(this.config?.openOisyInNewTab||this.config?.plugNPlay?.openOisyInNewTab),t={...this.config?.plugNPlay||{}},a=this.config?.recipientAddresses;if(a&&(a.ic||a.evm||a.sol)){let i=[];a.ic&&i.push("ic"),a.evm&&i.push("evm"),a.sol&&i.push("sol"),i.length&&(t.chainTypes=i)}else this.config?.chainTypes&&(t.chainTypes=this.config.chainTypes);let n=e?O(t):t;try{if(typeof window<"u"){let{resolveDerivationOrigin:i}=await import("./origin-44ZEXSX4.js");n.derivationOrigin=this.config?.derivationOrigin||i()}}catch{}return this.pnp=new $e(n),this.pnp}async generateWalletConnectQr(e){try{let t=await this.getOrCreatePnp();return!t||typeof t.generateWalletConnectQr!="function"?null:await t.generateWalletConnectQr({onConnected:a=>{this.walletConnected=!0,this.lastWalletId="walletconnect";let n=x(this.pnp,a),i=this.pnp?.getEvmProvider?.(),s=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:n,actorProvider:(o,d)=>this.pnp.getActor({canisterId:o,idl:d,requiresSigning:!0,anon:!1}),...i?{evmProvider:i}:{},...s?{solanaProvider:s}:{}},this.sdk=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:"walletconnect"}}))}catch{}try{e?.onConnected?.()}catch{}this.requestUpdate()}})}catch{return null}}async checkCoinbaseConnection(){try{return(await this.getOrCreatePnp())?.hasCoinbaseAccounts?.()??!1}catch{return!1}}async connectWallet(e){let t=await this.getOrCreatePnp();if(!t||!e)throw new Error("Wallet not available");let a=(e||"").toLowerCase(),n=await t.connect(a);if(!!!(n&&(n.connected===!0||n.principal||n.owner||t.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0,this.lastWalletId=a;let s=x(this.pnp,n),o=this.pnp?.getEvmProvider?.(),d=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:s,actorProvider:(p,y)=>this.pnp.getActor({canisterId:p,idl:y,requiresSigning:!0,anon:!1}),...o?{evmProvider:o}:{},...d?{solanaProvider:d}:{}},this.sdk=null;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:a}}))}catch{}this.requestUpdate()}async ensureWallet(){if(this.config.useOwnWallet)return this.config.actorProvider?!0:(this.pendingAction="pay",this.dispatchEvent(new CustomEvent("icpay-connect-wallet",{bubbles:!0})),!1);if(this.walletConnected)return!0;try{if(!(await this.getOrCreatePnp()).getEnabledWallets()?.length)throw new Error("No wallets available");return this.pendingAction="pay",this.showWalletModal=!0,!1}catch(e){return this.errorMessage=e instanceof Error?e.message:"Wallet connection failed",this.errorSeverity="error",!1}}getWalletId(e){return e&&(e.id||e.provider||e.key)||""}getWalletLabel(e){return e&&(e.label||e.name||e.title||e.id)||"Wallet"}getWalletIcon(e){return e&&(e.icon||e.logo||e.image)||null}connectWithWallet(e){if(this.pnp)try{if(!e)throw new Error("No wallet ID provided");this.lastWalletId=(e||"").toLowerCase(),this.pnp.connect(e).then(a=>{if(!!!(a&&(a.connected===!0||a.principal||a.owner||this.pnp?.account)))throw new Error("Wallet connection was rejected");this.walletConnected=!0;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-connected",{detail:{walletType:e}}))}catch{}let i=x(this.pnp,a),s=this.pnp?.getEvmProvider?.(),o=this.pnp?.getSolanaProvider?.();this.config={...this.config,connectedWallet:i,actorProvider:(d,p)=>this.pnp.getActor({canisterId:d,idl:p,requiresSigning:!0,anon:!1}),...s?{evmProvider:s}:{},...o?{solanaProvider:o}:{}},this.sdk=null,this.walletModalStep="balances",this.showBalanceModal=!1,this.showWalletModal=!0,this.fetchAndShowBalances()}).catch(a=>{this.errorMessage=a instanceof Error?a.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-error",{detail:{message:this.errorMessage,code:"WALLET_CONNECT_ERROR"}}))}catch{}})}catch(t){this.errorMessage=t instanceof Error?t.message:"Wallet connection failed",this.errorSeverity="error",this.showWalletModal=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-error",{detail:{message:this.errorMessage,code:"WALLET_CONNECT_ERROR"}}))}catch{}}}async fetchAndShowBalances(){try{this.balancesLoading=!0,this.balancesError=null,this.walletModalStep="balances",this.showBalanceModal=!1;let e=E(this.config),{balances:t}=await Y({sdk:e,lastWalletId:this.lastWalletId,connectedWallet:this.config?.connectedWallet,amountUsd:Number(this.amountUsd??0),fiatCurrency:this.config?.fiat_currency,chainShortcodes:this.config?.chainShortcodes,tokenShortcodes:this.config?.tokenShortcodes});this.walletBalances=t}catch(e){this.walletBalances=[],this.balancesError=e&&(e.message||String(e))||"Failed to load balances"}finally{this.balancesLoading=!1}}attachTransakMessageListener(){if(!this.transakMessageHandlerBound){this.transakMessageHandlerBound=e=>this.onTransakMessage(e);try{window.addEventListener("message",this.transakMessageHandlerBound)}catch{}}}detachTransakMessageListener(){if(this.transakMessageHandlerBound){try{window.removeEventListener("message",this.transakMessageHandlerBound)}catch{}this.transakMessageHandlerBound=null}}onTransakMessage(e){let t=e?.data,a=t?.event_id||t?.eventId||t?.id;if(!(!a||typeof a!="string")&&a==="TRANSAK_ORDER_SUCCESSFUL"){if(this.detachTransakMessageListener(),this.onrampPollingActive)return;this.showOnrampModal=!1;let n=t?.data?.id||t?.id||t?.webhookData?.id||null;this.startOnrampPolling(n||void 0)}}startOnramp(){try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"createPaymentUsd",type:"onramp"}}))}catch{}this.showWalletModal=!1,setTimeout(()=>this.createOnrampIntent(),0)}async createOnrampIntent(){try{let e=E(this.config),t=Number(this.amountUsd),a=await e.startOnrampUsd(t,void 0,{context:"amount-input:onramp",onrampPayment:!0,onrampProvider:this?.selectedOnrampProvider||"coinbase"}),n=a?.metadata?.onramp?.url||a?.onramp?.url||a?.metadata?.icpay_onramp?.url||a?.paymentIntent?.metadata?.icpay?.onrampUrl||a?.metadata?.icpay?.onrampUrl||null,i=a?.metadata?.icpay_payment_intent_id||a?.metadata?.paymentIntentId||a?.paymentIntentId||null,s=a?.metadata?.icpay_onramp?.errorMessage||a?.metadata?.onramp?.errorMessage||null;if(this.onrampPaymentIntentId=i,n){this.onrampUrl=n,this.onrampErrorMessage=null;try{window.open(n,"icpay_onramp","noopener,noreferrer");try{window.dispatchEvent(new CustomEvent("icpay-onramp-opened",{detail:{url:n}}))}catch{}}catch{}this.startOnrampPolling()}else this.onrampUrl=null,this.onrampErrorMessage=s||"Failed to obtain onramp sessionId",this.showOnrampModal=!0}catch(e){this.onrampUrl=null,this.onrampErrorMessage=e?.message||"Failed to obtain onramp sessionId",this.showOnrampModal=!0}}startOnrampPolling(e){if(this.onrampPollTimer){try{clearInterval(this.onrampPollTimer)}catch{}this.onrampPollTimer=null}if(this.onrampNotifyController){try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null}let t=this.onrampPaymentIntentId;if(!t)return;let a=E(this.config),n=()=>{if(this.detachTransakMessageListener(),this.onrampNotifyController)try{this.onrampNotifyController.stop()}catch{}this.onrampNotifyController=null,this.onrampPollingActive=!1};try{window.addEventListener("icpay-sdk-transaction-completed",(()=>n()),{once:!0})}catch{}this.onrampPollingActive=!0,this.onrampNotifyController=a.notifyIntentUntilComplete(t,5e3,e),this.onrampPollTimer=1}resetPaymentFlow(){ee(this,{pendingAction:"pay"})}async pay(){if(Qe){if(this.resetPaymentFlow(),!this.isValidAmount()){this.errorMessage="Please enter a valid amount",this.errorSeverity="warning";return}try{window.dispatchEvent(new CustomEvent("icpay-sdk-method-start",{detail:{name:"pay",type:"sendUsd",amount:this.amountUsd,currency:this.selectedSymbol||"ICP"}}))}catch{}this.processing=!0;try{if(!await this.ensureWallet())return;this.showWalletModal=!0,await this.fetchAndShowBalances();return}catch(e){f(e,{onError:t=>{this.dispatchEvent(new CustomEvent("icpay-error",{detail:t,bubbles:!0})),w(t)&&(this.errorMessage=m(t),this.errorSeverity=v(t),this.errorAction=b(t))}});try{!this.config.useOwnWallet&&this.pnp&&(await this.pnp.disconnect?.(),this.walletConnected=!1,this.config={...this.config,actorProvider:void 0,connectedWallet:void 0})}catch{}}finally{this.processing=!1}}}render(){if(!this.config)return xe`<div class="icpay-card icpay-section">Loading...</div>`;let e=this.config?.placeholder||"Enter amount in USD",a=(this.config?.buttonLabel||"Pay with crypto").replace("{amount}",this.amountUsd?`${Number(this.amountUsd).toFixed(2)}`:"$0.00").replace("{symbol}",this.selectedSymbol||"ICP"),n=this.selectedSymbol||"ICP",s=this.config?.progressBar?.enabled!==!1;return xe`
2048
2048
  <div class="icpay-card icpay-section icpay-widget-base">
2049
- ${o?be`
2049
+ ${s?xe`
2050
2050
  <icpay-progress-bar
2051
2051
  .debug=${!!this.config?.debug}
2052
2052
  .theme=${this.config?.theme}
@@ -2059,36 +2059,36 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
2059
2059
  <div class="top-row">
2060
2060
  <div class="amount-field">
2061
2061
  <span class="currency-prefix">$</span>
2062
- <input type="number" min="0" step="${Number(this.config?.stepUsd??.5)}" .value=${String(this.amountUsd||"")} placeholder="${e}" @input=${c=>this.onInputChange(c)} />
2062
+ <input type="number" min="0" step="${Number(this.config?.stepUsd??.5)}" .value=${String(this.amountUsd||"")} placeholder="${e}" @input=${o=>this.onInputChange(o)} />
2063
2063
  </div>
2064
2064
  ${null}
2065
2065
  </div>
2066
2066
  <button class="pay-button ${this.processing?"processing":""}"
2067
2067
  ?disabled=${this.processing||this.config?.disablePaymentButton===!0||this.succeeded&&this.config?.disableAfterSuccess===!0}
2068
2068
  @click=${()=>this.pay()}>
2069
- ${this.succeeded&&this.config?.disableAfterSuccess?"Paid":this.processing?"Processing\u2026":n}
2069
+ ${this.succeeded&&this.config?.disableAfterSuccess?"Paid":this.processing?"Processing\u2026":a}
2070
2070
  </button>
2071
2071
  </div>
2072
2072
  <div class="hint">Min: $${Number(this.config?.minUsd??.5).toFixed(2)}${this.config?.maxUsd?`, Max: $${Number(this.config.maxUsd).toFixed(2)}`:""}</div>
2073
2073
 
2074
- ${this.errorMessage?be`
2074
+ ${this.errorMessage?xe`
2075
2075
  <div class="error-message ${this.errorSeverity}" style="margin-top: 12px; padding: 8px 12px; border-radius: 6px; font-size: 14px; text-align: center;">
2076
2076
  ${this.errorMessage}
2077
- ${this.errorAction?be`<button style="margin-left: 8px; padding: 4px 8px; background: transparent; border: 1px solid currentColor; border-radius: 4px; font-size: 12px; cursor: pointer;">${this.errorAction}</button>`:""}
2077
+ ${this.errorAction?xe`<button style="margin-left: 8px; padding: 4px 8px; background: transparent; border: 1px solid currentColor; border-radius: 4px; font-size: 12px; cursor: pointer;">${this.errorAction}</button>`:""}
2078
2078
  </div>
2079
2079
  `:""}
2080
- ${(()=>{let c=this.pnp?.getEnabledWallets?.()||[],d=V(c),p=this.config?.theme?typeof this.config.theme=="string"?this.config.theme:this.config.theme.mode||"light":void 0;return Q({visible:!!(this.showWalletModal&&this.pnp),wallets:d,isConnecting:!1,step:this.walletModalStep,balances:this.walletModalStep==="balances"?this.walletBalances:[],balancesLoading:this.walletModalStep==="balances"?this.balancesLoading:!1,balancesError:this.walletModalStep==="balances"?this.balancesError:null,onSelectBalance:y=>this.onSelectBalanceSymbol(y),onBack:()=>{this.walletModalStep="connect"},onSwitchAccount:()=>this.onSwitchAccount(null),onSelect:y=>this.connectWithWallet(y),onClose:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-cancelled",{detail:{reason:"user_cancelled"}}))}catch{}},onDismiss:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1},onCreditCard:this.config?.onramp?.enabled===!0&&this.config?.onrampDisabled!==!0?()=>this.startOnramp():void 0,creditCardLabel:this.config?.onramp?.creditCardLabel||"Pay with credit card",showCreditCard:this.config?.onramp?.enabled===!0&&this.config?.onrampDisabled!==!0,creditCardTooltip:(()=>{let h=Number(this.amountUsd||0);return h>0&&h<5&&this.config?.onramp?.enabled===!0&&this.config?.onrampDisabled!==!0?`Note: Minimum card amount is $5. You will pay about $${(5-h).toFixed(2)} more.`:null})(),oisyReadyToPay:this.oisyReadyToPay,onOisyPay:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1,this.pay()},theme:p})})()}
2080
+ ${(()=>{let o=this.pnp?.getEnabledWallets?.()||[],d=X(o),p=this.config?.theme?typeof this.config.theme=="string"?this.config.theme:this.config.theme.mode||"light":void 0;return Q({visible:!!(this.showWalletModal&&this.pnp),wallets:d,isConnecting:!1,step:this.walletModalStep,balances:this.walletModalStep==="balances"?this.walletBalances:[],balancesLoading:this.walletModalStep==="balances"?this.balancesLoading:!1,balancesError:this.walletModalStep==="balances"?this.balancesError:null,onSelectBalance:y=>this.onSelectBalanceSymbol(y),onBack:()=>{this.walletModalStep="connect"},onSwitchAccount:()=>this.onSwitchAccount(null),onSelect:y=>this.connectWithWallet(y),onClose:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1;try{window.dispatchEvent(new CustomEvent("icpay-sdk-wallet-cancelled",{detail:{reason:"user_cancelled"}}))}catch{}},onDismiss:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1},onCreditCard:this.config?.onramp?.enabled===!0&&this.config?.onrampDisabled!==!0?()=>this.startOnramp():void 0,creditCardLabel:this.config?.onramp?.creditCardLabel||"Pay with credit card",showCreditCard:this.config?.onramp?.enabled===!0&&this.config?.onrampDisabled!==!0,creditCardTooltip:(()=>{let h=Number(this.amountUsd||0);return h>0&&h<5&&this.config?.onramp?.enabled===!0&&this.config?.onrampDisabled!==!0?`Note: Minimum card amount is $5. You will pay about $${(5-h).toFixed(2)} more.`:null})(),oisyReadyToPay:this.oisyReadyToPay,onOisyPay:()=>{this.showWalletModal=!1,this.oisyReadyToPay=!1,this.pay()},theme:p})})()}
2081
2081
 
2082
- ${(()=>{let c=this.config?.theme?typeof this.config.theme=="string"?this.config.theme:this.config.theme.mode||"light":void 0;return be`
2083
- ${Z({visible:this.showBalanceModal,isLoading:this.balancesLoading,error:this.balancesError,balances:this.walletBalances,onSelect:d=>this.onSelectBalanceSymbol(d),onClose:()=>{this.showBalanceModal=!1},theme:c})}
2082
+ ${(()=>{let o=this.config?.theme?typeof this.config.theme=="string"?this.config.theme:this.config.theme.mode||"light":void 0;return xe`
2083
+ ${Z({visible:this.showBalanceModal,isLoading:this.balancesLoading,error:this.balancesError,balances:this.walletBalances,onSelect:d=>this.onSelectBalanceSymbol(d),onClose:()=>{this.showBalanceModal=!1},theme:o})}
2084
2084
 
2085
- ${H({visible:this.showOnrampModal,url:this.onrampUrl||void 0,errorMessage:this.onrampErrorMessage||void 0,width:this.config?.onramp?.width,height:this.config?.onramp?.height,onClose:()=>{this.showOnrampModal=!1},onBack:()=>{this.showOnrampModal=!1,this.showWalletModal=!0},title:"Pay with credit card",theme:c})}
2085
+ ${H({visible:this.showOnrampModal,url:this.onrampUrl||void 0,errorMessage:this.onrampErrorMessage||void 0,width:this.config?.onramp?.width,height:this.config?.onramp?.height,onClose:()=>{this.showOnrampModal=!1},onBack:()=>{this.showOnrampModal=!1,this.showWalletModal=!0},title:"Pay with credit card",theme:o})}
2086
2086
  `})()}
2087
2087
  <div class="icpay-powered-by">
2088
2088
  <a href="https://icpay.org" target="_blank" rel="noopener noreferrer">Powered by icpay</a>
2089
2089
  </div>
2090
2090
  </div>
2091
- `}};P.styles=[K,jt`
2091
+ `}};T.styles=[K,jt`
2092
2092
  .row { display: grid; grid-template-columns: 1fr; gap: 12px; align-items: stretch; }
2093
2093
  .top-row { display: grid; grid-template-columns: 1fr; gap: 10px; align-items: center; }
2094
2094
  .top-row.with-selector { grid-template-columns: 1fr 2fr; }
@@ -2108,5 +2108,5 @@ import{a as s}from"./chunk-LTEQ7OUJ.js";import{css as Ze}from"lit";var K=Ze`
2108
2108
  @media (max-width: 520px) {
2109
2109
  .top-row { grid-template-columns: 1fr; }
2110
2110
  }
2111
- `],s([Ht({type:Object})],P.prototype,"config",2),s([_()],P.prototype,"amountUsd",2),s([_()],P.prototype,"hasUserAmount",2),s([_()],P.prototype,"selectedSymbol",2),s([_()],P.prototype,"processing",2),s([_()],P.prototype,"succeeded",2),s([_()],P.prototype,"errorMessage",2),s([_()],P.prototype,"errorSeverity",2),s([_()],P.prototype,"errorAction",2),s([_()],P.prototype,"walletConnected",2),s([_()],P.prototype,"pendingAction",2),s([_()],P.prototype,"showWalletModal",2),s([_()],P.prototype,"walletModalStep",2),s([_()],P.prototype,"showOnrampModal",2),s([_()],P.prototype,"onrampUrl",2),s([_()],P.prototype,"onrampPaymentIntentId",2),s([_()],P.prototype,"onrampErrorMessage",2),s([_()],P.prototype,"oisyReadyToPay",2),s([_()],P.prototype,"lastWalletId",2),s([_()],P.prototype,"showBalanceModal",2),s([_()],P.prototype,"balancesLoading",2),s([_()],P.prototype,"balancesError",2),s([_()],P.prototype,"walletBalances",2),P=s([Kt("icpay-amount-input")],P);export{K as a,Yt as b,ge as c,E as d,H as e,T as f,W as g,C as h,L as i,A as j,k,P as l};
2112
- //# sourceMappingURL=chunk-RCWWBMN4.js.map
2111
+ `],c([Ht({type:Object})],T.prototype,"config",2),c([B()],T.prototype,"amountUsd",2),c([B()],T.prototype,"hasUserAmount",2),c([B()],T.prototype,"selectedSymbol",2),c([B()],T.prototype,"processing",2),c([B()],T.prototype,"succeeded",2),c([B()],T.prototype,"errorMessage",2),c([B()],T.prototype,"errorSeverity",2),c([B()],T.prototype,"errorAction",2),c([B()],T.prototype,"walletConnected",2),c([B()],T.prototype,"pendingAction",2),c([B()],T.prototype,"showWalletModal",2),c([B()],T.prototype,"walletModalStep",2),c([B()],T.prototype,"showOnrampModal",2),c([B()],T.prototype,"onrampUrl",2),c([B()],T.prototype,"onrampPaymentIntentId",2),c([B()],T.prototype,"onrampErrorMessage",2),c([B()],T.prototype,"oisyReadyToPay",2),c([B()],T.prototype,"lastWalletId",2),c([B()],T.prototype,"showBalanceModal",2),c([B()],T.prototype,"balancesLoading",2),c([B()],T.prototype,"balancesError",2),c([B()],T.prototype,"walletBalances",2),T=c([Kt("icpay-amount-input")],T);export{K as a,Yt as b,fe as c,E as d,H as e,I as f,A as g,C as h,L as i,P as j,k,T as l};
2112
+ //# sourceMappingURL=chunk-V4GOXE2A.js.map