spaark-payapi-sdk 1.6.0 → 1.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
- import {z}from'zod';import fe from'axios';import {createHmac,timingSafeEqual}from'crypto';import {v4,validate,version}from'uuid';import {useState,useCallback}from'react';import {jsxs,jsx}from'react/jsx-runtime';var I={timeout:3e4,retries:3,retryDelay:1e3,logLevel:"info",sandboxUrl:"https://api.sandbox.pawapay.io",productionUrl:"https://api.pawapay.io"};var N={VALIDATION_ERROR:"VALIDATION_ERROR",INVALID_PHONE:"INVALID_PHONE",INSUFFICIENT_FUNDS:"INSUFFICIENT_FUNDS",AMOUNT_TOO_LOW:"AMOUNT_TOO_LOW",AMOUNT_TOO_HIGH:"AMOUNT_TOO_HIGH",LIMIT_EXCEEDED:"LIMIT_EXCEEDED",DUPLICATE:"DUPLICATE",MMO_UNAVAILABLE:"MMO_UNAVAILABLE",TIMEOUT:"TIMEOUT",UNAUTHORIZED:"UNAUTHORIZED",RATE_LIMITED:"RATE_LIMITED",SERVER_ERROR:"SERVER_ERROR",NETWORK_ERROR:"NETWORK_ERROR",NOT_FOUND:"NOT_FOUND",REFUND_NOT_ALLOWED:"REFUND_NOT_ALLOWED"},Nt=[{pawapayCode:"INVALID_PHONE_NUMBER",sdkCode:N.INVALID_PHONE,httpStatus:400,retryable:false,message:"Invalid phone number format"},{pawapayCode:"INSUFFICIENT_FUNDS",sdkCode:N.INSUFFICIENT_FUNDS,httpStatus:402,retryable:false,message:"Insufficient funds in account"},{pawapayCode:"AMOUNT_TOO_LOW",sdkCode:N.AMOUNT_TOO_LOW,httpStatus:400,retryable:false,message:"Amount below minimum"},{pawapayCode:"AMOUNT_TOO_HIGH",sdkCode:N.AMOUNT_TOO_HIGH,httpStatus:400,retryable:false,message:"Amount exceeds maximum"},{pawapayCode:"TRANSACTION_LIMIT_EXCEEDED",sdkCode:N.LIMIT_EXCEEDED,httpStatus:400,retryable:false,message:"Daily or monthly limit exceeded"},{pawapayCode:"DUPLICATE_TRANSACTION",sdkCode:N.DUPLICATE,httpStatus:409,retryable:false,message:"Transaction ID already used"},{pawapayCode:"CORRESPONDENT_UNAVAILABLE",sdkCode:N.MMO_UNAVAILABLE,httpStatus:503,retryable:true,message:"Mobile Money operator temporarily unavailable"},{pawapayCode:"CORRESPONDENT_TEMPORARILY_UNAVAILABLE",sdkCode:N.MMO_UNAVAILABLE,httpStatus:503,retryable:true,message:"Mobile Money operator temporarily unavailable"},{pawapayCode:"TIMEOUT",sdkCode:N.TIMEOUT,httpStatus:408,retryable:true,message:"Transaction timed out"},{pawapayCode:"INVALID_API_KEY",sdkCode:N.UNAUTHORIZED,httpStatus:401,retryable:false,message:"Invalid or expired API key"},{pawapayCode:"RATE_LIMIT_EXCEEDED",sdkCode:N.RATE_LIMITED,httpStatus:429,retryable:true,message:"Too many requests"},{pawapayCode:"INTERNAL_ERROR",sdkCode:N.SERVER_ERROR,httpStatus:500,retryable:true,message:"Pawapay internal error"},{pawapayCode:"REFUND_NOT_ALLOWED",sdkCode:N.REFUND_NOT_ALLOWED,httpStatus:400,retryable:false,message:"Refund not allowed for this transaction"}];function Ue(i){return Nt.find(e=>e.pawapayCode===i)}var p=class i extends Error{constructor(e,t,n,a){super(e),this.name="PawapayError",this.code=t,this.statusCode=n,this.failureReason=a?.failureReason,this.retryable=a?.retryable??false,this.originalError=a?.originalError,Error.captureStackTrace&&Error.captureStackTrace(this,i);}static fromPawapayResponse(e,t,n){let a=Ue(e);return a?new i(t??a.message,a.sdkCode,a.httpStatus,{retryable:a.retryable,originalError:n}):new i(t??"Unknown error occurred",N.SERVER_ERROR,500,{retryable:false,originalError:n})}static validation(e){return new i(e,N.VALIDATION_ERROR,400,{retryable:false})}static network(e,t){return new i(e,N.NETWORK_ERROR,0,{retryable:true,originalError:t})}static timeout(e="Request timed out"){return new i(e,N.TIMEOUT,408,{retryable:true})}static unauthorized(e="Invalid or expired API key"){return new i(e,N.UNAUTHORIZED,401,{retryable:false})}static notFound(e="Resource not found"){return new i(e,N.NOT_FOUND,404,{retryable:false})}toJSON(){return {name:this.name,message:this.message,code:this.code,statusCode:this.statusCode,failureReason:this.failureReason,retryable:this.retryable}}};var Ct=z.object({apiKey:z.string().min(1,"API key is required"),environment:z.enum(["sandbox","production"]),baseUrl:z.string().url().optional(),callbackUrl:z.string().url().optional(),timeout:z.number().positive().max(6e5).optional(),retries:z.number().int().min(0).max(10).optional(),retryDelay:z.number().positive().max(6e4).optional(),logLevel:z.enum(["debug","info","warn","error","none"]).optional()});function Fe(i){let e=Ct.safeParse(i);if(!e.success){let a=e.error.errors.map(d=>`${d.path.join(".")}: ${d.message}`);throw p.validation(`Invalid SDK configuration: ${a.join(", ")}`)}let t=e.data,n=t.baseUrl??(t.environment==="production"?I.productionUrl:I.sandboxUrl);return {apiKey:t.apiKey,environment:t.environment,baseUrl:n,callbackUrl:t.callbackUrl,timeout:t.timeout??I.timeout,retries:t.retries??I.retries,retryDelay:t.retryDelay??I.retryDelay,logLevel:t.logLevel??I.logLevel}}function We(){let i=typeof process<"u"?process.env:{},e={};if(i.PAWAPAY_API_KEY&&(e.apiKey=i.PAWAPAY_API_KEY),i.PAWAPAY_ENVIRONMENT){let t=i.PAWAPAY_ENVIRONMENT.toLowerCase();(t==="production"||t==="sandbox")&&(e.environment=t);}if(i.PAWAPAY_BASE_URL&&(e.baseUrl=i.PAWAPAY_BASE_URL),i.PAWAPAY_CALLBACK_URL&&(e.callbackUrl=i.PAWAPAY_CALLBACK_URL),i.PAWAPAY_TIMEOUT){let t=parseInt(i.PAWAPAY_TIMEOUT,10);isNaN(t)||(e.timeout=t);}if(i.PAWAPAY_RETRIES){let t=parseInt(i.PAWAPAY_RETRIES,10);isNaN(t)||(e.retries=t);}if(i.PAWAPAY_LOG_LEVEL){let t=i.PAWAPAY_LOG_LEVEL.toLowerCase();["debug","info","warn","error","none"].includes(t)&&(e.logLevel=t);}return e}var Rt={maxAttempts:3,initialDelay:1e3,maxDelay:3e4,backoffMultiplier:2};function wt(i){return new Promise(e=>setTimeout(e,i))}function Et(i,e){let t=e.initialDelay*Math.pow(e.backoffMultiplier,i-1),n=Math.random()*.3*t;return Math.min(t+n,e.maxDelay)}async function B(i,e={},t){let n={...Rt,...e},a;for(let d=1;d<=n.maxAttempts;d++)try{return await i()}catch(y){if(a=y instanceof Error?y:new Error(String(y)),!(y instanceof p?y.retryable:kt(y))||d===n.maxAttempts)throw y;let l=Et(d,n);t?.warn(`Attempt ${d}/${n.maxAttempts} failed, retrying in ${Math.round(l)}ms`,{error:a.message}),await wt(l);}throw a??new Error("Retry failed without error")}function kt(i){return i instanceof p?i.retryable:i instanceof Error?["ECONNRESET","ECONNREFUSED","ETIMEDOUT","ENOTFOUND","Network Error","timeout","socket hang up"].some(t=>i.message.includes(t)||i.code===t):false}var Y=class i{constructor(e){this.logger=e.logger,this.retries=e.retries,this.retryDelay=e.retryDelay,this.client=fe.create({baseURL:e.baseUrl,timeout:e.timeout,headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`}}),this.setupInterceptors();}setupInterceptors(){this.client.interceptors.request.use(e=>(this.logger.debug(`${e.method?.toUpperCase()} ${e.url}`,{params:e.params}),e),e=>(this.logger.error("Request error",e),Promise.reject(e))),this.client.interceptors.response.use(e=>(this.logger.debug(`${e.config.method?.toUpperCase()} ${e.config.url} -> ${e.status}`,{data:e.data}),e),e=>(fe.isAxiosError(e)&&this.logger.error(`Request failed: ${e.config?.method?.toUpperCase()} ${e.config?.url}`,{status:e.response?.status,data:e.response?.data}),Promise.reject(e)));}handleError(e){if(fe.isAxiosError(e)){if(e.code==="ECONNABORTED"||e.message.includes("timeout"))throw p.timeout();if(!e.response)throw p.network(e.message||"Network error",e);let{status:t,data:n}=e.response,a=n;if(t===401)throw p.unauthorized();if(t===404)throw p.notFound();let d=a?.errorCode??a?.rejectionReason?.rejectionCode;throw d?p.fromPawapayResponse(d,a?.errorMessage??a?.rejectionReason?.rejectionMessage,e):new p(a?.errorMessage??`HTTP error ${t}`,"SERVER_ERROR",t,{retryable:t>=500,originalError:e})}throw e instanceof p?e:p.network(e instanceof Error?e.message:"Unknown error",e instanceof Error?e:void 0)}async get(e,t){return B(async()=>{try{return (await this.client.get(e,t)).data}catch(n){this.handleError(n);}},{maxAttempts:this.retries,initialDelay:this.retryDelay},this.logger)}async post(e,t,n){return B(async()=>{try{return (await this.client.post(e,t,n)).data}catch(a){this.handleError(a);}},{maxAttempts:this.retries,initialDelay:this.retryDelay},this.logger)}async put(e,t,n){return B(async()=>{try{return (await this.client.put(e,t,n)).data}catch(a){this.handleError(a);}},{maxAttempts:this.retries,initialDelay:this.retryDelay},this.logger)}async delete(e,t){return B(async()=>{try{return (await this.client.delete(e,t)).data}catch(n){this.handleError(n);}},{maxAttempts:this.retries,initialDelay:this.retryDelay},this.logger)}static fromConfig(e,t){return new i({baseUrl:e.baseUrl,apiKey:e.apiKey,timeout:e.timeout,retries:e.retries,retryDelay:e.retryDelay,logger:t})}};var je={debug:0,info:1,warn:2,error:3,none:4},q=class{constructor(e,t="info"){this.prefix=e,this.level=t;}setLevel(e){this.level=e;}shouldLog(e){return je[e]>=je[this.level]}formatMessage(e,t){return `[${new Date().toISOString()}] ${e.toUpperCase().padEnd(5)} [${this.prefix}] ${t}`}sanitize(e){if(e==null||typeof e=="string"||typeof e!="object")return e;if(Array.isArray(e))return e.map(a=>this.sanitize(a));let t={},n=["apiKey","api_key","authorization","password","secret","token"];for(let[a,d]of Object.entries(e))n.some(y=>a.toLowerCase().includes(y))?t[a]="[REDACTED]":typeof d=="object"&&d!==null?t[a]=this.sanitize(d):t[a]=d;return t}debug(e,t){if(this.shouldLog("debug")){let n=this.formatMessage("debug",e);t!==void 0?console.debug(n,this.sanitize(t)):console.debug(n);}}info(e,t){if(this.shouldLog("info")){let n=this.formatMessage("info",e);t!==void 0?console.info(n,this.sanitize(t)):console.info(n);}}warn(e,t){if(this.shouldLog("warn")){let n=this.formatMessage("warn",e);t!==void 0?console.warn(n,this.sanitize(t)):console.warn(n);}}error(e,t){if(this.shouldLog("error")){let n=this.formatMessage("error",e);t!==void 0?console.error(n,this.sanitize(t)):console.error(n);}}};var $=["MTN_MOMO_CMR","ORANGE_CMR","MTN_MOMO_COG","AIRTEL_COG","MTN_MOMO_GAB","AIRTEL_GAB"],G={MTN_MOMO_CMR:{correspondent:"MTN_MOMO_CMR",name:"MTN Mobile Money",country:"Cameroon",countryCode:"CMR",currency:"XAF",features:["deposit","payout","refund"],phoneRegex:/^237(67|68|65[0-4])\d{6}$/},ORANGE_CMR:{correspondent:"ORANGE_CMR",name:"Orange Money",country:"Cameroon",countryCode:"CMR",currency:"XAF",features:["deposit","payout","refund"],phoneRegex:/^237(69|65[5-9])\d{6}$/},MTN_MOMO_COG:{correspondent:"MTN_MOMO_COG",name:"MTN Mobile Money",country:"Congo",countryCode:"COG",currency:"XAF",features:["deposit","payout","refund"],phoneRegex:/^242(04|05|06)\d{7}$/},AIRTEL_COG:{correspondent:"AIRTEL_COG",name:"Airtel Money",country:"Congo",countryCode:"COG",currency:"XAF",features:["deposit","payout"],phoneRegex:/^242(01|02|03)\d{7}$/},MTN_MOMO_GAB:{correspondent:"MTN_MOMO_GAB",name:"MTN Mobile Money",country:"Gabon",countryCode:"GAB",currency:"XAF",features:["deposit","payout","refund"],phoneRegex:/^241(06|07)\d{6}$/},AIRTEL_GAB:{correspondent:"AIRTEL_GAB",name:"Airtel Money",country:"Gabon",countryCode:"GAB",currency:"XAF",features:["deposit","payout"],phoneRegex:/^241(04|05)\d{6}$/}},J={MTN_MOMO_CMR:{minDeposit:100,maxDeposit:1e6,minPayout:500,maxPayout:5e5,currency:"XAF",dailyLimit:2e6},ORANGE_CMR:{minDeposit:100,maxDeposit:1e6,minPayout:500,maxPayout:5e5,currency:"XAF",dailyLimit:2e6},MTN_MOMO_COG:{minDeposit:100,maxDeposit:5e5,minPayout:500,maxPayout:3e5,currency:"XAF",dailyLimit:1e6},AIRTEL_COG:{minDeposit:100,maxDeposit:5e5,minPayout:500,maxPayout:3e5,currency:"XAF",dailyLimit:1e6},MTN_MOMO_GAB:{minDeposit:100,maxDeposit:5e5,minPayout:500,maxPayout:3e5,currency:"XAF",dailyLimit:1e6},AIRTEL_GAB:{minDeposit:100,maxDeposit:5e5,minPayout:500,maxPayout:3e5,currency:"XAF",dailyLimit:1e6}};var Pt=z.object({amount:z.number().positive("Amount must be positive").max(1e7),currency:z.string().min(3).max(3),provider:z.enum($),phoneNumber:z.string().regex(/^[0-9]{9,15}$/,"Phone number must be 9-15 digits"),transactionId:z.string().uuid(),preAuthorisationCode:z.string().optional(),clientReferenceId:z.string().optional(),customerMessage:z.string().min(4).max(22).optional(),metadata:z.array(z.record(z.unknown())).max(10).optional()}),Tt=z.object({amount:z.number().positive("Amount must be positive").max(1e7),currency:z.string().min(3).max(3),provider:z.enum($),phoneNumber:z.string().regex(/^[0-9]{9,15}$/,"Phone number must be 9-15 digits"),transactionId:z.string().uuid(),clientReferenceId:z.string().optional(),customerMessage:z.string().min(4).max(22).optional(),metadata:z.array(z.record(z.unknown())).max(10).optional()}),At=z.object({depositId:z.string().uuid(),returnUrl:z.string().url(),phoneNumber:z.string().optional(),amountDetails:z.object({amount:z.number().positive(),currency:z.string().length(3)}).optional(),language:z.enum(["EN","FR"]).optional(),country:z.string().length(3).optional(),reason:z.string().max(50).optional(),customerMessage:z.string().min(4).max(22).optional(),metadata:z.array(z.record(z.unknown())).max(10).optional()}),St=z.object({depositId:z.string().uuid(),amount:z.number().positive("Amount must be positive"),transactionId:z.string().uuid()});function Ot(i){return new Promise(e=>setTimeout(e,i))}var Z=class{constructor(e,t){this.httpClient=e;this.logger=t;}async initiateDeposit(e){let t=Pt.parse(e),n={depositId:t.transactionId,amount:t.amount.toString(),currency:t.currency,payer:{type:"MMO",accountDetails:{phoneNumber:t.phoneNumber,provider:t.provider}},preAuthorisationCode:t.preAuthorisationCode,clientReferenceId:t.clientReferenceId,customerMessage:t.customerMessage,metadata:t.metadata};this.logger.info(`Initiating V2 deposit ${t.transactionId}`,{amount:t.amount,currency:t.currency,provider:t.provider});let a=await this.httpClient.post("/v2/deposits",n);if(a.status==="REJECTED"&&a.rejectionReason)throw p.fromPawapayResponse(a.rejectionReason.rejectionCode,a.rejectionReason.rejectionMessage);return this.logger.info(`Deposit ${a.depositId} status: ${a.status}`),{depositId:a.depositId,status:a.status,created:a.created??new Date().toISOString(),nextStep:a.nextStep,redirectUrl:a.redirectUrl}}async initiatePayout(e){let t=Tt.parse(e),n={payoutId:t.transactionId,amount:t.amount.toString(),currency:t.currency,recipient:{type:"MMO",accountDetails:{phoneNumber:t.phoneNumber,provider:t.provider}},clientReferenceId:t.clientReferenceId,customerMessage:t.customerMessage,metadata:t.metadata};this.logger.info(`Initiating V2 payout ${t.transactionId}`,{amount:t.amount,currency:t.currency,provider:t.provider});let a=await this.httpClient.post("/v2/payouts",n);if(a.status==="REJECTED"&&a.rejectionReason)throw p.fromPawapayResponse(a.rejectionReason.rejectionCode,a.rejectionReason.rejectionMessage);return this.logger.info(`Payout ${a.payoutId} status: ${a.status}`),{payoutId:a.payoutId,status:a.status,created:a.created??new Date().toISOString()}}async createPaymentPage(e){let t=At.parse(e),n={depositId:t.depositId,returnUrl:t.returnUrl,phoneNumber:t.phoneNumber,amountDetails:t.amountDetails?{amount:t.amountDetails.amount.toString(),currency:t.amountDetails.currency}:void 0,language:t.language,country:t.country,reason:t.reason,customerMessage:t.customerMessage,metadata:t.metadata};this.logger.info(`Creating payment page for deposit ${t.depositId}`);let a=await this.httpClient.post("/v2/paymentpage",n);return this.logger.info(`Payment page created: ${a.redirectUrl}`),{redirectUrl:a.redirectUrl}}async refund(e){let t=St.parse(e),n={refundId:t.transactionId,depositId:t.depositId,amount:t.amount.toString()};this.logger.info(`Initiating refund ${t.transactionId}`,{depositId:t.depositId,amount:t.amount});let a=await this.httpClient.post("/refunds",n);if(a.status==="REJECTED"&&a.rejectionReason)throw p.fromPawapayResponse(a.rejectionReason.rejectionCode,a.rejectionReason.rejectionMessage);return this.logger.info(`Refund ${a.refundId} status: ${a.status}`),{refundId:a.refundId,depositId:t.depositId,status:a.status,amount:t.amount,created:a.created??new Date().toISOString()}}async checkDepositStatus(e){if(!z.string().uuid().safeParse(e).success)throw p.validation("Invalid deposit ID format");let t=await this.httpClient.get(`/v2/deposits/${e}`);if(t.status==="NOT_FOUND"||!t.data)throw p.notFound(`Deposit ${e} not found`);let n=t.data;return {depositId:n.depositId,status:n.status,amount:n.amount,currency:n.currency,country:n.country,payer:n.payer,created:n.created,customerMessage:n.customerMessage,clientReferenceId:n.clientReferenceId,providerTransactionId:n.providerTransactionId,failureReason:n.failureReason,metadata:n.metadata}}async checkPayoutStatus(e){if(!z.string().uuid().safeParse(e).success)throw p.validation("Invalid payout ID format");let t=await this.httpClient.get(`/v2/payouts/${e}`);if(t.status==="NOT_FOUND"||!t.data)throw p.notFound(`Payout ${e} not found`);let n=t.data;return {payoutId:n.payoutId,status:n.status,amount:n.amount,currency:n.currency,country:n.country,recipient:n.recipient,created:n.created,customerMessage:n.customerMessage,clientReferenceId:n.clientReferenceId,providerTransactionId:n.providerTransactionId,failureReason:n.failureReason,metadata:n.metadata}}async checkStatus(e){try{return await this.checkDepositStatus(e)}catch(t){if(t instanceof p&&t.code==="NOT_FOUND")return await this.checkPayoutStatus(e);throw t}}async pollUntilComplete(e,t={}){let{interval:n=5e3,maxAttempts:a=12,onStatusChange:d}=t,y;for(let l=1;l<=a;l++){let C=await this.checkStatus(e);if(C.status!==y&&(y=C.status,d?.(C.status)),C.status==="COMPLETED"||C.status==="FAILED")return C;l<a&&await Ot(n);}return await this.checkStatus(e)}async listDeposits(e){let t={};return e?.from&&(t.from=e.from),e?.to&&(t.to=e.to),e?.status&&(t.status=e.status),e?.provider&&(t.provider=e.provider),e?.limit&&(t.limit=String(e.limit)),e?.offset&&(t.offset=String(e.offset)),(await this.httpClient.get("/v2/deposits",{params:t})).map(a=>({depositId:a.depositId??"",status:a.status,created:a.created}))}async listPayouts(e){let t={};return e?.from&&(t.from=e.from),e?.to&&(t.to=e.to),e?.status&&(t.status=e.status),e?.provider&&(t.provider=e.provider),e?.limit&&(t.limit=String(e.limit)),e?.offset&&(t.offset=String(e.offset)),(await this.httpClient.get("/v2/payouts",{params:t})).map(a=>({payoutId:a.payoutId??"",status:a.status,created:a.created}))}async resendDepositCallback(e){if(!z.string().uuid().safeParse(e).success)throw p.validation("Invalid deposit ID format");this.logger.info(`Resending callback for deposit ${e}`);let t=await this.httpClient.post(`/v2/deposits/${e}/resend-callback`,{});return this.logger.info(`Resend callback for deposit ${e}: ${t.status}`),t}async resendPayoutCallback(e){if(!z.string().uuid().safeParse(e).success)throw p.validation("Invalid payout ID format");this.logger.info(`Resending callback for payout ${e}`);let t=await this.httpClient.post(`/v2/payouts/${e}/resend-callback`,{});return this.logger.info(`Resend callback for payout ${e}: ${t.status}`),t}async cancelEnqueuedPayout(e){if(!z.string().uuid().safeParse(e).success)throw p.validation("Invalid payout ID format");this.logger.info(`Cancelling enqueued payout ${e}`);let t=await this.httpClient.post(`/v2/payouts/${e}/cancel`,{});return this.logger.info(`Cancel payout ${e}: ${t.status}`),t}};var $e=z.object({name:z.string().min(1).max(100),description:z.string().max(500).optional(),price:z.number().positive(),currency:z.enum(["XAF","XOF","USD"]),metadata:z.record(z.unknown()).optional()}),Mt=z.object({productId:z.string().uuid(),domain:z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]?\.[a-zA-Z]{2,}$/)}),Q=class{constructor(e){this.logger=e;this.products=new Map;}async create(e){let t=$e.parse(e),n=crypto.randomUUID(),a=new Date().toISOString(),d={id:n,name:t.name,description:t.description,price:t.price,currency:t.currency,domains:[],created:a,updated:a,metadata:t.metadata};return this.products.set(n,d),this.logger.info(`Created product ${n}`,{name:t.name}),this.toProduct(d)}async get(e){let t=this.products.get(e);if(!t)throw p.notFound(`Product ${e} not found`);return this.toProduct(t)}async list(){return Array.from(this.products.values()).map(e=>this.toProduct(e))}async update(e,t){let n=this.products.get(e);if(!n)throw p.notFound(`Product ${e} not found`);let a=$e.partial().parse(t),d={...n,...a,updated:new Date().toISOString()};return this.products.set(e,d),this.logger.info(`Updated product ${e}`),this.toProduct(d)}async delete(e){if(!this.products.get(e))throw p.notFound(`Product ${e} not found`);this.products.delete(e),this.logger.info(`Deleted product ${e}`);}async addDomain(e){let t=Mt.parse(e),n=this.products.get(t.productId);if(!n)throw p.notFound(`Product ${t.productId} not found`);if(n.domains.includes(t.domain))throw p.validation(`Domain ${t.domain} already added to product`);return n.domains.push(t.domain),n.updated=new Date().toISOString(),this.logger.info(`Added domain ${t.domain} to product ${t.productId}`),this.toProduct(n)}async removeDomain(e,t){let n=this.products.get(e);if(!n)throw p.notFound(`Product ${e} not found`);let a=n.domains.indexOf(t);if(a===-1)throw p.notFound(`Domain ${t} not found in product`);return n.domains.splice(a,1),n.updated=new Date().toISOString(),this.logger.info(`Removed domain ${t} from product ${e}`),this.toProduct(n)}toProduct(e){return {id:e.id,name:e.name,description:e.description,price:e.price,currency:e.currency,domains:[...e.domains],created:e.created,updated:e.updated}}};var ee=class{constructor(e,t,n){this.httpClient=e;this.logger=t;this.webhookSecret=n?.webhookSecret;}setWebhookSecret(e){this.webhookSecret=e;}verifySignature(e,t){if(!this.webhookSecret)return this.logger.warn("Webhook secret not configured, skipping signature verification"),true;if(!t)return this.logger.warn("No signature provided in webhook request"),false;try{let n=createHmac("sha256",this.webhookSecret).update(e,"utf8").digest("hex"),a=Buffer.from(t,"hex"),d=Buffer.from(n,"hex");return a.length!==d.length?!1:timingSafeEqual(a,d)}catch(n){return this.logger.error("Error verifying webhook signature",n),false}}parseEvent(e){try{let t=JSON.parse(e);if(!t.eventId||!t.eventType||!t.timestamp)throw new Error("Invalid webhook event structure");return t}catch(t){throw p.validation(`Failed to parse webhook event: ${t instanceof Error?t.message:"Unknown error"}`)}}constructEvent(e,t){if(!this.verifySignature(e,t))throw p.unauthorized("Invalid webhook signature");return this.parseEvent(e)}async registerCallback(e){this.logger.info(`Registering callback URL: ${e}`),await this.httpClient.post("/webhooks",{url:e}),this.logger.info("Callback URL registered successfully");}async unregisterCallback(){this.logger.info("Unregistering callback URL"),await this.httpClient.delete("/webhooks"),this.logger.info("Callback URL unregistered successfully");}isDepositEvent(e){return e.startsWith("deposit.")}isPayoutEvent(e){return e.startsWith("payout.")}isRefundEvent(e){return e.startsWith("refund.")}isSuccessEvent(e){return e.endsWith(".completed")}isFailureEvent(e){return e.endsWith(".failed")}};var te=class{constructor(e,t){this.httpClient=e;this.logger=t;}generateTransactionId(){return v4()}validateTransactionId(e){return validate(e)&&version(e)===4}async getActiveConfiguration(e){let t={};e?.country&&(t.country=e.country),e?.operationType&&(t.operationType=e.operationType),this.logger.info("Fetching active configuration",e);let n=await this.httpClient.get("/v2/active-conf",{params:Object.keys(t).length>0?t:void 0});return this.logger.info(`Retrieved configuration for ${n.countries.length} countries`),n}async getProviderAvailability(e){let t={};return e?.country&&(t.country=e.country),e?.operationType&&(t.operationType=e.operationType),this.logger.info("Fetching provider availability",e),await this.httpClient.get("/v2/availability",{params:Object.keys(t).length>0?t:void 0})}async predictProvider(e){this.logger.info("Predicting provider for phone number");let t=await this.httpClient.post("/v2/predict-provider",{phoneNumber:e});return this.logger.info(`Predicted provider: ${t.provider} (${t.country})`),t}async getPublicKeys(){this.logger.info("Fetching public keys");let e=await this.httpClient.get("/v2/public-key/http");return this.logger.info(`Retrieved ${e.length} public keys`),e}async getTransactionLimits(e){try{let t=await this.getActiveConfiguration();for(let n of t.countries)for(let a of n.providers)if(a.provider===e){let d=a.currencies[0];if(d?.operationTypes){let y=d.operationTypes.DEPOSIT,g=d.operationTypes.PAYOUT,l=J[e];return {minDeposit:y?.minAmount?parseFloat(y.minAmount):l.minDeposit,maxDeposit:y?.maxAmount?parseFloat(y.maxAmount):l.maxDeposit,minPayout:g?.minAmount?parseFloat(g.minAmount):l.minPayout,maxPayout:g?.maxAmount?parseFloat(g.maxAmount):l.maxPayout,currency:d.currency,dailyLimit:l.dailyLimit}}}}catch(t){this.logger.warn(`Failed to fetch live limits for ${e}, using defaults`,t);}return J[e]}async checkMMOAvailability(e){try{let t=await this.getProviderAvailability();for(let n of t){let a=n.providers.find(d=>d.provider===e);if(a){let d=a.operationTypes.find(m=>m.operationType==="DEPOSIT"),y=a.operationTypes.find(m=>m.operationType==="PAYOUT"),g=d?.status==="OPERATIONAL"||y?.status==="OPERATIONAL",l=d?.status==="DELAYED"||y?.status==="DELAYED",C=d?.status==="CLOSED"&&y?.status==="CLOSED";return {correspondent:e,available:g||l,degraded:l,message:C?"Provider is currently closed":void 0}}}return {correspondent:e,available:!1,degraded:!1,message:"Correspondent not found in availability list"}}catch(t){return this.logger.warn(`Failed to check MMO availability for ${e}`,t),{correspondent:e,available:false,degraded:true,message:"Unable to verify availability"}}}formatPhoneNumber(e,t){let n=e.replace(/\D/g,"");n.startsWith("00")&&(n=n.slice(2));let d={CMR:"237",COG:"242",GAB:"241",ZMB:"260",GHA:"233",KEN:"254",TZA:"255",UGA:"256",RWA:"250",BEN:"229",CIV:"225",SEN:"221"}[t.toUpperCase()];return d&&!n.startsWith(d)&&(n.startsWith("0")&&(n=n.slice(1)),n=d+n),n}validatePhoneNumber(e,t){let n=G[t];if(!n)return false;let a=e.replace(/\D/g,"");return n.phoneRegex.test(a)}getSupportedCorrespondents(){return $}getCorrespondentInfo(e){return G[e]}getAllCorrespondentsInfo(){return Object.values(G)}detectCorrespondent(e){let t=e.replace(/\D/g,"");for(let[n,a]of Object.entries(G))if(a.phoneRegex.test(t))return n;return null}};var Ft=z.object({wallet:z.object({country:z.string().length(3),currency:z.string().length(3),provider:z.string().optional()}),callbackUrl:z.string().url(),startDate:z.string(),endDate:z.string(),compressed:z.boolean().optional()}),oe=class{constructor(e,t){this.httpClient=e;this.logger=t;}async getWalletBalances(){this.logger.info("Fetching wallet balances");let e=await this.httpClient.get("/v2/wallets/balances");return this.logger.info(`Retrieved ${e.balances.length} wallet balances`),e.balances}async generateStatement(e){let t=Ft.parse(e);this.logger.info("Generating statement",{wallet:t.wallet,startDate:t.startDate,endDate:t.endDate});let n=await this.httpClient.post("/v2/statements",t);if(n.status==="REJECTED"&&n.failureReason)throw p.fromPawapayResponse(n.failureReason.failureCode,n.failureReason.failureMessage);return this.logger.info(`Statement ${n.statementId} status: ${n.status}`),n}async checkStatementStatus(e){if(!z.string().uuid().safeParse(e).success)throw p.validation("Invalid statement ID format");let t=await this.httpClient.get(`/v2/statements/${e}`);if(t.status==="NOT_FOUND"||!t.data)throw p.notFound(`Statement ${e} not found`);return this.logger.info(`Statement ${e} status: ${t.data.status}`),t.data}async pollStatementUntilComplete(e,t={}){let{interval:n=5e3,maxAttempts:a=24}=t;for(let d=1;d<=a;d++){let y=await this.checkStatementStatus(e);if(y.status==="COMPLETED"||y.status==="FAILED")return y;d<a&&await new Promise(g=>setTimeout(g,n));}return this.checkStatementStatus(e)}};var ye=class{constructor(e){let n={...We(),...e};this.config=Fe(n),this.logger=new q("SpaarkPayApiSdk",this.config.logLevel),this.httpClient=Y.fromConfig(this.config,this.logger),this.transactions=new Z(this.httpClient,this.logger),this.products=new Q(this.logger),this.webhooks=new ee(this.httpClient,this.logger,{webhookSecret:this.getWebhookSecretFromEnv()}),this.utils=new te(this.httpClient,this.logger),this.finances=new oe(this.httpClient,this.logger),this.logger.info("SpaarkPayApiSdk initialized",{environment:this.config.environment,baseUrl:this.config.baseUrl});}getWebhookSecretFromEnv(){if(typeof process<"u"&&process.env)return process.env.PAWAPAY_WEBHOOK_SECRET}getConfig(){return {...this.config}}setLogLevel(e){this.logger.setLevel(e);}setWebhookSecret(e){this.webhooks.setWebhookSecret(e);}};var L=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{let e=Math.random()*16|0;return (i==="x"?e:e&3|8).toString(16)});function Wt(i,e={}){let{transactionId:t=L(),amount:n="5000",currency:a="XAF",correspondent:d="MTN_MOMO_CMR",phoneNumber:y="237670000000",status:g=i==="deposit.failed"?"FAILED":"COMPLETED",failureCode:l="INSUFFICIENT_FUNDS",failureMessage:C="The payer has insufficient funds"}=e,m=new Date().toISOString(),R={depositId:t,status:g,amount:n,currency:a,correspondent:d,payer:{type:"MSISDN",address:{value:y}},customerTimestamp:m,created:m};return g==="COMPLETED"&&(R.receivedByPayer=m),g==="FAILED"&&(R.failureReason={failureCode:l,failureMessage:C}),{eventId:L(),eventType:i,timestamp:m,data:R}}function jt(i,e={}){let{transactionId:t=L(),amount:n="5000",currency:a="XAF",correspondent:d="MTN_MOMO_CMR",phoneNumber:y="237670000000",status:g=i==="payout.failed"?"FAILED":"COMPLETED",failureCode:l="RECIPIENT_NOT_FOUND",failureMessage:C="The recipient account was not found"}=e,m=new Date().toISOString(),R={payoutId:t,status:g,amount:n,currency:a,correspondent:d,recipient:{type:"MSISDN",address:{value:y}},customerTimestamp:m,created:m};return g==="COMPLETED"&&(R.receivedByRecipient=m),g==="FAILED"&&(R.failureReason={failureCode:l,failureMessage:C}),{eventId:L(),eventType:i,timestamp:m,data:R}}function $t(i,e={}){let{transactionId:t=L(),depositId:n=L(),amount:a="5000",currency:d="XAF",correspondent:y="MTN_MOMO_CMR",phoneNumber:g="237670000000",status:l=i==="refund.failed"?"FAILED":"COMPLETED",failureCode:C="REFUND_LIMIT_EXCEEDED",failureMessage:m="The refund limit has been exceeded"}=e,R=new Date().toISOString(),K={refundId:t,depositId:n,status:l,amount:a,currency:d,correspondent:y,recipient:{type:"MSISDN",address:{value:g}},created:R};return l==="FAILED"&&(K.failureReason={failureCode:C,failureMessage:m}),{eventId:L(),eventType:i,timestamp:R,data:K}}function Ge(i,e={}){return i.startsWith("deposit.")?Wt(i,e):i.startsWith("payout.")?jt(i,e):$t(i,e)}var Ve=["deposit.accepted","deposit.completed","deposit.failed","payout.accepted","payout.completed","payout.failed","refund.completed","refund.failed"];var Gt=i=>({depositId:i,status:"ACCEPTED",created:new Date().toISOString(),nextStep:"FINAL_STATUS"}),Vt=i=>({payoutId:i,status:"ACCEPTED",created:new Date().toISOString()}),Bt=i=>({depositId:i,status:["COMPLETED","ACCEPTED","PROCESSING","ENQUEUED"][Math.floor(Math.random()*4)],created:new Date(Date.now()-6e4).toISOString(),amount:"5000",currency:"XAF",country:"CMR",payer:{type:"MMO",accountDetails:{phoneNumber:"237670000000",provider:"MTN_MOMO_CMR"}}}),qt=()=>[{country:"CMR",providers:[{provider:"MTN_MOMO_CMR",operationTypes:[{operationType:"DEPOSIT",status:"OPERATIONAL"},{operationType:"PAYOUT",status:"OPERATIONAL"}]},{provider:"ORANGE_CMR",operationTypes:[{operationType:"DEPOSIT",status:"OPERATIONAL"},{operationType:"PAYOUT",status:"DELAYED"}]}]}],Ht=i=>({country:"CMR",provider:i.startsWith("23767")?"MTN_MOMO_CMR":"ORANGE_CMR",phoneNumber:i.replace(/\D/g,"")}),Kt=()=>({companyName:"Demo Company",signatureConfiguration:{signedRequestsOnly:false,signedCallbacks:true},countries:[{country:"CMR",displayName:{en:"Cameroon",fr:"Cameroun"},prefix:"237",flag:"https://cdn.pawapay.io/flags/cmr.svg",providers:[{provider:"MTN_MOMO_CMR",displayName:"MTN Mobile Money",nameDisplayedToCustomer:"MTN MoMo",currencies:[{currency:"XAF",displayName:"CFA Franc",operationTypes:{DEPOSIT:{minAmount:"100",maxAmount:"1000000",status:"OPERATIONAL"},PAYOUT:{minAmount:"100",maxAmount:"500000",status:"OPERATIONAL"}}}]}]}]}),zt=()=>({balances:[{country:"CMR",currency:"XAF",balance:"1250000.00"},{country:"COG",currency:"XAF",balance:"450000.00"},{country:"GAB",currency:"XAF",balance:"780000.00"}]}),Xt=()=>[{id:"key-001",key:"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA..."}],D=(i=800)=>new Promise(e=>setTimeout(e,i+Math.random()*400));async function Be(i,e){let t=new TextEncoder,n=await crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:"SHA-256"},false,["sign"]),a=await crypto.subtle.sign("HMAC",n,t.encode(i));return Array.from(new Uint8Array(a)).map(d=>d.toString(16).padStart(2,"0")).join("")}var re=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{let e=Math.random()*16|0;return (i==="x"?e:e&3|8).toString(16)}),be=[{value:"MTN_MOMO_CMR",label:"MTN Mobile Money",country:"Cameroun"},{value:"ORANGE_CMR",label:"Orange Money",country:"Cameroun"},{value:"MTN_MOMO_COG",label:"MTN Mobile Money",country:"Congo"},{value:"AIRTEL_COG",label:"Airtel Money",country:"Congo"},{value:"MTN_MOMO_GAB",label:"MTN Mobile Money",country:"Gabon"},{value:"AIRTEL_GAB",label:"Airtel Money",country:"Gabon"}],qe=[{value:"XAF",label:"XAF (CFA Franc BEAC)"},{value:"XOF",label:"XOF (CFA Franc BCEAO)"},{value:"GHS",label:"GHS (Ghana Cedi)"},{value:"KES",label:"KES (Kenyan Shilling)"},{value:"RWF",label:"RWF (Rwandan Franc)"},{value:"TZS",label:"TZS (Tanzanian Shilling)"},{value:"UGX",label:"UGX (Ugandan Shilling)"},{value:"ZMW",label:"ZMW (Zambian Kwacha)"}];function Yt({apiKey:i="",environment:e="sandbox",className:t="",demoMode:n=false,apiBasePath:a="/api/pawapay",onDepositComplete:d,onPayoutComplete:y,onError:g}){let[l,C]=useState(i),[m,R]=useState(e),[K,ae]=useState(!!i||n),[v,ve]=useState(n),[E,_]=useState("deposit"),[P,se]=useState("237670000000"),[U,xe]=useState("5000"),[F,Ne]=useState("XAF"),[W,Ce]=useState("MTN_MOMO_CMR"),[ie,Je]=useState("Test Payment"),[M,ce]=useState(""),[de,Re]=useState([]),[w,x]=useState("idle"),[we,Ze]=useState("whsec_test_secret_key"),[le,Ee]=useState([]),[z,Qe]=useState("deposit.completed"),[ke,et]=useState("5000"),[Pe,tt]=useState("237670000000"),[Te,ot]=useState("MTN_MOMO_CMR"),[ue,rt]=useState(""),[Ae,nt]=useState(""),[Se,at]=useState(""),[pe,st]=useState(""),[Oe,it]=useState(""),[X,Me]=useState(null),[De,ct]=useState(""),[j,Ie]=useState(null),[Le,_e]=useState(""),[V,dt]=useState("all"),f=useCallback((r,c,b,S)=>{let ge={id:re(),operation:r,status:c,response:b,error:S,timestamp:new Date().toLocaleTimeString()};Re(xt=>[ge,...xt].slice(0,20));},[]),lt=useCallback(()=>{if(!l.trim()){f("Configuration","error",void 0,"API Key is required");return}ae(true),ve(false),f("Configuration","success",{environment:m,configured:true,apiBasePath:a});},[l,m,a,f]),ut=useCallback(()=>{ve(true),ae(true),f("Configuration","success",{mode:"demo",message:"Demo mode activated - responses are simulated"});},[f]),pt=useCallback(async()=>{if(!(!l&&!v)){x("loading");try{let r=re();ce(r);let c;if(v)await D(),c=Gt(r);else {let b=await fetch(`${a}/deposit`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:l,environment:m,amount:parseFloat(U),currency:F,provider:W,phoneNumber:P,customerMessage:ie.slice(0,22),transactionId:r})}),S=await b.json();if(!b.ok)throw new Error(S.error||"Deposit failed");c=S;}x("success"),f("Deposit","success",c),d?.(c);}catch(r){x("error");let c=r instanceof Error?r.message:"Deposit failed";f("Deposit","error",void 0,c),g?.(r instanceof Error?r:new Error(c));}}},[l,a,m,v,U,F,W,P,ie,f,d,g]),mt=useCallback(async()=>{if(!(!l&&!v)){x("loading");try{let r=re();ce(r);let c;if(v)await D(),c=Vt(r);else {let b=await fetch(`${a}/payout`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:l,environment:m,amount:parseFloat(U),currency:F,provider:W,phoneNumber:P,transactionId:r})}),S=await b.json();if(!b.ok)throw new Error(S.error||"Payout failed");c=S;}x("success"),f("Payout","success",c),y?.(c);}catch(r){x("error");let c=r instanceof Error?r.message:"Payout failed";f("Payout","error",void 0,c),g?.(r instanceof Error?r:new Error(c));}}},[l,a,m,v,U,F,W,P,f,y,g]),gt=useCallback(async()=>{if(!l&&!v||!M){f("Check Status","error",void 0,"No transaction ID");return}x("loading");try{let r;if(v)await D(),r=Bt(M);else {let c=await fetch(`${a}/status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:l,environment:m,transactionId:M})}),b=await c.json();if(!c.ok)throw new Error(b.error||"Status check failed");r=b;}x("success"),f("Check Status","success",r);}catch(r){x("error");let c=r instanceof Error?r.message:"Status check failed";f("Check Status","error",void 0,c),g?.(r instanceof Error?r:new Error(c));}},[l,a,m,v,M,f,g]),ft=useCallback(async()=>{if(!(!l&&!v)){x("loading");try{let r;if(v)await D(),r=qt();else {let c=await fetch(`${a}/availability`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:l,environment:m})}),b=await c.json();if(!c.ok)throw new Error(b.error||"Availability check failed");r=b;}x("success"),f("Provider Availability","success",r);}catch(r){x("error");let c=r instanceof Error?r.message:"Availability check failed";f("Provider Availability","error",void 0,c),g?.(r instanceof Error?r:new Error(c));}}},[l,a,m,v,f,g]),yt=useCallback(async()=>{if(!(!l&&!v)){x("loading");try{let r;if(v)await D(),r=Ht(P);else {let c=await fetch(`${a}/predict-provider`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:l,environment:m,phoneNumber:P})}),b=await c.json();if(!c.ok)throw new Error(b.error||"Prediction failed");r=b;}x("success"),f("Predict Provider","success",r);}catch(r){x("error");let c=r instanceof Error?r.message:"Prediction failed";f("Predict Provider","error",void 0,c),g?.(r instanceof Error?r:new Error(c));}}},[l,a,m,v,P,f,g]),bt=useCallback(async()=>{if(!(!l&&!v)){x("loading");try{let r;if(v)await D(),r=Kt();else {let c=await fetch(`${a}/active-config`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:l,environment:m})}),b=await c.json();if(!c.ok)throw new Error(b.error||"Failed to get config");r=b;}x("success"),f("Active Configuration","success",r);}catch(r){x("error");let c=r instanceof Error?r.message:"Failed to get config";f("Active Configuration","error",void 0,c),g?.(r instanceof Error?r:new Error(c));}}},[l,a,m,v,f,g]),ht=useCallback(async()=>{if(!(!l&&!v)){x("loading");try{let r;if(v)await D(),r=Xt();else {let c=await fetch(`${a}/public-keys`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:l,environment:m})}),b=await c.json();if(!c.ok)throw new Error(b.error||"Failed to get public keys");r=b;}x("success"),f("Public Keys","success",r);}catch(r){x("error");let c=r instanceof Error?r.message:"Failed to get public keys";f("Public Keys","error",void 0,c),g?.(r instanceof Error?r:new Error(c));}}},[l,a,m,v,f,g]),vt=useCallback(async()=>{if(!(!l&&!v)){x("loading");try{let r;if(v)await D(),r=zt();else {let c=await fetch(`${a}/wallet-balances`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:l,environment:m})}),b=await c.json();if(!c.ok)throw new Error(b.error||"Failed to get balances");r=b;}x("success"),f("Wallet Balances","success",r);}catch(r){x("error");let c=r instanceof Error?r.message:"Failed to get balances";f("Wallet Balances","error",void 0,c),g?.(r instanceof Error?r:new Error(c));}}},[l,a,m,v,f,g]),me=useCallback(r=>{navigator.clipboard.writeText(r);},[]);return K?jsxs("div",{className:`space-y-6 ${t}`,children:[jsxs("div",{className:"flex items-center justify-between flex-wrap gap-4",children:[jsxs("div",{children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Spaark Pay Console"}),v?jsx("span",{className:"px-2 py-0.5 text-xs font-medium bg-amber-100 text-amber-800 dark:bg-amber-900 dark:text-amber-200",children:"DEMO"}):m==="production"?jsx("span",{className:"px-2 py-0.5 text-xs font-medium bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200",children:"PRODUCTION"}):jsx("span",{className:"px-2 py-0.5 text-xs font-medium bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200",children:"SANDBOX"})]}),jsx("p",{className:"text-muted-foreground mt-1",children:v?"Mode d\xE9mo - Les r\xE9ponses sont simul\xE9es":m==="production"?"Mode production - Transactions r\xE9elles":"Mode sandbox - Environnement de test"})]}),jsxs("button",{onClick:()=>ae(false),className:"h-8 px-3 text-xs font-medium border border-border bg-background hover:bg-muted transition-colors flex items-center gap-2",children:[jsx(he,{}),"Reconfigure"]})]}),jsxs("div",{className:"grid lg:grid-cols-3 gap-6",children:[jsxs("div",{className:"lg:col-span-2 space-y-6",children:[jsxs("div",{className:"flex flex-wrap gap-1 bg-muted p-1",children:[jsxs("button",{onClick:()=>_("deposit"),className:`flex-1 min-w-[80px] h-8 px-3 text-xs font-medium transition-colors flex items-center justify-center gap-1.5 ${E==="deposit"?"bg-background text-foreground":"text-muted-foreground hover:text-foreground"}`,children:[jsx(He,{}),"Deposit"]}),jsxs("button",{onClick:()=>_("payout"),className:`flex-1 min-w-[80px] h-8 px-3 text-xs font-medium transition-colors flex items-center justify-center gap-1.5 ${E==="payout"?"bg-background text-foreground":"text-muted-foreground hover:text-foreground"}`,children:[jsx(Jt,{}),"Payout"]}),jsxs("button",{onClick:()=>_("status"),className:`flex-1 min-w-[80px] h-8 px-3 text-xs font-medium transition-colors flex items-center justify-center gap-1.5 ${E==="status"?"bg-background text-foreground":"text-muted-foreground hover:text-foreground"}`,children:[jsx(Ke,{}),"Status"]}),jsxs("button",{onClick:()=>_("toolkit"),className:`flex-1 min-w-[80px] h-8 px-3 text-xs font-medium transition-colors flex items-center justify-center gap-1.5 ${E==="toolkit"?"bg-background text-foreground":"text-muted-foreground hover:text-foreground"}`,children:[jsx(Qt,{}),"Toolkit"]}),jsxs("button",{onClick:()=>_("finances"),className:`flex-1 min-w-[80px] h-8 px-3 text-xs font-medium transition-colors flex items-center justify-center gap-1.5 ${E==="finances"?"bg-background text-foreground":"text-muted-foreground hover:text-foreground"}`,children:[jsx(eo,{}),"Finances"]}),jsxs("button",{onClick:()=>_("webhooks"),className:`flex-1 min-w-[80px] h-8 px-3 text-xs font-medium transition-colors flex items-center justify-center gap-1.5 ${E==="webhooks"?"bg-background text-foreground":"text-muted-foreground hover:text-foreground"}`,children:[jsx(no,{}),"Webhooks"]})]}),E==="deposit"&&jsxs("div",{className:"border border-border bg-background p-6 space-y-4",children:[jsxs("div",{children:[jsx("h3",{className:"font-semibold",children:"Initiate Deposit"}),jsx("p",{className:"text-xs text-muted-foreground",children:"Collect payment from a Mobile Money user"})]}),jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Phone Number"}),jsx("input",{placeholder:"237670000000",value:P,onChange:r=>se(r.target.value),className:"w-full h-8 px-2.5 text-xs border border-input bg-transparent rounded-none outline-none focus:border-ring"})]}),jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Amount"}),jsx("input",{type:"number",placeholder:"5000",value:U,onChange:r=>xe(r.target.value),className:"w-full h-8 px-2.5 text-xs border border-input bg-transparent rounded-none outline-none focus:border-ring"})]}),jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Currency"}),jsx("select",{value:F,onChange:r=>Ne(r.target.value),className:"w-full h-8 px-2.5 text-xs border border-input bg-transparent rounded-none outline-none focus:border-ring",children:qe.map(r=>jsx("option",{value:r.value,children:r.label},r.value))})]}),jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Provider"}),jsx("select",{value:W,onChange:r=>Ce(r.target.value),className:"w-full h-8 px-2.5 text-xs border border-input bg-transparent rounded-none outline-none focus:border-ring",children:be.map(r=>jsxs("option",{value:r.value,children:[r.label," (",r.country,")"]},r.value))})]}),jsxs("div",{className:"space-y-2 sm:col-span-2",children:[jsx("label",{className:"text-xs font-medium",children:"Customer Message (4-22 chars)"}),jsx("input",{placeholder:"Payment description",value:ie,onChange:r=>Je(r.target.value),maxLength:22,className:"w-full h-8 px-2.5 text-xs border border-input bg-transparent rounded-none outline-none focus:border-ring"})]})]}),jsxs("button",{onClick:pt,disabled:w==="loading",className:"w-full h-8 px-3 text-xs font-medium bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50 transition-colors flex items-center justify-center gap-2",children:[w==="loading"?jsx(H,{}):jsx(ne,{}),"Execute Deposit"]})]}),E==="payout"&&jsxs("div",{className:"border border-border bg-background p-6 space-y-4",children:[jsxs("div",{children:[jsx("h3",{className:"font-semibold",children:"Initiate Payout"}),jsx("p",{className:"text-xs text-muted-foreground",children:"Send money to a Mobile Money account"})]}),jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Recipient Phone"}),jsx("input",{placeholder:"237670000000",value:P,onChange:r=>se(r.target.value),className:"w-full h-8 px-2.5 text-xs border border-input bg-transparent rounded-none outline-none focus:border-ring"})]}),jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Amount"}),jsx("input",{type:"number",placeholder:"5000",value:U,onChange:r=>xe(r.target.value),className:"w-full h-8 px-2.5 text-xs border border-input bg-transparent rounded-none outline-none focus:border-ring"})]}),jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Currency"}),jsx("select",{value:F,onChange:r=>Ne(r.target.value),className:"w-full h-8 px-2.5 text-xs border border-input bg-transparent rounded-none outline-none focus:border-ring",children:qe.map(r=>jsx("option",{value:r.value,children:r.label},r.value))})]}),jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Provider"}),jsx("select",{value:W,onChange:r=>Ce(r.target.value),className:"w-full h-8 px-2.5 text-xs border border-input bg-transparent rounded-none outline-none focus:border-ring",children:be.map(r=>jsxs("option",{value:r.value,children:[r.label," (",r.country,")"]},r.value))})]})]}),jsxs("button",{onClick:mt,disabled:w==="loading",className:"w-full h-8 px-3 text-xs font-medium bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50 transition-colors flex items-center justify-center gap-2",children:[w==="loading"?jsx(H,{}):jsx(ne,{}),"Execute Payout"]})]}),E==="status"&&jsxs("div",{className:"border border-border bg-background p-6 space-y-4",children:[jsxs("div",{children:[jsx("h3",{className:"font-semibold",children:"Check Transaction Status"}),jsx("p",{className:"text-xs text-muted-foreground",children:"Query the status of a transaction"})]}),jsxs("div",{className:"space-y-4",children:[jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Transaction ID"}),jsxs("div",{className:"flex gap-2",children:[jsx("input",{placeholder:"Enter transaction ID (UUID)",value:M,onChange:r=>ce(r.target.value),className:"flex-1 h-8 px-2.5 text-xs border border-input bg-transparent rounded-none outline-none focus:border-ring font-mono"}),M&&jsx("button",{onClick:()=>me(M),className:"w-8 h-8 border border-border bg-background hover:bg-muted transition-colors flex items-center justify-center",title:"Copy to clipboard",children:jsx(ze,{})})]})]}),jsxs("button",{onClick:gt,disabled:w==="loading"||!M,className:"w-full h-8 px-3 text-xs font-medium bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50 transition-colors flex items-center justify-center gap-2",children:[w==="loading"?jsx(H,{}):jsx(Ke,{}),"Check Status"]})]})]}),E==="toolkit"&&jsxs("div",{className:"space-y-4",children:[jsxs("div",{className:"border border-border bg-background p-6 space-y-4",children:[jsxs("div",{children:[jsx("h3",{className:"font-semibold",children:"Predict Provider"}),jsx("p",{className:"text-xs text-muted-foreground",children:"Predict the provider from a phone number"})]}),jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Phone Number"}),jsx("input",{placeholder:"+237 670 000 000",value:P,onChange:r=>se(r.target.value),className:"w-full h-8 px-2.5 text-xs border border-input bg-transparent rounded-none outline-none focus:border-ring"})]}),jsxs("button",{onClick:yt,disabled:w==="loading",className:"w-full h-8 px-3 text-xs font-medium bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50 transition-colors flex items-center justify-center gap-2",children:[w==="loading"?jsx(H,{}):jsx(to,{}),"Predict Provider"]})]}),jsxs("div",{className:"grid sm:grid-cols-3 gap-3",children:[jsxs("button",{onClick:ft,disabled:w==="loading",className:"h-10 px-3 text-xs font-medium border border-border bg-background hover:bg-muted disabled:opacity-50 transition-colors flex items-center justify-center gap-2",children:[jsx(oo,{}),"Provider Availability"]}),jsxs("button",{onClick:bt,disabled:w==="loading",className:"h-10 px-3 text-xs font-medium border border-border bg-background hover:bg-muted disabled:opacity-50 transition-colors flex items-center justify-center gap-2",children:[jsx(he,{}),"Active Config"]}),jsxs("button",{onClick:ht,disabled:w==="loading",className:"h-10 px-3 text-xs font-medium border border-border bg-background hover:bg-muted disabled:opacity-50 transition-colors flex items-center justify-center gap-2",children:[jsx(ro,{}),"Public Keys"]})]})]}),E==="finances"&&jsxs("div",{className:"space-y-4",children:[jsxs("div",{className:"border border-border bg-background p-6 space-y-4",children:[jsxs("div",{children:[jsx("h3",{className:"font-semibold",children:"Wallet Balances"}),jsx("p",{className:"text-xs text-muted-foreground",children:"View balances for all your wallets"})]}),jsxs("button",{onClick:vt,disabled:w==="loading",className:"w-full h-8 px-3 text-xs font-medium bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50 transition-colors flex items-center justify-center gap-2",children:[w==="loading"?jsx(H,{}):jsx(He,{}),"Get Wallet Balances"]})]}),jsxs("div",{className:"border border-border bg-background p-6 space-y-4",children:[jsxs("div",{children:[jsx("h3",{className:"font-semibold",children:"Statements"}),jsx("p",{className:"text-xs text-muted-foreground",children:"Generate financial statements for your wallets"})]}),jsxs("div",{className:"p-4 bg-muted/50 text-xs text-muted-foreground",children:["Statement generation requires callback URL configuration. Use the SDK directly:",jsx("pre",{className:"mt-2 p-2 bg-background overflow-x-auto",children:`await sdk.finances.generateStatement({
1
+ import {z as z$1}from'zod';import Qe from'axios';import {createHmac,timingSafeEqual}from'crypto';import {v4,validate,version}from'uuid';import {forwardRef,useState,useEffect,useCallback,useMemo,useRef}from'react';import {ChevronDown,Check,Settings,Wallet,Smartphone,RefreshCw,Wrench,BarChart3,Zap,Loader2,PlayCircle,Copy,Search,Wifi,Key,Shield,CheckCircle2,XCircle,Code,LayoutDashboard,FlaskConical,Beaker,Globe,Lock,ArrowDownCircle,ArrowUpCircle,MoreVertical,TrendingUp,Hourglass,Ban,Inbox,Plus,ChevronLeft,ChevronRight,AlertCircle,Clock}from'lucide-react';import*as z from'@radix-ui/react-tabs';import*as S from'@radix-ui/react-select';import {useReactTable,getFilteredRowModel,getPaginationRowModel,getCoreRowModel,flexRender}from'@tanstack/react-table';import {ResponsiveContainer,AreaChart,CartesianGrid,XAxis,YAxis,Tooltip,Legend,Area,BarChart,Bar,Cell,PieChart,Pie}from'recharts';import {clsx}from'clsx';import {twMerge}from'tailwind-merge';import {jsx,jsxs,Fragment}from'react/jsx-runtime';var pe={timeout:3e4,retries:3,retryDelay:1e3,logLevel:"info",sandboxUrl:"https://api.sandbox.pawapay.io",productionUrl:"https://api.pawapay.io"};var A={VALIDATION_ERROR:"VALIDATION_ERROR",INVALID_PHONE:"INVALID_PHONE",INSUFFICIENT_FUNDS:"INSUFFICIENT_FUNDS",AMOUNT_TOO_LOW:"AMOUNT_TOO_LOW",AMOUNT_TOO_HIGH:"AMOUNT_TOO_HIGH",LIMIT_EXCEEDED:"LIMIT_EXCEEDED",DUPLICATE:"DUPLICATE",MMO_UNAVAILABLE:"MMO_UNAVAILABLE",TIMEOUT:"TIMEOUT",UNAUTHORIZED:"UNAUTHORIZED",RATE_LIMITED:"RATE_LIMITED",SERVER_ERROR:"SERVER_ERROR",NETWORK_ERROR:"NETWORK_ERROR",NOT_FOUND:"NOT_FOUND",REFUND_NOT_ALLOWED:"REFUND_NOT_ALLOWED"},Ea=[{pawapayCode:"INVALID_PHONE_NUMBER",sdkCode:A.INVALID_PHONE,httpStatus:400,retryable:false,message:"Invalid phone number format"},{pawapayCode:"INSUFFICIENT_FUNDS",sdkCode:A.INSUFFICIENT_FUNDS,httpStatus:402,retryable:false,message:"Insufficient funds in account"},{pawapayCode:"AMOUNT_TOO_LOW",sdkCode:A.AMOUNT_TOO_LOW,httpStatus:400,retryable:false,message:"Amount below minimum"},{pawapayCode:"AMOUNT_TOO_HIGH",sdkCode:A.AMOUNT_TOO_HIGH,httpStatus:400,retryable:false,message:"Amount exceeds maximum"},{pawapayCode:"TRANSACTION_LIMIT_EXCEEDED",sdkCode:A.LIMIT_EXCEEDED,httpStatus:400,retryable:false,message:"Daily or monthly limit exceeded"},{pawapayCode:"DUPLICATE_TRANSACTION",sdkCode:A.DUPLICATE,httpStatus:409,retryable:false,message:"Transaction ID already used"},{pawapayCode:"CORRESPONDENT_UNAVAILABLE",sdkCode:A.MMO_UNAVAILABLE,httpStatus:503,retryable:true,message:"Mobile Money operator temporarily unavailable"},{pawapayCode:"CORRESPONDENT_TEMPORARILY_UNAVAILABLE",sdkCode:A.MMO_UNAVAILABLE,httpStatus:503,retryable:true,message:"Mobile Money operator temporarily unavailable"},{pawapayCode:"TIMEOUT",sdkCode:A.TIMEOUT,httpStatus:408,retryable:true,message:"Transaction timed out"},{pawapayCode:"INVALID_API_KEY",sdkCode:A.UNAUTHORIZED,httpStatus:401,retryable:false,message:"Invalid or expired API key"},{pawapayCode:"RATE_LIMIT_EXCEEDED",sdkCode:A.RATE_LIMITED,httpStatus:429,retryable:true,message:"Too many requests"},{pawapayCode:"INTERNAL_ERROR",sdkCode:A.SERVER_ERROR,httpStatus:500,retryable:true,message:"Pawapay internal error"},{pawapayCode:"REFUND_NOT_ALLOWED",sdkCode:A.REFUND_NOT_ALLOWED,httpStatus:400,retryable:false,message:"Refund not allowed for this transaction"}];function xt(n){return Ea.find(e=>e.pawapayCode===n)}var v=class n extends Error{constructor(e,t,r,i){super(e),this.name="PawapayError",this.code=t,this.statusCode=r,this.failureReason=i?.failureReason,this.retryable=i?.retryable??false,this.originalError=i?.originalError,Error.captureStackTrace&&Error.captureStackTrace(this,n);}static fromPawapayResponse(e,t,r){let i=xt(e);return i?new n(t??i.message,i.sdkCode,i.httpStatus,{retryable:i.retryable,originalError:r}):new n(t??"Unknown error occurred",A.SERVER_ERROR,500,{retryable:false,originalError:r})}static validation(e){return new n(e,A.VALIDATION_ERROR,400,{retryable:false})}static network(e,t){return new n(e,A.NETWORK_ERROR,0,{retryable:true,originalError:t})}static timeout(e="Request timed out"){return new n(e,A.TIMEOUT,408,{retryable:true})}static unauthorized(e="Invalid or expired API key"){return new n(e,A.UNAUTHORIZED,401,{retryable:false})}static notFound(e="Resource not found"){return new n(e,A.NOT_FOUND,404,{retryable:false})}toJSON(){return {name:this.name,message:this.message,code:this.code,statusCode:this.statusCode,failureReason:this.failureReason,retryable:this.retryable}}};var Ta=z$1.object({apiKey:z$1.string().min(1,"API key is required"),environment:z$1.enum(["sandbox","production"]),baseUrl:z$1.string().url().optional(),callbackUrl:z$1.string().url().optional(),timeout:z$1.number().positive().max(6e5).optional(),retries:z$1.number().int().min(0).max(10).optional(),retryDelay:z$1.number().positive().max(6e4).optional(),logLevel:z$1.enum(["debug","info","warn","error","none"]).optional()});function Nt(n){let e=Ta.safeParse(n);if(!e.success){let i=e.error.errors.map(u=>`${u.path.join(".")}: ${u.message}`);throw v.validation(`Invalid SDK configuration: ${i.join(", ")}`)}let t=e.data,r=t.baseUrl??(t.environment==="production"?pe.productionUrl:pe.sandboxUrl);return {apiKey:t.apiKey,environment:t.environment,baseUrl:r,callbackUrl:t.callbackUrl,timeout:t.timeout??pe.timeout,retries:t.retries??pe.retries,retryDelay:t.retryDelay??pe.retryDelay,logLevel:t.logLevel??pe.logLevel}}function Ct(){let n=typeof process<"u"?process.env:{},e={};if(n.PAWAPAY_API_KEY&&(e.apiKey=n.PAWAPAY_API_KEY),n.PAWAPAY_ENVIRONMENT){let t=n.PAWAPAY_ENVIRONMENT.toLowerCase();(t==="production"||t==="sandbox")&&(e.environment=t);}if(n.PAWAPAY_BASE_URL&&(e.baseUrl=n.PAWAPAY_BASE_URL),n.PAWAPAY_CALLBACK_URL&&(e.callbackUrl=n.PAWAPAY_CALLBACK_URL),n.PAWAPAY_TIMEOUT){let t=parseInt(n.PAWAPAY_TIMEOUT,10);isNaN(t)||(e.timeout=t);}if(n.PAWAPAY_RETRIES){let t=parseInt(n.PAWAPAY_RETRIES,10);isNaN(t)||(e.retries=t);}if(n.PAWAPAY_LOG_LEVEL){let t=n.PAWAPAY_LOG_LEVEL.toLowerCase();["debug","info","warn","error","none"].includes(t)&&(e.logLevel=t);}return e}var wa={maxAttempts:3,initialDelay:1e3,maxDelay:3e4,backoffMultiplier:2};function Ra(n){return new Promise(e=>setTimeout(e,n))}function Pa(n,e){let t=e.initialDelay*Math.pow(e.backoffMultiplier,n-1),r=Math.random()*.3*t;return Math.min(t+r,e.maxDelay)}async function Re(n,e={},t){let r={...wa,...e},i;for(let u=1;u<=r.maxAttempts;u++)try{return await n()}catch(b){if(i=b instanceof Error?b:new Error(String(b)),!(b instanceof v?b.retryable:Sa(b))||u===r.maxAttempts)throw b;let f=Pa(u,r);t?.warn(`Attempt ${u}/${r.maxAttempts} failed, retrying in ${Math.round(f)}ms`,{error:i.message}),await Ra(f);}throw i??new Error("Retry failed without error")}function Sa(n){return n instanceof v?n.retryable:n instanceof Error?["ECONNRESET","ECONNREFUSED","ETIMEDOUT","ENOTFOUND","Network Error","timeout","socket hang up"].some(t=>n.message.includes(t)||n.code===t):false}var _e=class n{constructor(e){this.logger=e.logger,this.retries=e.retries,this.retryDelay=e.retryDelay,this.client=Qe.create({baseURL:e.baseUrl,timeout:e.timeout,headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`}}),this.setupInterceptors();}setupInterceptors(){this.client.interceptors.request.use(e=>(this.logger.debug(`${e.method?.toUpperCase()} ${e.url}`,{params:e.params}),e),e=>(this.logger.error("Request error",e),Promise.reject(e))),this.client.interceptors.response.use(e=>(this.logger.debug(`${e.config.method?.toUpperCase()} ${e.config.url} -> ${e.status}`,{data:e.data}),e),e=>(Qe.isAxiosError(e)&&this.logger.error(`Request failed: ${e.config?.method?.toUpperCase()} ${e.config?.url}`,{status:e.response?.status,data:e.response?.data}),Promise.reject(e)));}handleError(e){if(Qe.isAxiosError(e)){if(e.code==="ECONNABORTED"||e.message.includes("timeout"))throw v.timeout();if(!e.response)throw v.network(e.message||"Network error",e);let{status:t,data:r}=e.response,i=r;if(t===401)throw v.unauthorized();if(t===404)throw v.notFound();let u=i?.errorCode??i?.rejectionReason?.rejectionCode;throw u?v.fromPawapayResponse(u,i?.errorMessage??i?.rejectionReason?.rejectionMessage,e):new v(i?.errorMessage??`HTTP error ${t}`,"SERVER_ERROR",t,{retryable:t>=500,originalError:e})}throw e instanceof v?e:v.network(e instanceof Error?e.message:"Unknown error",e instanceof Error?e:void 0)}async get(e,t){return Re(async()=>{try{return (await this.client.get(e,t)).data}catch(r){this.handleError(r);}},{maxAttempts:this.retries,initialDelay:this.retryDelay},this.logger)}async post(e,t,r){return Re(async()=>{try{return (await this.client.post(e,t,r)).data}catch(i){this.handleError(i);}},{maxAttempts:this.retries,initialDelay:this.retryDelay},this.logger)}async put(e,t,r){return Re(async()=>{try{return (await this.client.put(e,t,r)).data}catch(i){this.handleError(i);}},{maxAttempts:this.retries,initialDelay:this.retryDelay},this.logger)}async delete(e,t){return Re(async()=>{try{return (await this.client.delete(e,t)).data}catch(r){this.handleError(r);}},{maxAttempts:this.retries,initialDelay:this.retryDelay},this.logger)}static fromConfig(e,t){return new n({baseUrl:e.baseUrl,apiKey:e.apiKey,timeout:e.timeout,retries:e.retries,retryDelay:e.retryDelay,logger:t})}};var Et={debug:0,info:1,warn:2,error:3,none:4},Pe=class{constructor(e,t="info"){this.prefix=e,this.level=t;}setLevel(e){this.level=e;}shouldLog(e){return Et[e]>=Et[this.level]}formatMessage(e,t){return `[${new Date().toISOString()}] ${e.toUpperCase().padEnd(5)} [${this.prefix}] ${t}`}sanitize(e){if(e==null||typeof e=="string"||typeof e!="object")return e;if(Array.isArray(e))return e.map(i=>this.sanitize(i));let t={},r=["apiKey","api_key","authorization","password","secret","token"];for(let[i,u]of Object.entries(e))r.some(b=>i.toLowerCase().includes(b))?t[i]="[REDACTED]":typeof u=="object"&&u!==null?t[i]=this.sanitize(u):t[i]=u;return t}debug(e,t){if(this.shouldLog("debug")){let r=this.formatMessage("debug",e);t!==void 0?console.debug(r,this.sanitize(t)):console.debug(r);}}info(e,t){if(this.shouldLog("info")){let r=this.formatMessage("info",e);t!==void 0?console.info(r,this.sanitize(t)):console.info(r);}}warn(e,t){if(this.shouldLog("warn")){let r=this.formatMessage("warn",e);t!==void 0?console.warn(r,this.sanitize(t)):console.warn(r);}}error(e,t){if(this.shouldLog("error")){let r=this.formatMessage("error",e);t!==void 0?console.error(r,this.sanitize(t)):console.error(r);}}};var he=["MTN_MOMO_CMR","ORANGE_CMR","MTN_MOMO_COG","AIRTEL_COG","MTN_MOMO_GAB","AIRTEL_GAB"],ve={MTN_MOMO_CMR:{correspondent:"MTN_MOMO_CMR",name:"MTN Mobile Money",country:"Cameroon",countryCode:"CMR",currency:"XAF",features:["deposit","payout","refund"],phoneRegex:/^237(67|68|65[0-4])\d{6}$/},ORANGE_CMR:{correspondent:"ORANGE_CMR",name:"Orange Money",country:"Cameroon",countryCode:"CMR",currency:"XAF",features:["deposit","payout","refund"],phoneRegex:/^237(69|65[5-9])\d{6}$/},MTN_MOMO_COG:{correspondent:"MTN_MOMO_COG",name:"MTN Mobile Money",country:"Congo",countryCode:"COG",currency:"XAF",features:["deposit","payout","refund"],phoneRegex:/^242(04|05|06)\d{7}$/},AIRTEL_COG:{correspondent:"AIRTEL_COG",name:"Airtel Money",country:"Congo",countryCode:"COG",currency:"XAF",features:["deposit","payout"],phoneRegex:/^242(01|02|03)\d{7}$/},MTN_MOMO_GAB:{correspondent:"MTN_MOMO_GAB",name:"MTN Mobile Money",country:"Gabon",countryCode:"GAB",currency:"XAF",features:["deposit","payout","refund"],phoneRegex:/^241(06|07)\d{6}$/},AIRTEL_GAB:{correspondent:"AIRTEL_GAB",name:"Airtel Money",country:"Gabon",countryCode:"GAB",currency:"XAF",features:["deposit","payout"],phoneRegex:/^241(04|05)\d{6}$/}},Fe={MTN_MOMO_CMR:{minDeposit:100,maxDeposit:1e6,minPayout:500,maxPayout:5e5,currency:"XAF",dailyLimit:2e6},ORANGE_CMR:{minDeposit:100,maxDeposit:1e6,minPayout:500,maxPayout:5e5,currency:"XAF",dailyLimit:2e6},MTN_MOMO_COG:{minDeposit:100,maxDeposit:5e5,minPayout:500,maxPayout:3e5,currency:"XAF",dailyLimit:1e6},AIRTEL_COG:{minDeposit:100,maxDeposit:5e5,minPayout:500,maxPayout:3e5,currency:"XAF",dailyLimit:1e6},MTN_MOMO_GAB:{minDeposit:100,maxDeposit:5e5,minPayout:500,maxPayout:3e5,currency:"XAF",dailyLimit:1e6},AIRTEL_GAB:{minDeposit:100,maxDeposit:5e5,minPayout:500,maxPayout:3e5,currency:"XAF",dailyLimit:1e6}};var ka=z$1.object({amount:z$1.number().positive("Amount must be positive").max(1e7),currency:z$1.string().min(3).max(3),provider:z$1.enum(he),phoneNumber:z$1.string().regex(/^[0-9]{9,15}$/,"Phone number must be 9-15 digits"),transactionId:z$1.string().uuid(),preAuthorisationCode:z$1.string().optional(),clientReferenceId:z$1.string().optional(),customerMessage:z$1.string().min(4).max(22).optional(),metadata:z$1.array(z$1.record(z$1.unknown())).max(10).optional()}),Da=z$1.object({amount:z$1.number().positive("Amount must be positive").max(1e7),currency:z$1.string().min(3).max(3),provider:z$1.enum(he),phoneNumber:z$1.string().regex(/^[0-9]{9,15}$/,"Phone number must be 9-15 digits"),transactionId:z$1.string().uuid(),clientReferenceId:z$1.string().optional(),customerMessage:z$1.string().min(4).max(22).optional(),metadata:z$1.array(z$1.record(z$1.unknown())).max(10).optional()}),Aa=z$1.object({depositId:z$1.string().uuid(),returnUrl:z$1.string().url(),phoneNumber:z$1.string().optional(),amountDetails:z$1.object({amount:z$1.number().positive(),currency:z$1.string().length(3)}).optional(),language:z$1.enum(["EN","FR"]).optional(),country:z$1.string().length(3).optional(),reason:z$1.string().max(50).optional(),customerMessage:z$1.string().min(4).max(22).optional(),metadata:z$1.array(z$1.record(z$1.unknown())).max(10).optional()}),Ma=z$1.object({depositId:z$1.string().uuid(),amount:z$1.number().positive("Amount must be positive"),transactionId:z$1.string().uuid()});function Oa(n){return new Promise(e=>setTimeout(e,n))}var Ue=class{constructor(e,t){this.httpClient=e;this.logger=t;}async initiateDeposit(e){let t=ka.parse(e),r={depositId:t.transactionId,amount:t.amount.toString(),currency:t.currency,payer:{type:"MMO",accountDetails:{phoneNumber:t.phoneNumber,provider:t.provider}},preAuthorisationCode:t.preAuthorisationCode,clientReferenceId:t.clientReferenceId,customerMessage:t.customerMessage,metadata:t.metadata};this.logger.info(`Initiating V2 deposit ${t.transactionId}`,{amount:t.amount,currency:t.currency,provider:t.provider});let i=await this.httpClient.post("/v2/deposits",r);if(i.status==="REJECTED"&&i.rejectionReason)throw v.fromPawapayResponse(i.rejectionReason.rejectionCode,i.rejectionReason.rejectionMessage);return this.logger.info(`Deposit ${i.depositId} status: ${i.status}`),{depositId:i.depositId,status:i.status,created:i.created??new Date().toISOString(),nextStep:i.nextStep,redirectUrl:i.redirectUrl}}async initiatePayout(e){let t=Da.parse(e),r={payoutId:t.transactionId,amount:t.amount.toString(),currency:t.currency,recipient:{type:"MMO",accountDetails:{phoneNumber:t.phoneNumber,provider:t.provider}},clientReferenceId:t.clientReferenceId,customerMessage:t.customerMessage,metadata:t.metadata};this.logger.info(`Initiating V2 payout ${t.transactionId}`,{amount:t.amount,currency:t.currency,provider:t.provider});let i=await this.httpClient.post("/v2/payouts",r);if(i.status==="REJECTED"&&i.rejectionReason)throw v.fromPawapayResponse(i.rejectionReason.rejectionCode,i.rejectionReason.rejectionMessage);return this.logger.info(`Payout ${i.payoutId} status: ${i.status}`),{payoutId:i.payoutId,status:i.status,created:i.created??new Date().toISOString()}}async createPaymentPage(e){let t=Aa.parse(e),r={depositId:t.depositId,returnUrl:t.returnUrl,phoneNumber:t.phoneNumber,amountDetails:t.amountDetails?{amount:t.amountDetails.amount.toString(),currency:t.amountDetails.currency}:void 0,language:t.language,country:t.country,reason:t.reason,customerMessage:t.customerMessage,metadata:t.metadata};this.logger.info(`Creating payment page for deposit ${t.depositId}`);let i=await this.httpClient.post("/v2/paymentpage",r);return this.logger.info(`Payment page created: ${i.redirectUrl}`),{redirectUrl:i.redirectUrl}}async refund(e){let t=Ma.parse(e),r={refundId:t.transactionId,depositId:t.depositId,amount:t.amount.toString()};this.logger.info(`Initiating refund ${t.transactionId}`,{depositId:t.depositId,amount:t.amount});let i=await this.httpClient.post("/refunds",r);if(i.status==="REJECTED"&&i.rejectionReason)throw v.fromPawapayResponse(i.rejectionReason.rejectionCode,i.rejectionReason.rejectionMessage);return this.logger.info(`Refund ${i.refundId} status: ${i.status}`),{refundId:i.refundId,depositId:t.depositId,status:i.status,amount:t.amount,created:i.created??new Date().toISOString()}}async checkDepositStatus(e){if(!z$1.string().uuid().safeParse(e).success)throw v.validation("Invalid deposit ID format");let t=await this.httpClient.get(`/v2/deposits/${e}`);if(t.status==="NOT_FOUND"||!t.data)throw v.notFound(`Deposit ${e} not found`);let r=t.data;return {depositId:r.depositId,status:r.status,amount:r.amount,currency:r.currency,country:r.country,payer:r.payer,created:r.created,customerMessage:r.customerMessage,clientReferenceId:r.clientReferenceId,providerTransactionId:r.providerTransactionId,failureReason:r.failureReason,metadata:r.metadata}}async checkPayoutStatus(e){if(!z$1.string().uuid().safeParse(e).success)throw v.validation("Invalid payout ID format");let t=await this.httpClient.get(`/v2/payouts/${e}`);if(t.status==="NOT_FOUND"||!t.data)throw v.notFound(`Payout ${e} not found`);let r=t.data;return {payoutId:r.payoutId,status:r.status,amount:r.amount,currency:r.currency,country:r.country,recipient:r.recipient,created:r.created,customerMessage:r.customerMessage,clientReferenceId:r.clientReferenceId,providerTransactionId:r.providerTransactionId,failureReason:r.failureReason,metadata:r.metadata}}async checkStatus(e){try{return await this.checkDepositStatus(e)}catch(t){if(t instanceof v&&t.code==="NOT_FOUND")return await this.checkPayoutStatus(e);throw t}}async pollUntilComplete(e,t={}){let{interval:r=5e3,maxAttempts:i=12,onStatusChange:u}=t,b;for(let f=1;f<=i;f++){let D=await this.checkStatus(e);if(D.status!==b&&(b=D.status,u?.(D.status)),D.status==="COMPLETED"||D.status==="FAILED")return D;f<i&&await Oa(r);}return await this.checkStatus(e)}async listDeposits(e){let t={};return e?.from&&(t.from=e.from),e?.to&&(t.to=e.to),e?.status&&(t.status=e.status),e?.provider&&(t.provider=e.provider),e?.limit&&(t.limit=String(e.limit)),e?.offset&&(t.offset=String(e.offset)),(await this.httpClient.get("/v2/deposits",{params:t})).map(i=>({depositId:i.depositId??"",status:i.status,created:i.created}))}async listPayouts(e){let t={};return e?.from&&(t.from=e.from),e?.to&&(t.to=e.to),e?.status&&(t.status=e.status),e?.provider&&(t.provider=e.provider),e?.limit&&(t.limit=String(e.limit)),e?.offset&&(t.offset=String(e.offset)),(await this.httpClient.get("/v2/payouts",{params:t})).map(i=>({payoutId:i.payoutId??"",status:i.status,created:i.created}))}async resendDepositCallback(e){if(!z$1.string().uuid().safeParse(e).success)throw v.validation("Invalid deposit ID format");this.logger.info(`Resending callback for deposit ${e}`);let t=await this.httpClient.post(`/v2/deposits/${e}/resend-callback`,{});return this.logger.info(`Resend callback for deposit ${e}: ${t.status}`),t}async resendPayoutCallback(e){if(!z$1.string().uuid().safeParse(e).success)throw v.validation("Invalid payout ID format");this.logger.info(`Resending callback for payout ${e}`);let t=await this.httpClient.post(`/v2/payouts/${e}/resend-callback`,{});return this.logger.info(`Resend callback for payout ${e}: ${t.status}`),t}async cancelEnqueuedPayout(e){if(!z$1.string().uuid().safeParse(e).success)throw v.validation("Invalid payout ID format");this.logger.info(`Cancelling enqueued payout ${e}`);let t=await this.httpClient.post(`/v2/payouts/${e}/cancel`,{});return this.logger.info(`Cancel payout ${e}: ${t.status}`),t}};var Tt=z$1.object({name:z$1.string().min(1).max(100),description:z$1.string().max(500).optional(),price:z$1.number().positive(),currency:z$1.enum(["XAF","XOF","USD"]),metadata:z$1.record(z$1.unknown()).optional()}),Ia=z$1.object({productId:z$1.string().uuid(),domain:z$1.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]?\.[a-zA-Z]{2,}$/)}),We=class{constructor(e){this.logger=e;this.products=new Map;}async create(e){let t=Tt.parse(e),r=crypto.randomUUID(),i=new Date().toISOString(),u={id:r,name:t.name,description:t.description,price:t.price,currency:t.currency,domains:[],created:i,updated:i,metadata:t.metadata};return this.products.set(r,u),this.logger.info(`Created product ${r}`,{name:t.name}),this.toProduct(u)}async get(e){let t=this.products.get(e);if(!t)throw v.notFound(`Product ${e} not found`);return this.toProduct(t)}async list(){return Array.from(this.products.values()).map(e=>this.toProduct(e))}async update(e,t){let r=this.products.get(e);if(!r)throw v.notFound(`Product ${e} not found`);let i=Tt.partial().parse(t),u={...r,...i,updated:new Date().toISOString()};return this.products.set(e,u),this.logger.info(`Updated product ${e}`),this.toProduct(u)}async delete(e){if(!this.products.get(e))throw v.notFound(`Product ${e} not found`);this.products.delete(e),this.logger.info(`Deleted product ${e}`);}async addDomain(e){let t=Ia.parse(e),r=this.products.get(t.productId);if(!r)throw v.notFound(`Product ${t.productId} not found`);if(r.domains.includes(t.domain))throw v.validation(`Domain ${t.domain} already added to product`);return r.domains.push(t.domain),r.updated=new Date().toISOString(),this.logger.info(`Added domain ${t.domain} to product ${t.productId}`),this.toProduct(r)}async removeDomain(e,t){let r=this.products.get(e);if(!r)throw v.notFound(`Product ${e} not found`);let i=r.domains.indexOf(t);if(i===-1)throw v.notFound(`Domain ${t} not found in product`);return r.domains.splice(i,1),r.updated=new Date().toISOString(),this.logger.info(`Removed domain ${t} from product ${e}`),this.toProduct(r)}toProduct(e){return {id:e.id,name:e.name,description:e.description,price:e.price,currency:e.currency,domains:[...e.domains],created:e.created,updated:e.updated}}};var $e=class{constructor(e,t,r){this.httpClient=e;this.logger=t;this.webhookSecret=r?.webhookSecret;}setWebhookSecret(e){this.webhookSecret=e;}verifySignature(e,t){if(!this.webhookSecret)return this.logger.warn("Webhook secret not configured, skipping signature verification"),true;if(!t)return this.logger.warn("No signature provided in webhook request"),false;try{let r=createHmac("sha256",this.webhookSecret).update(e,"utf8").digest("hex"),i=Buffer.from(t,"hex"),u=Buffer.from(r,"hex");return i.length!==u.length?!1:timingSafeEqual(i,u)}catch(r){return this.logger.error("Error verifying webhook signature",r),false}}parseEvent(e){try{let t=JSON.parse(e);if(!t.eventId||!t.eventType||!t.timestamp)throw new Error("Invalid webhook event structure");return t}catch(t){throw v.validation(`Failed to parse webhook event: ${t instanceof Error?t.message:"Unknown error"}`)}}constructEvent(e,t){if(!this.verifySignature(e,t))throw v.unauthorized("Invalid webhook signature");return this.parseEvent(e)}async registerCallback(e){this.logger.info(`Registering callback URL: ${e}`),await this.httpClient.post("/webhooks",{url:e}),this.logger.info("Callback URL registered successfully");}async unregisterCallback(){this.logger.info("Unregistering callback URL"),await this.httpClient.delete("/webhooks"),this.logger.info("Callback URL unregistered successfully");}isDepositEvent(e){return e.startsWith("deposit.")}isPayoutEvent(e){return e.startsWith("payout.")}isRefundEvent(e){return e.startsWith("refund.")}isSuccessEvent(e){return e.endsWith(".completed")}isFailureEvent(e){return e.endsWith(".failed")}};var Ge=class{constructor(e,t){this.httpClient=e;this.logger=t;}generateTransactionId(){return v4()}validateTransactionId(e){return validate(e)&&version(e)===4}async getActiveConfiguration(e){let t={};e?.country&&(t.country=e.country),e?.operationType&&(t.operationType=e.operationType),this.logger.info("Fetching active configuration",e);let r=await this.httpClient.get("/v2/active-conf",{params:Object.keys(t).length>0?t:void 0});return this.logger.info(`Retrieved configuration for ${r.countries.length} countries`),r}async getProviderAvailability(e){let t={};return e?.country&&(t.country=e.country),e?.operationType&&(t.operationType=e.operationType),this.logger.info("Fetching provider availability",e),await this.httpClient.get("/v2/availability",{params:Object.keys(t).length>0?t:void 0})}async predictProvider(e){this.logger.info("Predicting provider for phone number");let t=await this.httpClient.post("/v2/predict-provider",{phoneNumber:e});return this.logger.info(`Predicted provider: ${t.provider} (${t.country})`),t}async getPublicKeys(){this.logger.info("Fetching public keys");let e=await this.httpClient.get("/v2/public-key/http");return this.logger.info(`Retrieved ${e.length} public keys`),e}async getTransactionLimits(e){try{let t=await this.getActiveConfiguration();for(let r of t.countries)for(let i of r.providers)if(i.provider===e){let u=i.currencies[0];if(u?.operationTypes){let b=u.operationTypes.DEPOSIT,h=u.operationTypes.PAYOUT,f=Fe[e];return {minDeposit:b?.minAmount?parseFloat(b.minAmount):f.minDeposit,maxDeposit:b?.maxAmount?parseFloat(b.maxAmount):f.maxDeposit,minPayout:h?.minAmount?parseFloat(h.minAmount):f.minPayout,maxPayout:h?.maxAmount?parseFloat(h.maxAmount):f.maxPayout,currency:u.currency,dailyLimit:f.dailyLimit}}}}catch(t){this.logger.warn(`Failed to fetch live limits for ${e}, using defaults`,t);}return Fe[e]}async checkMMOAvailability(e){try{let t=await this.getProviderAvailability();for(let r of t){let i=r.providers.find(u=>u.provider===e);if(i){let u=i.operationTypes.find(l=>l.operationType==="DEPOSIT"),b=i.operationTypes.find(l=>l.operationType==="PAYOUT"),h=u?.status==="OPERATIONAL"||b?.status==="OPERATIONAL",f=u?.status==="DELAYED"||b?.status==="DELAYED",D=u?.status==="CLOSED"&&b?.status==="CLOSED";return {correspondent:e,available:h||f,degraded:f,message:D?"Provider is currently closed":void 0}}}return {correspondent:e,available:!1,degraded:!1,message:"Correspondent not found in availability list"}}catch(t){return this.logger.warn(`Failed to check MMO availability for ${e}`,t),{correspondent:e,available:false,degraded:true,message:"Unable to verify availability"}}}formatPhoneNumber(e,t){let r=e.replace(/\D/g,"");r.startsWith("00")&&(r=r.slice(2));let u={CMR:"237",COG:"242",GAB:"241",ZMB:"260",GHA:"233",KEN:"254",TZA:"255",UGA:"256",RWA:"250",BEN:"229",CIV:"225",SEN:"221"}[t.toUpperCase()];return u&&!r.startsWith(u)&&(r.startsWith("0")&&(r=r.slice(1)),r=u+r),r}validatePhoneNumber(e,t){let r=ve[t];if(!r)return false;let i=e.replace(/\D/g,"");return r.phoneRegex.test(i)}getSupportedCorrespondents(){return he}getCorrespondentInfo(e){return ve[e]}getAllCorrespondentsInfo(){return Object.values(ve)}detectCorrespondent(e){let t=e.replace(/\D/g,"");for(let[r,i]of Object.entries(ve))if(i.phoneRegex.test(t))return r;return null}};var $a=z$1.object({wallet:z$1.object({country:z$1.string().length(3),currency:z$1.string().length(3),provider:z$1.string().optional()}),callbackUrl:z$1.string().url(),startDate:z$1.string(),endDate:z$1.string(),compressed:z$1.boolean().optional()}),je=class{constructor(e,t){this.httpClient=e;this.logger=t;}async getWalletBalances(){this.logger.info("Fetching wallet balances");let e=await this.httpClient.get("/v2/wallets/balances");return this.logger.info(`Retrieved ${e.balances.length} wallet balances`),e.balances}async generateStatement(e){let t=$a.parse(e);this.logger.info("Generating statement",{wallet:t.wallet,startDate:t.startDate,endDate:t.endDate});let r=await this.httpClient.post("/v2/statements",t);if(r.status==="REJECTED"&&r.failureReason)throw v.fromPawapayResponse(r.failureReason.failureCode,r.failureReason.failureMessage);return this.logger.info(`Statement ${r.statementId} status: ${r.status}`),r}async checkStatementStatus(e){if(!z$1.string().uuid().safeParse(e).success)throw v.validation("Invalid statement ID format");let t=await this.httpClient.get(`/v2/statements/${e}`);if(t.status==="NOT_FOUND"||!t.data)throw v.notFound(`Statement ${e} not found`);return this.logger.info(`Statement ${e} status: ${t.data.status}`),t.data}async pollStatementUntilComplete(e,t={}){let{interval:r=5e3,maxAttempts:i=24}=t;for(let u=1;u<=i;u++){let b=await this.checkStatementStatus(e);if(b.status==="COMPLETED"||b.status==="FAILED")return b;u<i&&await new Promise(h=>setTimeout(h,r));}return this.checkStatementStatus(e)}};var et=class{constructor(e){let r={...Ct(),...e};this.config=Nt(r),this.logger=new Pe("SpaarkPayApiSdk",this.config.logLevel),this.httpClient=_e.fromConfig(this.config,this.logger),this.transactions=new Ue(this.httpClient,this.logger),this.products=new We(this.logger),this.webhooks=new $e(this.httpClient,this.logger,{webhookSecret:this.getWebhookSecretFromEnv()}),this.utils=new Ge(this.httpClient,this.logger),this.finances=new je(this.httpClient,this.logger),this.logger.info("SpaarkPayApiSdk initialized",{environment:this.config.environment,baseUrl:this.config.baseUrl});}getWebhookSecretFromEnv(){if(typeof process<"u"&&process.env)return process.env.PAWAPAY_WEBHOOK_SECRET}getConfig(){return {...this.config}}setLogLevel(e){this.logger.setLevel(e);}setWebhookSecret(e){this.webhooks.setWebhookSecret(e);}};var me=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{let e=Math.random()*16|0;return (n==="x"?e:e&3|8).toString(16)});function Ga(n,e={}){let{transactionId:t=me(),amount:r="5000",currency:i="XAF",correspondent:u="MTN_MOMO_CMR",phoneNumber:b="237670000000",status:h=n==="deposit.failed"?"FAILED":"COMPLETED",failureCode:f="INSUFFICIENT_FUNDS",failureMessage:D="The payer has insufficient funds"}=e,l=new Date().toISOString(),k={depositId:t,status:h,amount:r,currency:i,correspondent:u,payer:{type:"MSISDN",address:{value:b}},customerTimestamp:l,created:l};return h==="COMPLETED"&&(k.receivedByPayer=l),h==="FAILED"&&(k.failureReason={failureCode:f,failureMessage:D}),{eventId:me(),eventType:n,timestamp:l,data:k}}function ja(n,e={}){let{transactionId:t=me(),amount:r="5000",currency:i="XAF",correspondent:u="MTN_MOMO_CMR",phoneNumber:b="237670000000",status:h=n==="payout.failed"?"FAILED":"COMPLETED",failureCode:f="RECIPIENT_NOT_FOUND",failureMessage:D="The recipient account was not found"}=e,l=new Date().toISOString(),k={payoutId:t,status:h,amount:r,currency:i,correspondent:u,recipient:{type:"MSISDN",address:{value:b}},customerTimestamp:l,created:l};return h==="COMPLETED"&&(k.receivedByRecipient=l),h==="FAILED"&&(k.failureReason={failureCode:f,failureMessage:D}),{eventId:me(),eventType:n,timestamp:l,data:k}}function Ha(n,e={}){let{transactionId:t=me(),depositId:r=me(),amount:i="5000",currency:u="XAF",correspondent:b="MTN_MOMO_CMR",phoneNumber:h="237670000000",status:f=n==="refund.failed"?"FAILED":"COMPLETED",failureCode:D="REFUND_LIMIT_EXCEEDED",failureMessage:l="The refund limit has been exceeded"}=e,k=new Date().toISOString(),m={refundId:t,depositId:r,status:f,amount:i,currency:u,correspondent:b,recipient:{type:"MSISDN",address:{value:h}},created:k};return f==="FAILED"&&(m.failureReason={failureCode:D,failureMessage:l}),{eventId:me(),eventType:n,timestamp:k,data:m}}function wt(n,e={}){return n.startsWith("deposit.")?Ga(n,e):n.startsWith("payout.")?ja(n,e):Ha(n,e)}var Rt=["deposit.accepted","deposit.completed","deposit.failed","payout.accepted","payout.completed","payout.failed","refund.completed","refund.failed"];function w(...n){return twMerge(clsx(n))}var ho={fr:{title:"Tableau de bord financier",subtitle:"Vue d'ensemble de vos transactions",totalVolume:"Volume Total",deposits:"D\xE9p\xF4ts",payouts:"Retraits",failed:"\xC9checs",refunds:"Remboursements",pending:"En attente",completed:"Compl\xE9t\xE9es",cancelled:"Annul\xE9es",search:"Rechercher par ID ou t\xE9l\xE9phone...",allTypes:"Tous les types",allStatuses:"Tous les statuts",deposit:"D\xE9p\xF4t",payout:"Retrait",refund:"Remboursement",expertMode:"Mode Expert",refresh:"Actualiser",settings:"Param\xE8tres",actions:"Actions",noTransactions:"Aucune transaction",noTransactionsDesc:"Les transactions appara\xEEtront ici une fois effectu\xE9es.",addTransaction:"Nouvelle transaction",id:"ID",type:"Type",amount:"Montant",status:"Statut",provider:"Op\xE9rateur",phone:"T\xE9l\xE9phone",date:"Date",page:"Page",of:"sur",transactions:"transactions",copied:"Copi\xE9 !",dashboard:"Tableau de bord",charts:"Graphiques",volumeOverTime:"Volume dans le temps",transactionsByType:"Par type",statusDistribution:"Par statut",noDataForCharts:"Pas de donn\xE9es pour les graphiques",loading:"Chargement...",previous:"Pr\xE9c\xE9dent",next:"Suivant"},en:{title:"Finance Dashboard",subtitle:"Overview of your transactions",totalVolume:"Total Volume",deposits:"Deposits",payouts:"Payouts",failed:"Failed",refunds:"Refunds",pending:"Pending",completed:"Completed",cancelled:"Cancelled",search:"Search by ID or phone...",allTypes:"All types",allStatuses:"All statuses",deposit:"Deposit",payout:"Payout",refund:"Refund",expertMode:"Expert Mode",refresh:"Refresh",settings:"Settings",actions:"Actions",noTransactions:"No transactions",noTransactionsDesc:"Transactions will appear here once made.",addTransaction:"New transaction",id:"ID",type:"Type",amount:"Amount",status:"Status",provider:"Provider",phone:"Phone",date:"Date",page:"Page",of:"of",transactions:"transactions",copied:"Copied!",dashboard:"Dashboard",charts:"Charts",volumeOverTime:"Volume over time",transactionsByType:"By type",statusDistribution:"By status",noDataForCharts:"No data for charts",loading:"Loading...",previous:"Previous",next:"Next"}},vo={COMPLETED:"bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200",ACCEPTED:"bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200",PENDING:"bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200",ENQUEUED:"bg-yellow-100 text-yellow-800 dark:bg-yellow-900 dark:text-yellow-200",PROCESSING:"bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200",FAILED:"bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200",CANCELLED:"bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-200",REJECTED:"bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200"},W={deposit:"#22c55e",payout:"#3b82f6",refund:"#f97316",COMPLETED:"#22c55e",PENDING:"#eab308",FAILED:"#ef4444",CANCELLED:"#6b7280"},fe=forwardRef(({className:n,variant:e="default",size:t="default",...r},i)=>jsx("button",{ref:i,className:w("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",{"bg-primary text-primary-foreground hover:bg-primary/90":e==="default","border border-input bg-background hover:bg-accent hover:text-accent-foreground":e==="outline","hover:bg-accent hover:text-accent-foreground":e==="ghost","bg-secondary text-secondary-foreground hover:bg-secondary/80":e==="secondary"},{"h-10 px-4 py-2":t==="default","h-9 rounded-md px-3":t==="sm","h-11 rounded-md px-8":t==="lg","h-10 w-10":t==="icon"},n),...r}));fe.displayName="Button";var xo=z.Root,Kt=forwardRef(({className:n,...e},t)=>jsx(z.List,{ref:t,className:w("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",n),...e}));Kt.displayName=z.List.displayName;var st=forwardRef(({className:n,...e},t)=>jsx(z.Trigger,{ref:t,className:w("inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1.5 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=inactive]:text-muted-foreground data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",n),...e}));st.displayName=z.Trigger.displayName;var nt=forwardRef(({className:n,...e},t)=>jsx(z.Content,{ref:t,className:w("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",n),...e}));nt.displayName=z.Content.displayName;var Ft=S.Root,Ut=S.Value,it=forwardRef(({className:n,children:e,...t},r)=>jsxs(S.Trigger,{ref:r,className:w("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",n),...t,children:[e,jsx(S.Icon,{asChild:true,children:jsx(ChevronDown,{className:"h-4 w-4 opacity-50"})})]}));it.displayName=S.Trigger.displayName;var dt=forwardRef(({className:n,children:e,position:t="popper",...r},i)=>jsx(S.Portal,{children:jsx(S.Content,{ref:i,className:w("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",t==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",n),position:t,...r,children:jsx(S.Viewport,{className:w("p-1",t==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:e})})}));dt.displayName=S.Content.displayName;var $=forwardRef(({className:n,children:e,...t},r)=>jsxs(S.Item,{ref:r,className:w("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",n),...t,children:[jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:jsx(S.ItemIndicator,{children:jsx(Check,{className:"h-3 w-3"})})}),jsx(S.ItemText,{children:e})]}));$.displayName=S.Item.displayName;function No({trigger:n,children:e,align:t="end"}){let[r,i]=useState(false),u=useRef(null);return useEffect(()=>{if(!r)return;function b(h){u.current&&!u.current.contains(h.target)&&i(false);}return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[r]),jsxs("div",{ref:u,className:"relative",children:[jsx("div",{onClick:()=>i(!r),children:n}),r&&jsx("div",{className:w("absolute z-50 mt-1 min-w-[160px] rounded-md border bg-popover p-1 shadow-md",t==="end"?"right-0":"left-0"),children:e})]})}function Wt({children:n,onClick:e,icon:t}){return jsxs("button",{onClick:e,className:"flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none hover:bg-accent hover:text-accent-foreground",children:[t,n]})}var F=forwardRef(({className:n,...e},t)=>jsx("div",{ref:t,className:w("rounded-lg border bg-card text-card-foreground shadow-sm",n),...e}));F.displayName="Card";var G=forwardRef(({className:n,...e},t)=>jsx("div",{ref:t,className:w("flex flex-col space-y-1.5 p-6",n),...e}));G.displayName="CardHeader";var Ve=forwardRef(({className:n,...e},t)=>jsx("h3",{ref:t,className:w("text-lg font-semibold leading-none tracking-tight",n),...e}));Ve.displayName="CardTitle";var j=forwardRef(({className:n,...e},t)=>jsx("div",{ref:t,className:w("p-6 pt-0",n),...e}));j.displayName="CardContent";var Xt=forwardRef(({className:n,type:e,...t},r)=>jsx("input",{type:e,className:w("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",n),ref:r,...t}));Xt.displayName="Input";var zt=forwardRef(({className:n,...e},t)=>jsx("div",{className:"relative w-full overflow-auto",children:jsx("table",{ref:t,className:w("w-full caption-bottom text-sm",n),...e})}));zt.displayName="Table";var Jt=forwardRef(({className:n,...e},t)=>jsx("thead",{ref:t,className:w("[&_tr]:border-b",n),...e}));Jt.displayName="TableHeader";var Yt=forwardRef(({className:n,...e},t)=>jsx("tbody",{ref:t,className:w("[&_tr:last-child]:border-0",n),...e}));Yt.displayName="TableBody";var lt=forwardRef(({className:n,...e},t)=>jsx("tr",{ref:t,className:w("border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",n),...e}));lt.displayName="TableRow";var Zt=forwardRef(({className:n,...e},t)=>jsx("th",{ref:t,className:w("h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",n),...e}));Zt.displayName="TableHead";var Qt=forwardRef(({className:n,...e},t)=>jsx("td",{ref:t,className:w("p-4 align-middle [&:has([role=checkbox])]:pr-0",n),...e}));Qt.displayName="TableCell";var X=({className:n,...e})=>jsx("div",{className:w("animate-pulse rounded-md bg-muted",n),...e}),Co=({className:n})=>jsxs("svg",{className:w("animate-spin",n),xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",children:[jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})]}),$t=({icon:n=Inbox,title:e,description:t,action:r})=>jsxs("div",{className:"flex flex-col items-center justify-center py-12 px-4 text-center",children:[jsx("div",{className:"flex h-20 w-20 items-center justify-center rounded-full bg-muted",children:jsx(n,{className:"h-10 w-10 text-muted-foreground"})}),jsx("h3",{className:"mt-4 text-lg font-semibold",children:e}),t&&jsx("p",{className:"mt-2 text-sm text-muted-foreground max-w-sm",children:t}),r&&jsx("div",{className:"mt-6",children:r})]}),Eo=({status:n})=>{switch(n){case "COMPLETED":return jsx(CheckCircle2,{className:"w-3.5 h-3.5"});case "FAILED":case "REJECTED":return jsx(XCircle,{className:"w-3.5 h-3.5"});case "CANCELLED":return jsx(Ban,{className:"w-3.5 h-3.5"});case "PENDING":case "ENQUEUED":return jsx(Clock,{className:"w-3.5 h-3.5"});case "PROCESSING":case "ACCEPTED":return jsx(Co,{className:"w-3.5 h-3.5"});default:return jsx(AlertCircle,{className:"w-3.5 h-3.5"})}},xe=(n,e)=>new Intl.NumberFormat("fr-FR",{style:"decimal",minimumFractionDigits:0,maximumFractionDigits:0}).format(n)+" "+e,To=(n,e)=>{let t=new Date(n);return new Intl.DateTimeFormat(e==="fr"?"fr-FR":"en-US",{day:"2-digit",month:"short",year:"numeric",hour:"2-digit",minute:"2-digit"}).format(t)};function ct({transactions:n,title:e,subtitle:t,locale:r="fr",className:i="",showExpertMode:u=true,onExpertModeClick:b,onTransactionClick:h,onRefresh:f,onAddTransaction:D,onSettings:l,isLoading:k=false}){let m=ho[r],[ie,ke]=useState(""),[ee,U]=useState("all"),[V,H]=useState("all"),[ye,te]=useState(null),[De,de]=useState("dashboard"),[Ae,le]=useState([]),P=useMemo(()=>{let p=n.filter(x=>x.type==="deposit"),E=n.filter(x=>x.type==="payout"),K=n.filter(x=>x.type==="refund"),ce=n.filter(x=>x.status==="FAILED"||x.status==="REJECTED"),I=n.filter(x=>["PENDING","ENQUEUED","PROCESSING","ACCEPTED"].includes(x.status)),Y=n.filter(x=>x.status==="COMPLETED"),re=n.filter(x=>x.status==="CANCELLED"),Ee=n.filter(x=>x.status==="COMPLETED").reduce((x,_)=>x+_.amount,0),Me=p.filter(x=>x.status==="COMPLETED").reduce((x,_)=>x+_.amount,0),Ke=E.filter(x=>x.status==="COMPLETED").reduce((x,_)=>x+_.amount,0),Oe=K.filter(x=>x.status==="COMPLETED").reduce((x,_)=>x+_.amount,0),Xe=p.reduce((x,_)=>x+_.amount,0),Te=E.reduce((x,_)=>x+_.amount,0),ze=K.reduce((x,_)=>x+_.amount,0);return {totalVolume:Ee,depositsCount:p.length,depositsTotal:Me,depositsAllTotal:Xe,payoutsCount:E.length,payoutsTotal:Ke,payoutsAllTotal:Te,failedCount:ce.length,refundsCount:K.length,refundsTotal:Oe,refundsAllTotal:ze,pendingCount:I.length,completedCount:Y.length,cancelledCount:re.length}},[n]),ae=useMemo(()=>{let p={};n.forEach(I=>{let Y=new Date(I.createdAt),re=Y.toLocaleDateString(r==="fr"?"fr-FR":"en-US",{day:"2-digit",month:"short"});p[re]||(p[re]={date:re,dateSort:Y.getTime(),deposits:0,payouts:0,refunds:0});let Ee=I.type==="deposit"?"deposits":I.type==="payout"?"payouts":"refunds";p[re][Ee]+=I.amount;});let E=Object.values(p).sort((I,Y)=>I.dateSort-Y.dateSort).slice(-7).map(({dateSort:I,...Y})=>Y),K=[{name:m.deposit,value:P.depositsAllTotal,count:P.depositsCount,fill:W.deposit},{name:m.payout,value:P.payoutsAllTotal,count:P.payoutsCount,fill:W.payout},{name:m.refund,value:P.refundsAllTotal,count:P.refundsCount,fill:W.refund}],ce=[{name:"Completed",value:P.completedCount,fill:W.COMPLETED},{name:"Pending",value:P.pendingCount,fill:W.PENDING},{name:"Failed",value:P.failedCount,fill:W.FAILED},{name:"Cancelled",value:P.cancelledCount,fill:W.CANCELLED}].filter(I=>I.value>0);return {volumeData:E,typeData:K,statusData:ce}},[n,P,r,m]),Ne=useMemo(()=>n.filter(p=>{let E=ie===""||p.id.toLowerCase().includes(ie.toLowerCase())||p.phoneNumber.includes(ie),K=ee==="all"||p.type===ee,ce=V==="all"||p.status===V;return E&&K&&ce}),[n,ie,ee,V]),B=useCallback(p=>{navigator.clipboard.writeText(p),te(p),setTimeout(()=>te(null),2e3);},[]),oe=n[0]?.currency||"XAF",Ce=useMemo(()=>[{accessorKey:"id",header:m.id,cell:({row:p})=>jsxs("div",{className:"flex items-center gap-2",children:[jsxs("span",{className:"font-mono text-xs truncate max-w-[100px]",title:p.original.id,children:[p.original.id.slice(0,8),"..."]}),jsx(fe,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:E=>{E.stopPropagation(),B(p.original.id);},children:ye===p.original.id?jsx(Check,{className:"w-3.5 h-3.5 text-green-600"}):jsx(Copy,{className:"w-3.5 h-3.5 text-muted-foreground"})})]})},{accessorKey:"type",header:m.type,cell:({row:p})=>jsxs("span",{className:w("inline-flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded-full",p.original.type==="deposit"&&"bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200",p.original.type==="payout"&&"bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200",p.original.type==="refund"&&"bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-200"),children:[p.original.type==="deposit"&&jsx(ArrowDownCircle,{className:"w-3 h-3"}),p.original.type==="payout"&&jsx(ArrowUpCircle,{className:"w-3 h-3"}),p.original.type==="refund"&&jsx(RefreshCw,{className:"w-3 h-3"}),m[p.original.type]]})},{accessorKey:"amount",header:m.amount,cell:({row:p})=>jsx("span",{className:"font-semibold",children:xe(p.original.amount,p.original.currency)})},{accessorKey:"status",header:m.status,cell:({row:p})=>jsxs("span",{className:w("inline-flex items-center gap-1.5 px-2.5 py-1 text-xs font-medium rounded-full",vo[p.original.status]),children:[jsx(Eo,{status:p.original.status}),p.original.status]})},{accessorKey:"provider",header:m.provider,cell:({row:p})=>jsx("span",{className:"text-muted-foreground",children:p.original.provider.replace(/_/g," ")})},{accessorKey:"phoneNumber",header:m.phone,cell:({row:p})=>jsx("span",{className:"font-mono text-muted-foreground",children:p.original.phoneNumber})},{accessorKey:"createdAt",header:m.date,cell:({row:p})=>jsx("span",{className:"text-muted-foreground",children:To(p.original.createdAt,r)})}],[m,r,ye,B]),q=useReactTable({data:Ne,columns:Ce,getCoreRowModel:getCoreRowModel(),getPaginationRowModel:getPaginationRowModel(),getFilteredRowModel:getFilteredRowModel(),onColumnFiltersChange:le,state:{columnFilters:Ae},initialState:{pagination:{pageSize:10}}}),L=()=>jsx("div",{className:"space-y-3 p-4",children:Array.from({length:5}).map((p,E)=>jsxs("div",{className:"flex items-center gap-4",children:[jsx(X,{className:"h-4 w-24"}),jsx(X,{className:"h-6 w-16 rounded-full"}),jsx(X,{className:"h-4 w-20"}),jsx(X,{className:"h-6 w-20 rounded-full"}),jsx(X,{className:"h-4 w-24"}),jsx(X,{className:"h-4 w-28"}),jsx(X,{className:"h-4 w-32"})]},E))}),R=()=>jsxs(F,{children:[jsx(G,{className:"pb-2",children:jsxs("div",{className:"flex items-center gap-2",children:[jsx(X,{className:"h-8 w-8 rounded-md"}),jsx(X,{className:"h-4 w-24"})]})}),jsxs(j,{children:[jsx(X,{className:"h-8 w-32 mb-2"}),jsx(X,{className:"h-3 w-20"})]})]});return jsxs(xo,{value:De,onValueChange:de,className:w("space-y-6",i),children:[jsxs("div",{className:"flex items-center justify-between flex-wrap gap-4",children:[jsxs("div",{children:[jsx("h1",{className:"text-2xl font-bold tracking-tight",children:e||m.title}),jsx("p",{className:"text-muted-foreground mt-1",children:t||m.subtitle})]}),jsxs("div",{className:"flex items-center gap-2",children:[jsxs(Kt,{className:"h-9",children:[jsxs(st,{value:"dashboard",className:"gap-2 h-7",children:[jsx(LayoutDashboard,{className:"w-4 h-4"}),m.dashboard]}),jsxs(st,{value:"charts",className:"gap-2 h-7",children:[jsx(BarChart3,{className:"w-4 h-4"}),m.charts]})]}),f&&jsxs(fe,{variant:"outline",size:"sm",className:"h-9",onClick:f,disabled:k,children:[jsx(RefreshCw,{className:w("w-4 h-4",k&&"animate-spin")}),m.refresh]}),(l||u&&b)&&jsxs(No,{trigger:jsxs(fe,{variant:"outline",size:"sm",className:"h-9 gap-1",children:[jsx(MoreVertical,{className:"w-4 h-4"}),m.actions,jsx(ChevronDown,{className:"w-3 h-3 opacity-50"})]}),children:[l&&jsx(Wt,{onClick:l,icon:jsx(Settings,{className:"w-4 h-4"}),children:m.settings}),u&&b&&jsx(Wt,{onClick:b,icon:jsx(FlaskConical,{className:"w-4 h-4"}),children:m.expertMode})]})]})]}),jsxs(nt,{value:"dashboard",className:"space-y-6",children:[jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:k?jsx(Fragment,{children:Array.from({length:8}).map((p,E)=>jsx(R,{},E))}):jsxs(Fragment,{children:[jsxs(F,{children:[jsx(G,{className:"pb-2",children:jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"p-2 rounded-md bg-primary/10",children:jsx(TrendingUp,{className:"w-4 h-4 text-primary"})}),jsx("span",{className:"text-sm font-medium text-muted-foreground",children:m.totalVolume})]})}),jsxs(j,{children:[jsx("p",{className:"text-2xl font-bold",children:xe(P.totalVolume,oe)}),jsxs("p",{className:"text-xs text-muted-foreground",children:[n.length," ",m.transactions]})]})]}),jsxs(F,{children:[jsx(G,{className:"pb-2",children:jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"p-2 rounded-md bg-green-500/10",children:jsx(ArrowDownCircle,{className:"w-4 h-4 text-green-600 dark:text-green-400"})}),jsx("span",{className:"text-sm font-medium text-muted-foreground",children:m.deposits})]})}),jsxs(j,{children:[jsx("p",{className:"text-2xl font-bold",children:xe(P.depositsTotal,oe)}),jsxs("p",{className:"text-xs text-muted-foreground",children:[P.depositsCount," ",m.transactions]})]})]}),jsxs(F,{children:[jsx(G,{className:"pb-2",children:jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"p-2 rounded-md bg-blue-500/10",children:jsx(ArrowUpCircle,{className:"w-4 h-4 text-blue-600 dark:text-blue-400"})}),jsx("span",{className:"text-sm font-medium text-muted-foreground",children:m.payouts})]})}),jsxs(j,{children:[jsx("p",{className:"text-2xl font-bold",children:xe(P.payoutsTotal,oe)}),jsxs("p",{className:"text-xs text-muted-foreground",children:[P.payoutsCount," ",m.transactions]})]})]}),jsxs(F,{children:[jsx(G,{className:"pb-2",children:jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"p-2 rounded-md bg-orange-500/10",children:jsx(RefreshCw,{className:"w-4 h-4 text-orange-600 dark:text-orange-400"})}),jsx("span",{className:"text-sm font-medium text-muted-foreground",children:m.refunds})]})}),jsxs(j,{children:[jsx("p",{className:"text-2xl font-bold",children:xe(P.refundsTotal,oe)}),jsxs("p",{className:"text-xs text-muted-foreground",children:[P.refundsCount," ",m.transactions]})]})]}),jsxs(F,{children:[jsx(G,{className:"pb-2",children:jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"p-2 rounded-md bg-yellow-500/10",children:jsx(Hourglass,{className:"w-4 h-4 text-yellow-600 dark:text-yellow-400"})}),jsx("span",{className:"text-sm font-medium text-muted-foreground",children:m.pending})]})}),jsxs(j,{children:[jsx("p",{className:"text-2xl font-bold",children:P.pendingCount}),jsx("p",{className:"text-xs text-muted-foreground",children:m.transactions})]})]}),jsxs(F,{children:[jsx(G,{className:"pb-2",children:jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"p-2 rounded-md bg-green-500/10",children:jsx(CheckCircle2,{className:"w-4 h-4 text-green-600 dark:text-green-400"})}),jsx("span",{className:"text-sm font-medium text-muted-foreground",children:m.completed})]})}),jsxs(j,{children:[jsx("p",{className:"text-2xl font-bold",children:P.completedCount}),jsx("p",{className:"text-xs text-muted-foreground",children:m.transactions})]})]}),jsxs(F,{children:[jsx(G,{className:"pb-2",children:jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"p-2 rounded-md bg-red-500/10",children:jsx(XCircle,{className:"w-4 h-4 text-red-600 dark:text-red-400"})}),jsx("span",{className:"text-sm font-medium text-muted-foreground",children:m.failed})]})}),jsxs(j,{children:[jsx("p",{className:"text-2xl font-bold",children:P.failedCount}),jsx("p",{className:"text-xs text-muted-foreground",children:m.transactions})]})]}),jsxs(F,{children:[jsx(G,{className:"pb-2",children:jsxs("div",{className:"flex items-center gap-2",children:[jsx("div",{className:"p-2 rounded-md bg-gray-500/10",children:jsx(Ban,{className:"w-4 h-4 text-gray-600 dark:text-gray-400"})}),jsx("span",{className:"text-sm font-medium text-muted-foreground",children:m.cancelled})]})}),jsxs(j,{children:[jsx("p",{className:"text-2xl font-bold",children:P.cancelledCount}),jsx("p",{className:"text-xs text-muted-foreground",children:m.transactions})]})]})]})}),jsxs("div",{className:"flex flex-wrap gap-3",children:[jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[jsx(Search,{className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground pointer-events-none"}),jsx(Xt,{type:"text",placeholder:m.search,value:ie,onChange:p=>ke(p.target.value),className:"pl-9"})]}),jsxs(Ft,{value:ee,onValueChange:p=>U(p),children:[jsx(it,{className:"w-[160px]",children:jsx(Ut,{placeholder:m.allTypes})}),jsxs(dt,{children:[jsx($,{value:"all",children:m.allTypes}),jsx($,{value:"deposit",children:m.deposit}),jsx($,{value:"payout",children:m.payout}),jsx($,{value:"refund",children:m.refund})]})]}),jsxs(Ft,{value:V,onValueChange:p=>H(p),children:[jsx(it,{className:"w-[160px]",children:jsx(Ut,{placeholder:m.allStatuses})}),jsxs(dt,{children:[jsx($,{value:"all",children:m.allStatuses}),jsx($,{value:"COMPLETED",children:"COMPLETED"}),jsx($,{value:"PENDING",children:"PENDING"}),jsx($,{value:"PROCESSING",children:"PROCESSING"}),jsx($,{value:"ACCEPTED",children:"ACCEPTED"}),jsx($,{value:"FAILED",children:"FAILED"}),jsx($,{value:"CANCELLED",children:"CANCELLED"}),jsx($,{value:"REJECTED",children:"REJECTED"})]})]})]}),jsx(F,{children:k?jsx(L,{}):Ne.length===0?jsx($t,{icon:Inbox,title:m.noTransactions,description:m.noTransactionsDesc,action:D&&jsxs(fe,{onClick:D,children:[jsx(Plus,{className:"w-4 h-4"}),m.addTransaction]})}):jsxs(Fragment,{children:[jsxs(zt,{children:[jsx(Jt,{children:q.getHeaderGroups().map(p=>jsx(lt,{children:p.headers.map(E=>jsx(Zt,{children:E.isPlaceholder?null:flexRender(E.column.columnDef.header,E.getContext())},E.id))},p.id))}),jsx(Yt,{children:q.getRowModel().rows.map(p=>jsx(lt,{onClick:()=>h?.(p.original),className:h?"cursor-pointer":"",children:p.getVisibleCells().map(E=>jsx(Qt,{children:flexRender(E.column.columnDef.cell,E.getContext())},E.id))},p.id))})]}),jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-t",children:[jsxs("p",{className:"text-sm text-muted-foreground",children:[Ne.length," ",m.transactions]}),jsxs("div",{className:"flex items-center gap-2",children:[jsxs(fe,{variant:"outline",size:"sm",onClick:()=>q.previousPage(),disabled:!q.getCanPreviousPage(),children:[jsx(ChevronLeft,{className:"w-4 h-4"}),m.previous]}),jsxs("span",{className:"text-sm px-2",children:[m.page," ",q.getState().pagination.pageIndex+1," ",m.of," ",q.getPageCount()]}),jsxs(fe,{variant:"outline",size:"sm",onClick:()=>q.nextPage(),disabled:!q.getCanNextPage(),children:[m.next,jsx(ChevronRight,{className:"w-4 h-4"})]})]})]})]})})]}),jsx(nt,{value:"charts",className:"space-y-6",children:n.length===0?jsx(F,{children:jsx($t,{icon:BarChart3,title:m.noDataForCharts,description:m.noTransactionsDesc})}):jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[jsxs(F,{className:"col-span-1 lg:col-span-2",children:[jsx(G,{children:jsx(Ve,{children:m.volumeOverTime})}),jsx(j,{children:jsx("div",{className:"h-[300px]",children:jsx(ResponsiveContainer,{width:"100%",height:"100%",children:jsxs(AreaChart,{data:ae.volumeData,children:[jsxs("defs",{children:[jsxs("linearGradient",{id:"colorDeposits",x1:"0",y1:"0",x2:"0",y2:"1",children:[jsx("stop",{offset:"5%",stopColor:W.deposit,stopOpacity:.3}),jsx("stop",{offset:"95%",stopColor:W.deposit,stopOpacity:0})]}),jsxs("linearGradient",{id:"colorPayouts",x1:"0",y1:"0",x2:"0",y2:"1",children:[jsx("stop",{offset:"5%",stopColor:W.payout,stopOpacity:.3}),jsx("stop",{offset:"95%",stopColor:W.payout,stopOpacity:0})]})]}),jsx(CartesianGrid,{strokeDasharray:"3 3",className:"stroke-muted"}),jsx(XAxis,{dataKey:"date",className:"text-xs"}),jsx(YAxis,{className:"text-xs"}),jsx(Tooltip,{contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"8px"}}),jsx(Legend,{}),jsx(Area,{type:"monotone",dataKey:"deposits",name:m.deposits,stroke:W.deposit,fillOpacity:1,fill:"url(#colorDeposits)"}),jsx(Area,{type:"monotone",dataKey:"payouts",name:m.payouts,stroke:W.payout,fillOpacity:1,fill:"url(#colorPayouts)"})]})})})})]}),jsxs(F,{children:[jsx(G,{children:jsx(Ve,{children:m.transactionsByType})}),jsx(j,{children:jsx("div",{className:"h-[300px]",children:jsx(ResponsiveContainer,{width:"100%",height:"100%",children:jsxs(BarChart,{data:ae.typeData,children:[jsx(CartesianGrid,{strokeDasharray:"3 3",className:"stroke-muted"}),jsx(XAxis,{dataKey:"name",className:"text-xs"}),jsx(YAxis,{className:"text-xs"}),jsx(Tooltip,{contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"8px"},formatter:p=>xe(p,oe)}),jsx(Bar,{dataKey:"value",name:m.amount,radius:[4,4,0,0],children:ae.typeData.map((p,E)=>jsx(Cell,{fill:p.fill},`cell-${E}`))})]})})})})]}),jsxs(F,{children:[jsx(G,{children:jsx(Ve,{children:m.statusDistribution})}),jsx(j,{children:jsx("div",{className:"h-[300px]",children:jsx(ResponsiveContainer,{width:"100%",height:"100%",children:jsxs(PieChart,{children:[jsx(Pie,{data:ae.statusData,cx:"50%",cy:"50%",innerRadius:60,outerRadius:100,paddingAngle:2,dataKey:"value",label:({name:p,percent:E})=>`${p} ${(E*100).toFixed(0)}%`,labelLine:false,children:ae.statusData.map((p,E)=>jsx(Cell,{fill:p.fill},`cell-${E}`))}),jsx(Tooltip,{contentStyle:{backgroundColor:"hsl(var(--popover))",border:"1px solid hsl(var(--border))",borderRadius:"8px"}}),jsx(Legend,{})]})})})})]})]})})]})}var na=()=>{let n=["deposit","payout","refund"],e=["COMPLETED","COMPLETED","COMPLETED","PENDING","FAILED","PROCESSING"],t=["MTN_MOMO_CMR","ORANGE_CMR","MTN_MOMO_COG","AIRTEL_COG"],r=[],i=Date.now();for(let u=0;u<25;u++){let b=n[Math.floor(Math.random()*n.length)],h=e[Math.floor(Math.random()*e.length)],f=t[Math.floor(Math.random()*t.length)],D=Math.floor(Math.random()*5e4)+1e3,l=Math.floor(Math.random()*30);r.push({id:`tx-${String(u+1).padStart(3,"0")}-${Math.random().toString(36).slice(2,8)}`,type:b,amount:D,currency:"XAF",status:h,provider:f,phoneNumber:`237${6+Math.floor(Math.random()*3)}${Math.floor(Math.random()*1e8).toString().padStart(8,"0")}`,createdAt:new Date(i-l*24*60*60*1e3-Math.random()*24*60*60*1e3).toISOString(),...h==="FAILED"&&{failureReason:"INSUFFICIENT_FUNDS"}});}return r.sort((u,b)=>new Date(b.createdAt).getTime()-new Date(u.createdAt).getTime())},Wo=n=>({depositId:n,status:"ACCEPTED",created:new Date().toISOString(),nextStep:"FINAL_STATUS"}),$o=n=>({payoutId:n,status:"ACCEPTED",created:new Date().toISOString()}),Go=n=>({depositId:n,status:["COMPLETED","ACCEPTED","PROCESSING","ENQUEUED"][Math.floor(Math.random()*4)],created:new Date(Date.now()-6e4).toISOString(),amount:"5000",currency:"XAF",country:"CMR",payer:{type:"MMO",accountDetails:{phoneNumber:"237670000000",provider:"MTN_MOMO_CMR"}}}),jo=()=>[{country:"CMR",providers:[{provider:"MTN_MOMO_CMR",operationTypes:[{operationType:"DEPOSIT",status:"OPERATIONAL"},{operationType:"PAYOUT",status:"OPERATIONAL"}]},{provider:"ORANGE_CMR",operationTypes:[{operationType:"DEPOSIT",status:"OPERATIONAL"},{operationType:"PAYOUT",status:"DELAYED"}]}]}],Ho=n=>({country:"CMR",provider:n.startsWith("23767")?"MTN_MOMO_CMR":"ORANGE_CMR",phoneNumber:n.replace(/\D/g,"")}),Vo=()=>({companyName:"Demo Company",signatureConfiguration:{signedRequestsOnly:false,signedCallbacks:true},countries:[{country:"CMR",displayName:{en:"Cameroon",fr:"Cameroun"},prefix:"237",flag:"https://cdn.pawapay.io/flags/cmr.svg",providers:[{provider:"MTN_MOMO_CMR",displayName:"MTN Mobile Money",nameDisplayedToCustomer:"MTN MoMo",currencies:[{currency:"XAF",displayName:"CFA Franc",operationTypes:{DEPOSIT:{minAmount:"100",maxAmount:"1000000",status:"OPERATIONAL"},PAYOUT:{minAmount:"100",maxAmount:"500000",status:"OPERATIONAL"}}}]}]}]}),Bo=()=>({balances:[{country:"CMR",currency:"XAF",balance:"1250000.00"},{country:"COG",currency:"XAF",balance:"450000.00"},{country:"GAB",currency:"XAF",balance:"780000.00"}]}),qo=()=>[{id:"key-001",key:"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA..."}],ue=(n=800)=>new Promise(e=>setTimeout(e,n+Math.random()*400));async function ia(n,e){let t=new TextEncoder,r=await crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:"SHA-256"},false,["sign"]),i=await crypto.subtle.sign("HMAC",r,t.encode(n));return Array.from(new Uint8Array(i)).map(u=>u.toString(16).padStart(2,"0")).join("")}var qe=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{let e=Math.random()*16|0;return (n==="x"?e:e&3|8).toString(16)}),pt=[{value:"MTN_MOMO_CMR",label:"MTN Mobile Money",country:"Cameroun"},{value:"ORANGE_CMR",label:"Orange Money",country:"Cameroun"},{value:"MTN_MOMO_COG",label:"MTN Mobile Money",country:"Congo"},{value:"AIRTEL_COG",label:"Airtel Money",country:"Congo"},{value:"MTN_MOMO_GAB",label:"MTN Mobile Money",country:"Gabon"},{value:"AIRTEL_GAB",label:"Airtel Money",country:"Gabon"}],da=[{value:"XAF",label:"XAF (CFA Franc BEAC)"},{value:"XOF",label:"XOF (CFA Franc BCEAO)"},{value:"GHS",label:"GHS (Ghana Cedi)"},{value:"KES",label:"KES (Kenyan Shilling)"},{value:"RWF",label:"RWF (Rwandan Franc)"},{value:"TZS",label:"TZS (Tanzanian Shilling)"},{value:"UGX",label:"UGX (Ugandan Shilling)"},{value:"ZMW",label:"ZMW (Zambian Kwacha)"}],M={demo:{label:"DEMO",description:"Donn\xE9es fictives - Visualisez le dashboard",color:"text-purple-800 dark:text-purple-200",bgColor:"bg-purple-100 dark:bg-purple-900"},"demo-expert":{label:"EXPERT",description:"Console de test API - R\xE9ponses simul\xE9es",color:"text-amber-800 dark:text-amber-200",bgColor:"bg-amber-100 dark:bg-amber-900"},sandbox:{label:"SANDBOX",description:"Environnement de test Pawapay",color:"text-blue-800 dark:text-blue-200",bgColor:"bg-blue-100 dark:bg-blue-900"},production:{label:"PRODUCTION",description:"Environnement de production - Transactions r\xE9elles",color:"text-green-800 dark:text-green-200",bgColor:"bg-green-100 dark:bg-green-900"}};function Ko({apiKey:n="",environment:e="sandbox",className:t="",demoMode:r=false,apiBasePath:i="/api/pawapay",onDepositComplete:u,onPayoutComplete:b,onError:h}){let[f,D]=useState(n),[l,k]=useState(r?"demo":n?e:null),[m,ie]=useState([]),[ke,ee]=useState(false),[U,V]=useState("deposit"),[H,ye]=useState("237670000000"),[te,De]=useState("5000"),[de,Ae]=useState("XAF"),[le,P]=useState("MTN_MOMO_CMR"),[ae,Ne]=useState("Test Payment"),[B,oe]=useState(""),[Ce,q]=useState([]),[L,R]=useState("idle"),[p,E]=useState("whsec_test_secret_key"),[K,ce]=useState([]),[I,Y]=useState("deposit.completed"),[re,Ee]=useState("5000"),[Me,Ke]=useState("237670000000"),[Oe,Xe]=useState("MTN_MOMO_CMR"),[Te,ze]=useState(""),[x,_]=useState(""),[mt,la]=useState(""),[Je,ca]=useState(""),[gt,ua]=useState(""),[Ie,ft]=useState(null),[yt,pa]=useState(""),[be,bt]=useState(null),[ht,vt]=useState(""),[we,ma]=useState("all");useEffect(()=>{l==="demo"&&(ee(true),setTimeout(()=>{ie(na()),ee(false);},800));},[l]);let N=useCallback((o,g,C,se)=>{let Ze={id:qe(),operation:o,status:g,response:C,error:se,timestamp:new Date().toLocaleTimeString()};q(Ca=>[Ze,...Ca].slice(0,20));},[]),Le=useCallback(o=>{(o==="sandbox"||o==="production")&&!f.trim()||(k(o),o==="demo"?N("Configuration","success",{mode:"demo",message:"Mode d\xE9mo activ\xE9 - donn\xE9es fictives"}):o==="demo-expert"?N("Configuration","success",{mode:"demo-expert",message:"Mode expert activ\xE9 - r\xE9ponses simul\xE9es"}):N("Configuration","success",{mode:o,apiBasePath:i}));},[f,i,N]),ga=useCallback(async()=>{if(!(l!=="demo-expert"&&l!=="sandbox"&&l!=="production")){R("loading");try{let o=qe();oe(o);let g;if(l==="demo-expert")await ue(),g=Wo(o);else {let C=await fetch(`${i}/deposit`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:f,environment:l,amount:parseFloat(te),currency:de,provider:le,phoneNumber:H,customerMessage:ae.slice(0,22),transactionId:o})}),se=await C.json();if(!C.ok)throw new Error(se.error||"Deposit failed");g=se;}R("success"),N("Deposit","success",g),u?.(g);}catch(o){R("error");let g=o instanceof Error?o.message:"Deposit failed";N("Deposit","error",void 0,g),h?.(o instanceof Error?o:new Error(g));}}},[f,i,l,te,de,le,H,ae,N,u,h]),fa=useCallback(async()=>{if(!(l!=="demo-expert"&&l!=="sandbox"&&l!=="production")){R("loading");try{let o=qe();oe(o);let g;if(l==="demo-expert")await ue(),g=$o(o);else {let C=await fetch(`${i}/payout`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:f,environment:l,amount:parseFloat(te),currency:de,provider:le,phoneNumber:H,transactionId:o})}),se=await C.json();if(!C.ok)throw new Error(se.error||"Payout failed");g=se;}R("success"),N("Payout","success",g),b?.(g);}catch(o){R("error");let g=o instanceof Error?o.message:"Payout failed";N("Payout","error",void 0,g),h?.(o instanceof Error?o:new Error(g));}}},[f,i,l,te,de,le,H,N,b,h]),ya=useCallback(async()=>{if(l!=="demo-expert"&&l!=="sandbox"&&l!=="production"||!B){N("Check Status","error",void 0,"No transaction ID");return}R("loading");try{let o;if(l==="demo-expert")await ue(),o=Go(B);else {let g=await fetch(`${i}/status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:f,environment:l,transactionId:B})}),C=await g.json();if(!g.ok)throw new Error(C.error||"Status check failed");o=C;}R("success"),N("Check Status","success",o);}catch(o){R("error");let g=o instanceof Error?o.message:"Status check failed";N("Check Status","error",void 0,g),h?.(o instanceof Error?o:new Error(g));}},[f,i,l,B,N,h]),ba=useCallback(async()=>{if(!(l!=="demo-expert"&&l!=="sandbox"&&l!=="production")){R("loading");try{let o;if(l==="demo-expert")await ue(),o=jo();else {let g=await fetch(`${i}/availability`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:f,environment:l})}),C=await g.json();if(!g.ok)throw new Error(C.error||"Availability check failed");o=C;}R("success"),N("Provider Availability","success",o);}catch(o){R("error");let g=o instanceof Error?o.message:"Availability check failed";N("Provider Availability","error",void 0,g),h?.(o instanceof Error?o:new Error(g));}}},[f,i,l,N,h]),ha=useCallback(async()=>{if(!(l!=="demo-expert"&&l!=="sandbox"&&l!=="production")){R("loading");try{let o;if(l==="demo-expert")await ue(),o=Ho(H);else {let g=await fetch(`${i}/predict-provider`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:f,environment:l,phoneNumber:H})}),C=await g.json();if(!g.ok)throw new Error(C.error||"Prediction failed");o=C;}R("success"),N("Predict Provider","success",o);}catch(o){R("error");let g=o instanceof Error?o.message:"Prediction failed";N("Predict Provider","error",void 0,g),h?.(o instanceof Error?o:new Error(g));}}},[f,i,l,H,N,h]),va=useCallback(async()=>{if(!(l!=="demo-expert"&&l!=="sandbox"&&l!=="production")){R("loading");try{let o;if(l==="demo-expert")await ue(),o=Vo();else {let g=await fetch(`${i}/active-config`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:f,environment:l})}),C=await g.json();if(!g.ok)throw new Error(C.error||"Failed to get config");o=C;}R("success"),N("Active Configuration","success",o);}catch(o){R("error");let g=o instanceof Error?o.message:"Failed to get config";N("Active Configuration","error",void 0,g),h?.(o instanceof Error?o:new Error(g));}}},[f,i,l,N,h]),xa=useCallback(async()=>{if(!(l!=="demo-expert"&&l!=="sandbox"&&l!=="production")){R("loading");try{let o;if(l==="demo-expert")await ue(),o=qo();else {let g=await fetch(`${i}/public-keys`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:f,environment:l})}),C=await g.json();if(!g.ok)throw new Error(C.error||"Failed to get public keys");o=C;}R("success"),N("Public Keys","success",o);}catch(o){R("error");let g=o instanceof Error?o.message:"Failed to get public keys";N("Public Keys","error",void 0,g),h?.(o instanceof Error?o:new Error(g));}}},[f,i,l,N,h]),Na=useCallback(async()=>{if(!(l!=="demo-expert"&&l!=="sandbox"&&l!=="production")){R("loading");try{let o;if(l==="demo-expert")await ue(),o=Bo();else {let g=await fetch(`${i}/wallet-balances`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({apiKey:f,environment:l})}),C=await g.json();if(!g.ok)throw new Error(C.error||"Failed to get balances");o=C;}R("success"),N("Wallet Balances","success",o);}catch(o){R("error");let g=o instanceof Error?o.message:"Failed to get balances";N("Wallet Balances","error",void 0,g),h?.(o instanceof Error?o:new Error(g));}}},[f,i,l,N,h]),Ye=useCallback(o=>{navigator.clipboard.writeText(o);},[]);return l?l==="demo"?jsxs("div",{className:`space-y-6 ${t}`,children:[jsxs("div",{className:"flex items-center justify-between flex-wrap gap-4",children:[jsxs("div",{className:"flex items-center gap-3",children:[jsx("span",{className:`px-2 py-0.5 text-xs font-medium rounded ${M[l].bgColor} ${M[l].color}`,children:M[l].label}),jsx("span",{className:"text-sm text-muted-foreground",children:M[l].description})]}),jsxs("button",{onClick:()=>k(null),className:"h-8 px-3 text-xs font-medium border border-border bg-background hover:bg-muted transition-colors flex items-center gap-2 rounded-md",children:[jsx(Settings,{className:"w-4 h-4"}),"Changer de mode"]})]}),jsx(ct,{transactions:m,locale:"fr",isLoading:ke,onRefresh:()=>{ee(true),setTimeout(()=>{ie(na()),ee(false);},800);},showExpertMode:true,onExpertModeClick:()=>k("demo-expert")})]}):l==="sandbox"||l==="production"?jsxs("div",{className:`space-y-6 ${t}`,children:[jsxs("div",{className:"flex items-center justify-between flex-wrap gap-4",children:[jsxs("div",{className:"flex items-center gap-3",children:[jsx("span",{className:`px-2 py-0.5 text-xs font-medium rounded ${M[l].bgColor} ${M[l].color}`,children:M[l].label}),jsx("span",{className:"text-sm text-muted-foreground",children:M[l].description})]}),jsxs("button",{onClick:()=>k(null),className:"h-8 px-3 text-xs font-medium border border-border bg-background hover:bg-muted transition-colors flex items-center gap-2 rounded-md",children:[jsx(Settings,{className:"w-4 h-4"}),"Changer de mode"]})]}),jsx(ct,{transactions:m,locale:"fr",isLoading:ke,onRefresh:()=>{N("Refresh","success",{message:"Transactions refreshed"});},showExpertMode:true,onExpertModeClick:()=>k("demo-expert")})]}):jsxs("div",{className:`space-y-6 ${t}`,children:[jsxs("div",{className:"flex items-center justify-between flex-wrap gap-4",children:[jsxs("div",{children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Spaark Pay Console"}),jsx("span",{className:`px-2 py-0.5 text-xs font-medium rounded ${M[l].bgColor} ${M[l].color}`,children:M[l].label})]}),jsx("p",{className:"text-muted-foreground mt-1",children:M[l].description})]}),jsxs("button",{onClick:()=>k(null),className:"h-8 px-3 text-xs font-medium border border-border bg-background hover:bg-muted transition-colors flex items-center gap-2 rounded-md",children:[jsx(Settings,{className:"w-4 h-4"}),"Changer de mode"]})]}),jsxs("div",{className:"grid lg:grid-cols-3 gap-6",children:[jsxs("div",{className:"lg:col-span-2 space-y-6",children:[jsxs("div",{className:"flex flex-wrap gap-1 bg-muted p-1 rounded-md",children:[jsxs("button",{onClick:()=>V("deposit"),className:`flex-1 min-w-[80px] h-8 px-3 text-xs font-medium transition-colors flex items-center justify-center gap-1.5 rounded-sm ${U==="deposit"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[jsx(Wallet,{className:"w-4 h-4"}),"Deposit"]}),jsxs("button",{onClick:()=>V("payout"),className:`flex-1 min-w-[80px] h-8 px-3 text-xs font-medium transition-colors flex items-center justify-center gap-1.5 rounded-sm ${U==="payout"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[jsx(Smartphone,{className:"w-4 h-4"}),"Payout"]}),jsxs("button",{onClick:()=>V("status"),className:`flex-1 min-w-[80px] h-8 px-3 text-xs font-medium transition-colors flex items-center justify-center gap-1.5 rounded-sm ${U==="status"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[jsx(RefreshCw,{className:"w-4 h-4"}),"Status"]}),jsxs("button",{onClick:()=>V("toolkit"),className:`flex-1 min-w-[80px] h-8 px-3 text-xs font-medium transition-colors flex items-center justify-center gap-1.5 rounded-sm ${U==="toolkit"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[jsx(Wrench,{className:"w-4 h-4"}),"Toolkit"]}),jsxs("button",{onClick:()=>V("finances"),className:`flex-1 min-w-[80px] h-8 px-3 text-xs font-medium transition-colors flex items-center justify-center gap-1.5 rounded-sm ${U==="finances"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[jsx(BarChart3,{className:"w-4 h-4"}),"Finances"]}),jsxs("button",{onClick:()=>V("webhooks"),className:`flex-1 min-w-[80px] h-8 px-3 text-xs font-medium transition-colors flex items-center justify-center gap-1.5 rounded-sm ${U==="webhooks"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[jsx(Zap,{className:"w-4 h-4"}),"Webhooks"]})]}),U==="deposit"&&jsxs("div",{className:"border border-border bg-background p-6 space-y-4 rounded-lg",children:[jsxs("div",{children:[jsx("h3",{className:"font-semibold",children:"Initiate Deposit"}),jsx("p",{className:"text-xs text-muted-foreground",children:"Collect payment from a Mobile Money user"})]}),jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Phone Number"}),jsx("input",{placeholder:"237670000000",value:H,onChange:o=>ye(o.target.value),className:"w-full h-8 px-2.5 text-xs border border-input bg-transparent rounded-md outline-none focus:border-ring"})]}),jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Amount"}),jsx("input",{type:"number",placeholder:"5000",value:te,onChange:o=>De(o.target.value),className:"w-full h-8 px-2.5 text-xs border border-input bg-transparent rounded-md outline-none focus:border-ring"})]}),jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Currency"}),jsx("select",{value:de,onChange:o=>Ae(o.target.value),className:"w-full h-8 px-2.5 text-xs border border-input bg-transparent rounded-md outline-none focus:border-ring",children:da.map(o=>jsx("option",{value:o.value,children:o.label},o.value))})]}),jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Provider"}),jsx("select",{value:le,onChange:o=>P(o.target.value),className:"w-full h-8 px-2.5 text-xs border border-input bg-transparent rounded-md outline-none focus:border-ring",children:pt.map(o=>jsxs("option",{value:o.value,children:[o.label," (",o.country,")"]},o.value))})]}),jsxs("div",{className:"space-y-2 sm:col-span-2",children:[jsx("label",{className:"text-xs font-medium",children:"Customer Message (4-22 chars)"}),jsx("input",{placeholder:"Payment description",value:ae,onChange:o=>Ne(o.target.value),maxLength:22,className:"w-full h-8 px-2.5 text-xs border border-input bg-transparent rounded-md outline-none focus:border-ring"})]})]}),jsxs("button",{onClick:ga,disabled:L==="loading",className:"w-full h-8 px-3 text-xs font-medium bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50 transition-colors flex items-center justify-center gap-2 rounded-md",children:[L==="loading"?jsx(Loader2,{className:"w-4 h-4 animate-spin"}):jsx(PlayCircle,{className:"w-4 h-4"}),"Execute Deposit"]})]}),U==="payout"&&jsxs("div",{className:"border border-border bg-background p-6 space-y-4 rounded-lg",children:[jsxs("div",{children:[jsx("h3",{className:"font-semibold",children:"Initiate Payout"}),jsx("p",{className:"text-xs text-muted-foreground",children:"Send money to a Mobile Money account"})]}),jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Recipient Phone"}),jsx("input",{placeholder:"237670000000",value:H,onChange:o=>ye(o.target.value),className:"w-full h-8 px-2.5 text-xs border border-input bg-transparent rounded-md outline-none focus:border-ring"})]}),jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Amount"}),jsx("input",{type:"number",placeholder:"5000",value:te,onChange:o=>De(o.target.value),className:"w-full h-8 px-2.5 text-xs border border-input bg-transparent rounded-md outline-none focus:border-ring"})]}),jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Currency"}),jsx("select",{value:de,onChange:o=>Ae(o.target.value),className:"w-full h-8 px-2.5 text-xs border border-input bg-transparent rounded-md outline-none focus:border-ring",children:da.map(o=>jsx("option",{value:o.value,children:o.label},o.value))})]}),jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Provider"}),jsx("select",{value:le,onChange:o=>P(o.target.value),className:"w-full h-8 px-2.5 text-xs border border-input bg-transparent rounded-md outline-none focus:border-ring",children:pt.map(o=>jsxs("option",{value:o.value,children:[o.label," (",o.country,")"]},o.value))})]})]}),jsxs("button",{onClick:fa,disabled:L==="loading",className:"w-full h-8 px-3 text-xs font-medium bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50 transition-colors flex items-center justify-center gap-2 rounded-md",children:[L==="loading"?jsx(Loader2,{className:"w-4 h-4 animate-spin"}):jsx(PlayCircle,{className:"w-4 h-4"}),"Execute Payout"]})]}),U==="status"&&jsxs("div",{className:"border border-border bg-background p-6 space-y-4 rounded-lg",children:[jsxs("div",{children:[jsx("h3",{className:"font-semibold",children:"Check Transaction Status"}),jsx("p",{className:"text-xs text-muted-foreground",children:"Query the status of a transaction"})]}),jsxs("div",{className:"space-y-4",children:[jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Transaction ID"}),jsxs("div",{className:"flex gap-2",children:[jsx("input",{placeholder:"Enter transaction ID (UUID)",value:B,onChange:o=>oe(o.target.value),className:"flex-1 h-8 px-2.5 text-xs border border-input bg-transparent rounded-md outline-none focus:border-ring font-mono"}),B&&jsx("button",{onClick:()=>Ye(B),className:"w-8 h-8 border border-border bg-background hover:bg-muted transition-colors flex items-center justify-center rounded-md",title:"Copy to clipboard",children:jsx(Copy,{className:"w-4 h-4"})})]})]}),jsxs("button",{onClick:ya,disabled:L==="loading"||!B,className:"w-full h-8 px-3 text-xs font-medium bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50 transition-colors flex items-center justify-center gap-2 rounded-md",children:[L==="loading"?jsx(Loader2,{className:"w-4 h-4 animate-spin"}):jsx(RefreshCw,{className:"w-4 h-4"}),"Check Status"]})]})]}),U==="toolkit"&&jsxs("div",{className:"space-y-4",children:[jsxs("div",{className:"border border-border bg-background p-6 space-y-4 rounded-lg",children:[jsxs("div",{children:[jsx("h3",{className:"font-semibold",children:"Predict Provider"}),jsx("p",{className:"text-xs text-muted-foreground",children:"Predict the provider from a phone number"})]}),jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Phone Number"}),jsx("input",{placeholder:"+237 670 000 000",value:H,onChange:o=>ye(o.target.value),className:"w-full h-8 px-2.5 text-xs border border-input bg-transparent rounded-md outline-none focus:border-ring"})]}),jsxs("button",{onClick:ha,disabled:L==="loading",className:"w-full h-8 px-3 text-xs font-medium bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50 transition-colors flex items-center justify-center gap-2 rounded-md",children:[L==="loading"?jsx(Loader2,{className:"w-4 h-4 animate-spin"}):jsx(Search,{className:"w-4 h-4"}),"Predict Provider"]})]}),jsxs("div",{className:"grid sm:grid-cols-3 gap-3",children:[jsxs("button",{onClick:ba,disabled:L==="loading",className:"h-10 px-3 text-xs font-medium border border-border bg-background hover:bg-muted disabled:opacity-50 transition-colors flex items-center justify-center gap-2 rounded-md",children:[jsx(Wifi,{className:"w-4 h-4"}),"Provider Availability"]}),jsxs("button",{onClick:va,disabled:L==="loading",className:"h-10 px-3 text-xs font-medium border border-border bg-background hover:bg-muted disabled:opacity-50 transition-colors flex items-center justify-center gap-2 rounded-md",children:[jsx(Settings,{className:"w-4 h-4"}),"Active Config"]}),jsxs("button",{onClick:xa,disabled:L==="loading",className:"h-10 px-3 text-xs font-medium border border-border bg-background hover:bg-muted disabled:opacity-50 transition-colors flex items-center justify-center gap-2 rounded-md",children:[jsx(Key,{className:"w-4 h-4"}),"Public Keys"]})]})]}),U==="finances"&&jsxs("div",{className:"space-y-4",children:[jsxs("div",{className:"border border-border bg-background p-6 space-y-4 rounded-lg",children:[jsxs("div",{children:[jsx("h3",{className:"font-semibold",children:"Wallet Balances"}),jsx("p",{className:"text-xs text-muted-foreground",children:"View balances for all your wallets"})]}),jsxs("button",{onClick:Na,disabled:L==="loading",className:"w-full h-8 px-3 text-xs font-medium bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50 transition-colors flex items-center justify-center gap-2 rounded-md",children:[L==="loading"?jsx(Loader2,{className:"w-4 h-4 animate-spin"}):jsx(Wallet,{className:"w-4 h-4"}),"Get Wallet Balances"]})]}),jsxs("div",{className:"border border-border bg-background p-6 space-y-4 rounded-lg",children:[jsxs("div",{children:[jsx("h3",{className:"font-semibold",children:"Statements"}),jsx("p",{className:"text-xs text-muted-foreground",children:"Generate financial statements for your wallets"})]}),jsxs("div",{className:"p-4 bg-muted/50 text-xs text-muted-foreground rounded-md",children:["Statement generation requires callback URL configuration. Use the SDK directly:",jsx("pre",{className:"mt-2 p-2 bg-background overflow-x-auto rounded",children:`await sdk.finances.generateStatement({
2
2
  wallet: { country: 'CMR', currency: 'XAF' },
3
3
  callbackUrl: 'https://your-site.com/callback',
4
4
  startDate: '2025-01-01T00:00:00Z',
5
5
  endDate: '2025-01-31T23:59:59Z',
6
- });`})]})]})]}),E==="webhooks"&&jsxs("div",{className:"space-y-4",children:[jsxs("div",{className:"border border-border bg-background p-6 space-y-4",children:[jsxs("div",{children:[jsx("h3",{className:"font-semibold",children:"Webhook Secret"}),jsx("p",{className:"text-xs text-muted-foreground",children:"Configure the secret used for signing webhooks"})]}),jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Secret Key"}),jsx("input",{type:"text",placeholder:"whsec_...",value:we,onChange:r=>Ze(r.target.value),className:"w-full h-8 px-2.5 text-xs font-mono border border-input bg-transparent rounded-none outline-none focus:border-ring"})]})]}),jsxs("div",{className:"border border-border bg-background p-6 space-y-4",children:[jsxs("div",{children:[jsx("h3",{className:"font-semibold",children:"Webhook Simulator"}),jsx("p",{className:"text-xs text-muted-foreground",children:"Generate mock webhook events for testing"})]}),jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Event Type"}),jsx("select",{value:z,onChange:r=>Qe(r.target.value),className:"w-full h-8 px-2.5 text-xs border border-input bg-transparent rounded-none outline-none focus:border-ring",children:Ve.map(r=>jsx("option",{value:r,children:r},r))})]}),jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Amount"}),jsx("input",{type:"number",placeholder:"5000",value:ke,onChange:r=>et(r.target.value),className:"w-full h-8 px-2.5 text-xs border border-input bg-transparent rounded-none outline-none focus:border-ring"})]}),jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Phone Number"}),jsx("input",{placeholder:"237670000000",value:Pe,onChange:r=>tt(r.target.value),className:"w-full h-8 px-2.5 text-xs border border-input bg-transparent rounded-none outline-none focus:border-ring"})]}),jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Provider"}),jsx("select",{value:Te,onChange:r=>ot(r.target.value),className:"w-full h-8 px-2.5 text-xs border border-input bg-transparent rounded-none outline-none focus:border-ring",children:be.map(r=>jsxs("option",{value:r.value,children:[r.label," (",r.country,")"]},r.value))})]})]}),jsxs("button",{onClick:async()=>{let r=Ge(z,{amount:ke,phoneNumber:Pe,correspondent:Te}),c=JSON.stringify(r,null,2),b=await Be(JSON.stringify(r),we);rt(c),nt(b);let S={id:re(),eventType:z,payload:r,signature:b,receivedAt:new Date().toLocaleTimeString(),isVerified:null};Ee(ge=>[S,...ge].slice(0,50)),f("Generate Webhook","success",{eventType:z,eventId:r.eventId});},className:"w-full h-8 px-3 text-xs font-medium bg-primary text-primary-foreground hover:bg-primary/90 transition-colors flex items-center justify-center gap-2",children:[jsx(ne,{}),"Generate Event"]}),ue&&jsxs("div",{className:"space-y-2",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("label",{className:"text-xs font-medium",children:"Generated Payload"}),jsx("button",{onClick:()=>me(ue),className:"text-xs text-muted-foreground hover:text-foreground",children:"Copy"})]}),jsx("pre",{className:"text-xs bg-muted p-3 overflow-x-auto max-h-48",children:ue}),jsxs("div",{className:"flex items-center gap-2",children:[jsx("label",{className:"text-xs font-medium",children:"Signature:"}),jsx("code",{className:"text-xs bg-muted px-2 py-1 font-mono flex-1 overflow-x-auto",children:Ae}),jsx("button",{onClick:()=>me(Ae),className:"w-8 h-8 border border-border bg-background hover:bg-muted transition-colors flex items-center justify-center",children:jsx(ze,{})})]})]})]}),jsxs("div",{className:"border border-border bg-background p-6 space-y-4",children:[jsxs("div",{children:[jsx("h3",{className:"font-semibold",children:"Signature Verifier"}),jsx("p",{className:"text-xs text-muted-foreground",children:"Test webhook signature verification"})]}),jsxs("div",{className:"space-y-4",children:[jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Payload (JSON)"}),jsx("textarea",{placeholder:'{"eventId": "...", "eventType": "deposit.completed", ...}',value:Se,onChange:r=>at(r.target.value),rows:4,className:"w-full px-2.5 py-2 text-xs font-mono border border-input bg-transparent rounded-none outline-none focus:border-ring resize-none"})]}),jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Signature"}),jsx("input",{placeholder:"HMAC-SHA256 signature",value:pe,onChange:r=>st(r.target.value),className:"w-full h-8 px-2.5 text-xs font-mono border border-input bg-transparent rounded-none outline-none focus:border-ring"})]}),jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Secret"}),jsx("input",{type:"password",placeholder:"whsec_...",value:Oe,onChange:r=>it(r.target.value),className:"w-full h-8 px-2.5 text-xs font-mono border border-input bg-transparent rounded-none outline-none focus:border-ring"})]})]}),jsxs("button",{onClick:async()=>{try{let r=JSON.parse(Se),c=await Be(JSON.stringify(r),Oe),b=c===pe;Me(b),f("Verify Signature",b?"success":"error",{isValid:b,expected:c,received:pe});}catch{Me(false),f("Verify Signature","error",void 0,"Invalid JSON payload");}},className:"w-full h-8 px-3 text-xs font-medium bg-primary text-primary-foreground hover:bg-primary/90 transition-colors flex items-center justify-center gap-2",children:[jsx(ao,{}),"Verify Signature"]}),X!==null&&jsxs("div",{className:`p-3 text-xs flex items-center gap-2 ${X?"bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200":"bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200"}`,children:[X?jsx(Xe,{className:"text-green-600"}):jsx(Ye,{className:"text-red-600"}),X?"Signature is valid":"Signature is invalid"]})]})]}),jsxs("div",{className:"border border-border bg-background p-6 space-y-4",children:[jsxs("div",{children:[jsx("h3",{className:"font-semibold",children:"Event Parser"}),jsx("p",{className:"text-xs text-muted-foreground",children:"Parse and analyze raw webhook JSON"})]}),jsxs("div",{className:"space-y-4",children:[jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Raw JSON"}),jsx("textarea",{placeholder:"Paste webhook JSON here...",value:De,onChange:r=>ct(r.target.value),rows:4,className:"w-full px-2.5 py-2 text-xs font-mono border border-input bg-transparent rounded-none outline-none focus:border-ring resize-none"})]}),jsxs("button",{onClick:()=>{try{let r=JSON.parse(De);Ie(r),_e(""),f("Parse Event","success",{eventType:r.eventType,eventId:r.eventId});}catch(r){Ie(null),_e(r instanceof Error?r.message:"Invalid JSON"),f("Parse Event","error",void 0,"Invalid JSON");}},className:"w-full h-8 px-3 text-xs font-medium bg-primary text-primary-foreground hover:bg-primary/90 transition-colors flex items-center justify-center gap-2",children:[jsx(so,{}),"Parse Event"]}),Le&&jsx("div",{className:"p-3 text-xs bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200",children:Le}),j&&jsxs("div",{className:"space-y-3",children:[jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs",children:[jsxs("div",{className:"p-2 bg-muted",children:[jsx("span",{className:"text-muted-foreground",children:"Event ID:"}),jsx("p",{className:"font-mono truncate",children:String(j.eventId??"N/A")})]}),jsxs("div",{className:"p-2 bg-muted",children:[jsx("span",{className:"text-muted-foreground",children:"Event Type:"}),jsx("p",{className:"font-medium",children:String(j.eventType??"N/A")})]}),jsxs("div",{className:"p-2 bg-muted",children:[jsx("span",{className:"text-muted-foreground",children:"Timestamp:"}),jsx("p",{className:"font-mono truncate",children:String(j.timestamp??"N/A")})]}),jsxs("div",{className:"p-2 bg-muted",children:[jsx("span",{className:"text-muted-foreground",children:"Status:"}),jsx("p",{className:"font-medium",children:String(j.data?.status??"N/A")})]})]}),jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Full Data"}),jsx("pre",{className:"text-xs bg-muted p-3 overflow-x-auto max-h-48",children:JSON.stringify(j,null,2)})]})]})]})]}),jsxs("div",{className:"border border-border bg-background p-6 space-y-4",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsxs("div",{children:[jsx("h3",{className:"font-semibold",children:"Event Log"}),jsx("p",{className:"text-xs text-muted-foreground",children:"History of generated webhook events"})]}),jsxs("div",{className:"flex items-center gap-2",children:[jsxs("select",{value:V,onChange:r=>dt(r.target.value),className:"h-8 px-2 text-xs border border-input bg-transparent rounded-none outline-none focus:border-ring",children:[jsx("option",{value:"all",children:"All"}),jsx("option",{value:"deposit",children:"Deposits"}),jsx("option",{value:"payout",children:"Payouts"}),jsx("option",{value:"refund",children:"Refunds"})]}),le.length>0&&jsx("button",{onClick:()=>Ee([]),className:"text-xs text-muted-foreground hover:text-foreground",children:"Clear"})]})]}),jsx("div",{className:"divide-y divide-border max-h-64 overflow-y-auto",children:le.filter(r=>V==="all"||r.eventType.startsWith(V)).length===0?jsx("div",{className:"p-4 text-center text-muted-foreground text-xs",children:"No events yet. Generate a webhook event to see it here."}):le.filter(r=>V==="all"||r.eventType.startsWith(V)).map(r=>jsxs("div",{className:"py-3 space-y-1",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("div",{className:"flex items-center gap-2",children:jsx("span",{className:`px-1.5 py-0.5 text-xs font-medium ${r.eventType.includes("completed")?"bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200":r.eventType.includes("failed")?"bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200":"bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200"}`,children:r.eventType})}),jsx("span",{className:"text-xs text-muted-foreground",children:r.receivedAt})]}),jsxs("div",{className:"text-xs text-muted-foreground font-mono truncate",children:["sig: ",r.signature.slice(0,32),"..."]})]},r.id))})]})]})]}),jsxs("div",{className:"space-y-4",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("h3",{className:"font-semibold",children:"Results"}),de.length>0&&jsx("button",{onClick:()=>Re([]),className:"text-xs text-muted-foreground hover:text-foreground",children:"Clear"})]}),jsx("div",{className:"border border-border bg-background divide-y divide-border max-h-[600px] overflow-y-auto",children:de.length===0?jsx("div",{className:"p-6 text-center text-muted-foreground text-xs",children:"No results yet. Execute an operation to see results here."}):de.map(r=>jsxs("div",{className:"p-4 space-y-2",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsxs("div",{className:"flex items-center gap-2",children:[r.status==="success"?jsx(Xe,{className:"text-green-600"}):jsx(Ye,{className:"text-red-600"}),jsx("span",{className:"font-medium text-sm",children:r.operation})]}),jsx("span",{className:"text-xs text-muted-foreground",children:r.timestamp})]}),r.error?jsx("p",{className:"text-xs text-red-600",children:r.error}):jsx("pre",{className:"text-xs bg-muted p-2 overflow-x-auto max-h-48",children:JSON.stringify(r.response,null,2)})]},r.id))})]})]})]}):jsxs("div",{className:`space-y-8 ${t}`,children:[jsxs("div",{children:[jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Spaark Pay Console"}),jsx("p",{className:"text-muted-foreground mt-1",children:"Configurez vos identifiants PawaPay pour commencer"})]}),jsxs("div",{className:"border border-border bg-background p-6 max-w-md space-y-6",children:[jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"w-10 h-10 bg-muted flex items-center justify-center",children:jsx(he,{})}),jsxs("div",{children:[jsx("h2",{className:"font-semibold",children:"SDK Configuration"}),jsx("p",{className:"text-xs text-muted-foreground",children:"Enter your API credentials"})]})]}),jsxs("div",{className:"space-y-4",children:[jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"API Key"}),jsx("input",{type:"password",placeholder:"pk_sandbox_...",value:l,onChange:r=>C(r.target.value),className:"w-full h-8 px-2.5 text-xs border border-input bg-transparent rounded-none outline-none focus:border-ring"})]}),jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Environnement"}),jsxs("div",{className:"flex gap-2",children:[jsxs("button",{onClick:()=>R("sandbox"),className:`h-8 px-3 text-xs font-medium border transition-colors flex items-center gap-1.5 ${m==="sandbox"?"bg-blue-600 text-white border-blue-600":"bg-background border-border hover:bg-muted"}`,children:[jsx("span",{className:`w-2 h-2 rounded-full ${m==="sandbox"?"bg-blue-200":"bg-blue-500"}`}),"Sandbox"]}),jsxs("button",{onClick:()=>R("production"),className:`h-8 px-3 text-xs font-medium border transition-colors flex items-center gap-1.5 ${m==="production"?"bg-green-600 text-white border-green-600":"bg-background border-border hover:bg-muted"}`,children:[jsx("span",{className:`w-2 h-2 rounded-full ${m==="production"?"bg-green-200":"bg-green-500"}`}),"Production"]})]}),jsx("p",{className:"text-xs text-muted-foreground",children:m==="sandbox"?"Utilisez le sandbox pour tester sans frais r\xE9els":"Attention : les transactions en production sont r\xE9elles"})]}),jsxs("button",{onClick:lt,className:"w-full h-8 px-3 text-xs font-medium bg-primary text-primary-foreground hover:bg-primary/90 transition-colors flex items-center justify-center gap-2",children:[jsx(ne,{}),"Initialize SDK"]}),jsxs("div",{className:"relative flex items-center py-2",children:[jsx("div",{className:"flex-grow border-t border-border"}),jsx("span",{className:"flex-shrink mx-3 text-xs text-muted-foreground",children:"ou"}),jsx("div",{className:"flex-grow border-t border-border"})]}),jsxs("button",{onClick:ut,className:"w-full h-8 px-3 text-xs font-medium border border-border bg-background hover:bg-muted transition-colors flex items-center justify-center gap-2",children:[jsx(Zt,{}),"Mode D\xE9mo (sans API key)"]})]})]})]})}var he=()=>jsxs("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})]}),ne=()=>jsxs("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M14.752 11.168l-3.197-2.132A1 1 0 0010 9.87v4.263a1 1 0 001.555.832l3.197-2.132a1 1 0 000-1.664z"}),jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})]}),He=()=>jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"})}),Jt=()=>jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 18h.01M8 21h8a2 2 0 002-2V5a2 2 0 00-2-2H8a2 2 0 00-2 2v14a2 2 0 002 2z"})}),Ke=()=>jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"})}),H=()=>jsx("svg",{className:"w-4 h-4 animate-spin",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"})}),ze=()=>jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"})}),Xe=({className:i=""})=>jsx("svg",{className:`w-4 h-4 ${i}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"})}),Ye=({className:i=""})=>jsx("svg",{className:`w-4 h-4 ${i}`,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"})}),Zt=()=>jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19.428 15.428a2 2 0 00-1.022-.547l-2.387-.477a6 6 0 00-3.86.517l-.318.158a6 6 0 01-3.86.517L6.05 15.21a2 2 0 00-1.806.547M8 4h8l-1 1v5.172a2 2 0 00.586 1.414l5 5c1.26 1.26.367 3.414-1.415 3.414H4.828c-1.782 0-2.674-2.154-1.414-3.414l5-5A2 2 0 009 10.172V5L8 4z"})}),Qt=()=>jsxs("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})]}),eo=()=>jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z"})}),to=()=>jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"})}),oo=()=>jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8.111 16.404a5.5 5.5 0 017.778 0M12 20h.01m-7.08-7.071c3.904-3.905 10.236-3.905 14.141 0M1.394 9.393c5.857-5.857 15.355-5.857 21.213 0"})}),ro=()=>jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 7a2 2 0 012 2m4 0a6 6 0 01-7.743 5.743L11 17H9v2H7v2H4a1 1 0 01-1-1v-2.586a1 1 0 01.293-.707l5.964-5.964A6 6 0 1121 9z"})}),no=()=>jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M13 10V3L4 14h7v7l9-11h-7z"})}),ao=()=>jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"})}),so=()=>jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10 20l4-16m4 4l4 4-4 4M6 16l-4-4 4-4"})});export{$ as CORRESPONDENTS,G as CORRESPONDENT_INFO,J as DEFAULT_LIMITS,N as ERROR_CODES,q as Logger,p as PawapayError,ye as SpaarkPayApiSdk,Yt as SpaarkPaySdkTestDashboard};//# sourceMappingURL=index.mjs.map
6
+ });`})]})]})]}),U==="webhooks"&&jsxs("div",{className:"space-y-4",children:[jsxs("div",{className:"border border-border bg-background p-6 space-y-4 rounded-lg",children:[jsxs("div",{children:[jsx("h3",{className:"font-semibold",children:"Webhook Secret"}),jsx("p",{className:"text-xs text-muted-foreground",children:"Configure the secret used for signing webhooks"})]}),jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Secret Key"}),jsx("input",{type:"text",placeholder:"whsec_...",value:p,onChange:o=>E(o.target.value),className:"w-full h-8 px-2.5 text-xs font-mono border border-input bg-transparent rounded-md outline-none focus:border-ring"})]})]}),jsxs("div",{className:"border border-border bg-background p-6 space-y-4 rounded-lg",children:[jsxs("div",{children:[jsx("h3",{className:"font-semibold",children:"Webhook Simulator"}),jsx("p",{className:"text-xs text-muted-foreground",children:"Generate mock webhook events for testing"})]}),jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Event Type"}),jsx("select",{value:I,onChange:o=>Y(o.target.value),className:"w-full h-8 px-2.5 text-xs border border-input bg-transparent rounded-md outline-none focus:border-ring",children:Rt.map(o=>jsx("option",{value:o,children:o},o))})]}),jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Amount"}),jsx("input",{type:"number",placeholder:"5000",value:re,onChange:o=>Ee(o.target.value),className:"w-full h-8 px-2.5 text-xs border border-input bg-transparent rounded-md outline-none focus:border-ring"})]}),jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Phone Number"}),jsx("input",{placeholder:"237670000000",value:Me,onChange:o=>Ke(o.target.value),className:"w-full h-8 px-2.5 text-xs border border-input bg-transparent rounded-md outline-none focus:border-ring"})]}),jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Provider"}),jsx("select",{value:Oe,onChange:o=>Xe(o.target.value),className:"w-full h-8 px-2.5 text-xs border border-input bg-transparent rounded-md outline-none focus:border-ring",children:pt.map(o=>jsxs("option",{value:o.value,children:[o.label," (",o.country,")"]},o.value))})]})]}),jsxs("button",{onClick:async()=>{let o=wt(I,{amount:re,phoneNumber:Me,correspondent:Oe}),g=JSON.stringify(o,null,2),C=await ia(JSON.stringify(o),p);ze(g),_(C);let se={id:qe(),eventType:I,payload:o,signature:C,receivedAt:new Date().toLocaleTimeString(),isVerified:null};ce(Ze=>[se,...Ze].slice(0,50)),N("Generate Webhook","success",{eventType:I,eventId:o.eventId});},className:"w-full h-8 px-3 text-xs font-medium bg-primary text-primary-foreground hover:bg-primary/90 transition-colors flex items-center justify-center gap-2 rounded-md",children:[jsx(PlayCircle,{className:"w-4 h-4"}),"Generate Event"]}),Te&&jsxs("div",{className:"space-y-2",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("label",{className:"text-xs font-medium",children:"Generated Payload"}),jsx("button",{onClick:()=>Ye(Te),className:"text-xs text-muted-foreground hover:text-foreground",children:"Copy"})]}),jsx("pre",{className:"text-xs bg-muted p-3 overflow-x-auto max-h-48 rounded-md",children:Te}),jsxs("div",{className:"flex items-center gap-2",children:[jsx("label",{className:"text-xs font-medium",children:"Signature:"}),jsx("code",{className:"text-xs bg-muted px-2 py-1 font-mono flex-1 overflow-x-auto rounded",children:x}),jsx("button",{onClick:()=>Ye(x),className:"w-8 h-8 border border-border bg-background hover:bg-muted transition-colors flex items-center justify-center rounded-md",children:jsx(Copy,{className:"w-4 h-4"})})]})]})]}),jsxs("div",{className:"border border-border bg-background p-6 space-y-4 rounded-lg",children:[jsxs("div",{children:[jsx("h3",{className:"font-semibold",children:"Signature Verifier"}),jsx("p",{className:"text-xs text-muted-foreground",children:"Test webhook signature verification"})]}),jsxs("div",{className:"space-y-4",children:[jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Payload (JSON)"}),jsx("textarea",{placeholder:'{"eventId": "...", "eventType": "deposit.completed", ...}',value:mt,onChange:o=>la(o.target.value),rows:4,className:"w-full px-2.5 py-2 text-xs font-mono border border-input bg-transparent rounded-md outline-none focus:border-ring resize-none"})]}),jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Signature"}),jsx("input",{placeholder:"HMAC-SHA256 signature",value:Je,onChange:o=>ca(o.target.value),className:"w-full h-8 px-2.5 text-xs font-mono border border-input bg-transparent rounded-md outline-none focus:border-ring"})]}),jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Secret"}),jsx("input",{type:"password",placeholder:"whsec_...",value:gt,onChange:o=>ua(o.target.value),className:"w-full h-8 px-2.5 text-xs font-mono border border-input bg-transparent rounded-md outline-none focus:border-ring"})]})]}),jsxs("button",{onClick:async()=>{try{let o=JSON.parse(mt),g=await ia(JSON.stringify(o),gt),C=g===Je;ft(C),N("Verify Signature",C?"success":"error",{isValid:C,expected:g,received:Je});}catch{ft(false),N("Verify Signature","error",void 0,"Invalid JSON payload");}},className:"w-full h-8 px-3 text-xs font-medium bg-primary text-primary-foreground hover:bg-primary/90 transition-colors flex items-center justify-center gap-2 rounded-md",children:[jsx(Shield,{className:"w-4 h-4"}),"Verify Signature"]}),Ie!==null&&jsxs("div",{className:`p-3 text-xs flex items-center gap-2 rounded-md ${Ie?"bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200":"bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200"}`,children:[Ie?jsx(CheckCircle2,{className:"w-4 h-4 text-green-600"}):jsx(XCircle,{className:"w-4 h-4 text-red-600"}),Ie?"Signature is valid":"Signature is invalid"]})]})]}),jsxs("div",{className:"border border-border bg-background p-6 space-y-4 rounded-lg",children:[jsxs("div",{children:[jsx("h3",{className:"font-semibold",children:"Event Parser"}),jsx("p",{className:"text-xs text-muted-foreground",children:"Parse and analyze raw webhook JSON"})]}),jsxs("div",{className:"space-y-4",children:[jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Raw JSON"}),jsx("textarea",{placeholder:"Paste webhook JSON here...",value:yt,onChange:o=>pa(o.target.value),rows:4,className:"w-full px-2.5 py-2 text-xs font-mono border border-input bg-transparent rounded-md outline-none focus:border-ring resize-none"})]}),jsxs("button",{onClick:()=>{try{let o=JSON.parse(yt);bt(o),vt(""),N("Parse Event","success",{eventType:o.eventType,eventId:o.eventId});}catch(o){bt(null),vt(o instanceof Error?o.message:"Invalid JSON"),N("Parse Event","error",void 0,"Invalid JSON");}},className:"w-full h-8 px-3 text-xs font-medium bg-primary text-primary-foreground hover:bg-primary/90 transition-colors flex items-center justify-center gap-2 rounded-md",children:[jsx(Code,{className:"w-4 h-4"}),"Parse Event"]}),ht&&jsx("div",{className:"p-3 text-xs bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200 rounded-md",children:ht}),be&&jsxs("div",{className:"space-y-3",children:[jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs",children:[jsxs("div",{className:"p-2 bg-muted rounded",children:[jsx("span",{className:"text-muted-foreground",children:"Event ID:"}),jsx("p",{className:"font-mono truncate",children:String(be.eventId??"N/A")})]}),jsxs("div",{className:"p-2 bg-muted rounded",children:[jsx("span",{className:"text-muted-foreground",children:"Event Type:"}),jsx("p",{className:"font-medium",children:String(be.eventType??"N/A")})]}),jsxs("div",{className:"p-2 bg-muted rounded",children:[jsx("span",{className:"text-muted-foreground",children:"Timestamp:"}),jsx("p",{className:"font-mono truncate",children:String(be.timestamp??"N/A")})]}),jsxs("div",{className:"p-2 bg-muted rounded",children:[jsx("span",{className:"text-muted-foreground",children:"Status:"}),jsx("p",{className:"font-medium",children:String(be.data?.status??"N/A")})]})]}),jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"Full Data"}),jsx("pre",{className:"text-xs bg-muted p-3 overflow-x-auto max-h-48 rounded-md",children:JSON.stringify(be,null,2)})]})]})]})]}),jsxs("div",{className:"border border-border bg-background p-6 space-y-4 rounded-lg",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsxs("div",{children:[jsx("h3",{className:"font-semibold",children:"Event Log"}),jsx("p",{className:"text-xs text-muted-foreground",children:"History of generated webhook events"})]}),jsxs("div",{className:"flex items-center gap-2",children:[jsxs("select",{value:we,onChange:o=>ma(o.target.value),className:"h-8 px-2 text-xs border border-input bg-transparent rounded-md outline-none focus:border-ring",children:[jsx("option",{value:"all",children:"All"}),jsx("option",{value:"deposit",children:"Deposits"}),jsx("option",{value:"payout",children:"Payouts"}),jsx("option",{value:"refund",children:"Refunds"})]}),K.length>0&&jsx("button",{onClick:()=>ce([]),className:"text-xs text-muted-foreground hover:text-foreground",children:"Clear"})]})]}),jsx("div",{className:"divide-y divide-border max-h-64 overflow-y-auto",children:K.filter(o=>we==="all"||o.eventType.startsWith(we)).length===0?jsx("div",{className:"p-4 text-center text-muted-foreground text-xs",children:"No events yet. Generate a webhook event to see it here."}):K.filter(o=>we==="all"||o.eventType.startsWith(we)).map(o=>jsxs("div",{className:"py-3 space-y-1",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("div",{className:"flex items-center gap-2",children:jsx("span",{className:`px-1.5 py-0.5 text-xs font-medium rounded ${o.eventType.includes("completed")?"bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200":o.eventType.includes("failed")?"bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200":"bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200"}`,children:o.eventType})}),jsx("span",{className:"text-xs text-muted-foreground",children:o.receivedAt})]}),jsxs("div",{className:"text-xs text-muted-foreground font-mono truncate",children:["sig: ",o.signature.slice(0,32),"..."]})]},o.id))})]})]})]}),jsxs("div",{className:"space-y-4",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("h3",{className:"font-semibold",children:"Results"}),Ce.length>0&&jsx("button",{onClick:()=>q([]),className:"text-xs text-muted-foreground hover:text-foreground",children:"Clear"})]}),jsx("div",{className:"border border-border bg-background divide-y divide-border max-h-[600px] overflow-y-auto rounded-lg",children:Ce.length===0?jsx("div",{className:"p-6 text-center text-muted-foreground text-xs",children:"No results yet. Execute an operation to see results here."}):Ce.map(o=>jsxs("div",{className:"p-4 space-y-2",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsxs("div",{className:"flex items-center gap-2",children:[o.status==="success"?jsx(CheckCircle2,{className:"w-4 h-4 text-green-600"}):jsx(XCircle,{className:"w-4 h-4 text-red-600"}),jsx("span",{className:"font-medium text-sm",children:o.operation})]}),jsx("span",{className:"text-xs text-muted-foreground",children:o.timestamp})]}),o.error?jsx("p",{className:"text-xs text-red-600",children:o.error}):jsx("pre",{className:"text-xs bg-muted p-2 overflow-x-auto max-h-48 rounded",children:JSON.stringify(o.response,null,2)})]},o.id))})]})]})]}):jsxs("div",{className:`space-y-8 ${t}`,children:[jsxs("div",{children:[jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Spaark Pay Console"}),jsx("p",{className:"text-muted-foreground mt-1",children:"Choisissez un mode pour commencer"})]}),jsxs("div",{className:"border border-border bg-background p-6 max-w-2xl space-y-4",children:[jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"w-10 h-10 bg-muted flex items-center justify-center rounded-md",children:jsx(Key,{className:"w-5 h-5"})}),jsxs("div",{children:[jsx("h2",{className:"font-semibold",children:"Configuration API"}),jsx("p",{className:"text-xs text-muted-foreground",children:"Requis pour les modes Sandbox et Production"})]})]}),jsxs("div",{className:"space-y-2",children:[jsx("label",{className:"text-xs font-medium",children:"API Key"}),jsx("input",{type:"password",placeholder:"pk_sandbox_...",value:f,onChange:o=>D(o.target.value),className:"w-full h-10 px-3 text-sm border border-input bg-transparent rounded-md outline-none focus:border-ring"})]})]}),jsxs("div",{className:"grid sm:grid-cols-2 gap-4 max-w-2xl",children:[jsxs("button",{onClick:()=>Le("demo"),className:"p-6 border border-border bg-background hover:bg-muted/50 transition-colors text-left space-y-3 rounded-lg",children:[jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"w-10 h-10 bg-purple-100 dark:bg-purple-900 flex items-center justify-center rounded-md",children:jsx(LayoutDashboard,{className:"w-5 h-5 text-purple-600 dark:text-purple-400"})}),jsx("div",{children:jsx("span",{className:`px-2 py-0.5 text-xs font-medium rounded ${M.demo.bgColor} ${M.demo.color}`,children:"DEMO"})})]}),jsxs("div",{children:[jsx("h3",{className:"font-semibold",children:"Mode D\xE9monstration"}),jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Visualisez le dashboard financier avec des donn\xE9es fictives. Id\xE9al pour d\xE9couvrir l'interface."})]})]}),jsxs("button",{onClick:()=>Le("demo-expert"),className:"p-6 border border-border bg-background hover:bg-muted/50 transition-colors text-left space-y-3 rounded-lg",children:[jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"w-10 h-10 bg-amber-100 dark:bg-amber-900 flex items-center justify-center rounded-md",children:jsx(FlaskConical,{className:"w-5 h-5 text-amber-600 dark:text-amber-400"})}),jsx("div",{children:jsx("span",{className:`px-2 py-0.5 text-xs font-medium rounded ${M["demo-expert"].bgColor} ${M["demo-expert"].color}`,children:"EXPERT"})})]}),jsxs("div",{children:[jsx("h3",{className:"font-semibold",children:"Mode Expert (Test API)"}),jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Console de test avec r\xE9ponses simul\xE9es. Testez les endpoints sans cl\xE9 API."})]})]}),jsxs("button",{onClick:()=>Le("sandbox"),disabled:!f.trim(),className:"p-6 border border-border bg-background hover:bg-muted/50 transition-colors text-left space-y-3 rounded-lg disabled:opacity-50 disabled:cursor-not-allowed",children:[jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"w-10 h-10 bg-blue-100 dark:bg-blue-900 flex items-center justify-center rounded-md",children:jsx(Beaker,{className:"w-5 h-5 text-blue-600 dark:text-blue-400"})}),jsx("div",{children:jsx("span",{className:`px-2 py-0.5 text-xs font-medium rounded ${M.sandbox.bgColor} ${M.sandbox.color}`,children:"SANDBOX"})})]}),jsxs("div",{children:[jsx("h3",{className:"font-semibold",children:"Mode Sandbox"}),jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Connect\xE9 \xE0 l'API Pawapay Sandbox. Transactions de test r\xE9elles.",!f.trim()&&jsx("span",{className:"block text-amber-600 mt-1",children:"Entrez une cl\xE9 API ci-dessus"})]})]})]}),jsxs("button",{onClick:()=>Le("production"),disabled:!f.trim(),className:"p-6 border border-border bg-background hover:bg-muted/50 transition-colors text-left space-y-3 rounded-lg disabled:opacity-50 disabled:cursor-not-allowed",children:[jsxs("div",{className:"flex items-center gap-3",children:[jsx("div",{className:"w-10 h-10 bg-green-100 dark:bg-green-900 flex items-center justify-center rounded-md",children:jsx(Globe,{className:"w-5 h-5 text-green-600 dark:text-green-400"})}),jsxs("div",{className:"flex items-center gap-2",children:[jsx("span",{className:`px-2 py-0.5 text-xs font-medium rounded ${M.production.bgColor} ${M.production.color}`,children:"PRODUCTION"}),jsx(Lock,{className:"w-3 h-3 text-muted-foreground"})]})]}),jsxs("div",{children:[jsx("h3",{className:"font-semibold",children:"Mode Production"}),jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Environnement de production. Transactions r\xE9elles avec argent r\xE9el.",!f.trim()&&jsx("span",{className:"block text-amber-600 mt-1",children:"Entrez une cl\xE9 API ci-dessus"})]})]})]})]})]})}export{he as CORRESPONDENTS,ve as CORRESPONDENT_INFO,Fe as DEFAULT_LIMITS,A as ERROR_CODES,Pe as Logger,v as PawapayError,et as SpaarkPayApiSdk,Ko as SpaarkPaySdkTestDashboard};//# sourceMappingURL=index.mjs.map
7
7
  //# sourceMappingURL=index.mjs.map