@stacknet/keyutils 0.1.12 → 0.1.18

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- 'use strict';var it=require('react'),jsxRuntime=require('react/jsx-runtime'),clsx=require('clsx'),tailwindMerge=require('tailwind-merge'),lucideReact=require('lucide-react');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var it__default=/*#__PURE__*/_interopDefault(it);var ve=it.createContext(null);function v(){let e=it.useContext(ve);if(!e)throw new Error("useKeyUtilsContext must be used within a KeyUtilsProvider");return e}function te({config:e,callbacks:t={},children:r}){typeof e.apiBaseUrl!="string"&&console.error("[KeyUtils] apiBaseUrl must be a string");let s=it.useMemo(()=>({config:e,callbacks:t}),[e,t]);return jsxRuntime.jsx(ve.Provider,{value:s,children:r})}function f(...e){return tailwindMerge.twMerge(clsx.clsx(e))}function T(e){return e==null?"0":e>=1e9?`${(e/1e9).toFixed(1)}B`:e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:e.toLocaleString()}function Ne(e,t){return t<=0?0:Math.min(100,Math.round(e/t*100))}function ke(e){return e>=70?"bg-green-500":e>=30?"bg-yellow-500":"bg-red-500"}function F(e){let t=typeof e=="string"&&/^\d+$/.test(e)?Number(e):e,r=new Date(t);return isNaN(r.getTime())?String(e):r.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}function we(){if(typeof navigator>"u")return "mac";let e=navigator.userAgent.toLowerCase();return /iphone|ipad|ipod/.test(e)?"ios":/android/.test(e)?"android":/win/.test(e)?"windows":/linux/.test(e)?"linux":"mac"}function Ce(){let{config:e}=v(),[t,r]=it.useState(null),[s,d]=it.useState(true),[u,g]=it.useState(null),a=it.useRef(true),n=it.useRef(e.apiBaseUrl);n.current=e.apiBaseUrl;let i=async()=>{try{a.current&&(d(!0),g(null));let p=await fetch(`${n.current}/api/keys/pricing`);if(!p.ok){let l=`Pricing unavailable (${p.status})`;try{let o=await p.json();o.error&&(l=o.error);}catch{}throw new Error(l)}let m=await p.json();a.current&&r(m);}catch(p){a.current&&g(p instanceof Error?p.message:"Failed to fetch pricing");}finally{a.current&&d(false);}};return it.useEffect(()=>{a.current=true,i();let p=setInterval(i,6e4);return ()=>{a.current=false,clearInterval(p);}},[]),{pricing:t,loading:s,error:u,refresh:i}}function Se(){let{config:e,callbacks:t}=v(),[r,s]=it.useState(false),[d,u]=it.useState(null),[g,a]=it.useState(null);return {mint:it.useCallback(async(i,p,m=1)=>{try{s(!0),a(null),t.onPaymentComplete?.(i,p);let l=await fetch(`${e.apiBaseUrl}/api/keys/mint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paymentMethod:i,paymentRef:p,quantity:m})});if(!l.ok){let P="Key generation failed";try{let w=await l.json();w.error&&(P=w.error);}catch{}throw new Error(P)}let o=await l.json(),c=o.keys?.[0]||o,N={success:!0,key:{id:c.keyId||c.id||"",key:c.key||"",userId:c.userId||"",status:"active",tokenBalance:c.tokenBalance??c.currentTokenBalance??0,maxTokens:c.initialTokenBalance??c.tokenBalance??0,createdAt:String(c.createdAt||Date.now())},transactionId:p};return u(N),t.onMintSuccess?.(N),N}catch(l){let o=l instanceof Error?l:new Error("Key generation failed");return a(o.message),t.onMintError?.(o),{success:false,error:o.message}}finally{s(false);}},[e.apiBaseUrl,t]),minting:r,result:d,error:g}}function Ue(){let{config:e}=v(),[t,r]=it.useState(false),[s,d]=it.useState(null),u=it.useRef(true);return {createSession:it.useCallback(async(a,n)=>{try{r(!0),d(null);let i=await fetch(`${e.apiBaseUrl}/api/keys/stripe-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({priceCents:a,quantity:n,stackId:e.stackId,referrerUrl:window.location.href})});if(!i.ok){let m=`Checkout failed (${i.status})`;try{let l=await i.json();l.error&&(m=l.error);}catch{}throw new Error(m)}let{url:p}=await i.json();if(p){try{sessionStorage.setItem("keyutils_stripe_pending","1");}catch{}window.location.href=p;}else throw new Error("No checkout URL returned")}catch(i){if(u.current){let p=i instanceof Error?i.message:"Checkout failed";d(p),r(false);}}},[e.apiBaseUrl,e.stackId]),loading:t,error:s}}var He=/^[1-9A-HJ-NP-Za-km-z]{32,44}$/;function ae({amountSol:e,onSuccess:t,onError:r,disabled:s,className:d,style:u}){let{config:g}=v(),[a,n]=it.useState(false),[i,p]=it.useState(null),m=!!(g.merchantWallet&&He.test(g.merchantWallet)),l=it.useCallback(async()=>{if(m)try{n(!0),p(null);let{Connection:o,PublicKey:c,Transaction:N,SystemProgram:P,LAMPORTS_PER_SOL:w}=await import('@solana/web3.js'),B=typeof window<"u"?window.solana:void 0;if(!B||typeof B!="object"||!B.isPhantom)throw new Error("Phantom wallet not found. Please install Phantom.");let L=B,j;try{j=new c(g.merchantWallet);}catch{throw new Error("Invalid merchant wallet address.")}let A=await L.connect(),k=new c(A.publicKey.toString()),W=new o(g.solanaRpcUrl||"https://api.mainnet-beta.solana.com"),{blockhash:$}=await W.getLatestBlockhash(),H=BigInt(Math.floor(e*1e9)),ee=new N({recentBlockhash:$,feePayer:k}).add(P.transfer({fromPubkey:k,toPubkey:j,lamports:Number(H)})),{signature:U}=await L.signAndSendTransaction(ee);t(U);}catch(o){let c=o instanceof Error?o:new Error("Payment failed");p(c.message),r?.(c);}finally{n(false);}},[e,g.merchantWallet,m,t,r]);return jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("button",{onClick:l,disabled:s||a||!m,"aria-label":`Pay ${e.toFixed(4)} SOL`,className:f("flex w-full items-center justify-center gap-2 rounded-lg bg-purple-600 px-4 py-3 font-medium text-white transition-colors hover:bg-purple-700 disabled:opacity-50 disabled:cursor-not-allowed",d),style:u,children:a?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(lucideReact.Loader2,{className:"h-4 w-4 animate-spin"}),"Processing..."]}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:["Pay ",e.toFixed(4)," SOL"]})}),i&&jsxRuntime.jsx("p",{className:"mt-2 text-center text-xs text-red-500",children:i})]})}function ie({result:e,className:t,style:r}){let[s,d]=it.useState(false),u=it.useRef(null);it.useEffect(()=>()=>{u.current&&clearTimeout(u.current);},[]);let g=it.useCallback(()=>{e.key?.key&&(navigator.clipboard.writeText(e.key.key),d(true),u.current&&clearTimeout(u.current),u.current=setTimeout(()=>d(false),2e3));},[e.key?.key]);return !e.success||!e.key?null:jsxRuntime.jsxs("div",{className:f("rounded-lg border border-green-500/20 bg-green-500/10 p-6 text-center",t),style:r,children:[jsxRuntime.jsx(lucideReact.CheckCircle,{className:"mx-auto mb-3 h-12 w-12 text-green-500"}),jsxRuntime.jsx("h3",{className:"mb-2 text-lg font-semibold text-foreground",children:"Key Generated!"}),jsxRuntime.jsx("p",{className:"mb-4 text-sm text-muted-foreground",children:"Your node key has been successfully generated."}),jsxRuntime.jsxs("div",{className:"mx-auto flex max-w-md items-center gap-2 rounded-md border bg-background p-3",children:[jsxRuntime.jsx("code",{className:"flex-1 truncate text-xs text-foreground",children:e.key.key}),jsxRuntime.jsx("button",{onClick:g,"aria-label":"Copy key to clipboard",className:"shrink-0 rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:s?jsxRuntime.jsx(lucideReact.Check,{className:"h-4 w-4 text-green-500"}):jsxRuntime.jsx(lucideReact.Copy,{className:"h-4 w-4"})})]})]})}function I({className:e}){return jsxRuntime.jsx("div",{className:f("animate-pulse rounded-xl bg-muted",e)})}function le(){return jsxRuntime.jsxs("div",{className:"space-y-6",children:[jsxRuntime.jsxs("div",{className:"px-6 py-10 flex flex-col items-center gap-3",children:[jsxRuntime.jsx(I,{className:"h-14 w-48"}),jsxRuntime.jsx(I,{className:"h-5 w-64"})]}),jsxRuntime.jsx(I,{className:"h-[72px] w-full rounded-2xl"}),jsxRuntime.jsx(I,{className:"h-[68px] w-full rounded-2xl"}),jsxRuntime.jsx(I,{className:"h-[60px] w-full rounded-2xl"})]})}function Y({count:e=3}){return jsxRuntime.jsx("div",{className:"space-y-3",children:Array.from({length:e}).map((t,r)=>jsxRuntime.jsxs("div",{className:"rounded-xl border p-4 space-y-3",children:[jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsx(I,{className:"h-4 w-32"}),jsxRuntime.jsx(I,{className:"h-4 w-16"})]}),jsxRuntime.jsx(I,{className:"h-2 w-full rounded-full"}),jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsx(I,{className:"h-3 w-24"}),jsxRuntime.jsx(I,{className:"h-3 w-20"})]})]},r))})}function gt({quantity:e,max:t,onChange:r}){return jsxRuntime.jsxs("div",{className:"flex items-center justify-between rounded-2xl border bg-muted/20 px-6 py-5",children:[jsxRuntime.jsx("span",{className:"text-sm font-medium text-foreground",children:"Quantity"}),jsxRuntime.jsxs("div",{className:"flex items-center gap-0 rounded-xl border bg-background",children:[jsxRuntime.jsx("button",{onClick:()=>r(Math.max(1,e-1)),disabled:e<=1,"aria-label":"Decrease quantity",className:"flex h-12 w-12 items-center justify-center rounded-l-xl text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-30",children:jsxRuntime.jsx(lucideReact.Minus,{className:"h-5 w-5"})}),jsxRuntime.jsx("span",{className:"flex h-12 w-14 items-center justify-center border-x text-xl font-bold text-foreground","aria-live":"polite",children:e}),jsxRuntime.jsx("button",{onClick:()=>r(Math.min(t,e+1)),disabled:e>=t,"aria-label":"Increase quantity",className:"flex h-12 w-12 items-center justify-center rounded-r-xl text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-30",children:jsxRuntime.jsx(lucideReact.Plus,{className:"h-5 w-5"})})]})]})}function Ee({pricing:e,quantity:t}){let[r,s]=it.useState(false),d=e.priceUsd*t;return jsxRuntime.jsxs("div",{className:"rounded-2xl border bg-background",children:[jsxRuntime.jsxs("button",{onClick:()=>s(!r),"aria-expanded":r,className:"flex w-full items-center justify-between px-6 py-5 text-left",children:[jsxRuntime.jsxs("span",{className:"text-foreground",children:[jsxRuntime.jsxs("span",{className:"text-xl font-bold",children:["$",d.toFixed(2)]})," ",jsxRuntime.jsx("span",{className:"text-sm text-muted-foreground",children:"total fees included"})]}),r?jsxRuntime.jsx(lucideReact.ChevronUp,{className:"h-5 w-5 text-muted-foreground"}):jsxRuntime.jsx(lucideReact.ChevronDown,{className:"h-5 w-5 text-muted-foreground"})]}),r&&jsxRuntime.jsxs("div",{className:"border-t px-6 pb-8 pt-4 space-y-3 text-sm",children:[jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsxs("span",{className:"text-muted-foreground",children:["Node Key \xD7 ",t]}),jsxRuntime.jsxs("span",{className:"text-foreground",children:["$",(e.priceUsd*t).toFixed(2)]})]}),jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsx("span",{className:"text-muted-foreground",children:"Keys sold"}),jsxRuntime.jsx("span",{className:"text-foreground",children:e.keysSold})]}),e.daysUntilHalving>0&&jsxRuntime.jsxs("div",{className:"flex justify-between text-muted-foreground",children:[jsxRuntime.jsx("span",{children:"Next refresh"}),jsxRuntime.jsxs("span",{children:[e.daysUntilHalving," day",e.daysUntilHalving!==1?"s":""]})]}),jsxRuntime.jsxs("div",{className:"flex justify-between border-t pt-3 font-semibold",children:[jsxRuntime.jsx("span",{className:"text-foreground",children:"Total"}),jsxRuntime.jsxs("span",{className:"text-foreground",children:["$",d.toFixed(2)]})]})]})]})}function ce({className:e,style:t}){let{config:r}=v(),{pricing:s,loading:d,error:u,refresh:g}=Ce(),{mint:a,minting:n,result:i,error:p}=Se(),{createSession:m,loading:l,error:o}=Ue(),[c,N]=it.useState(1),[P,w]=it.useState(r.paymentMethods?.includes("stripe")?"stripe":"solana"),[B,L]=it.useState(0),[j,A]=it.useState(false),k=it__default.default.useRef(c);k.current=c;let W=Math.max(1,r.maxQuantity||5),$=[...r.paymentMethods||["solana"]].sort((U,G)=>U==="stripe"?-1:G==="stripe"?1:0);if(it.useEffect(()=>{if(typeof window>"u")return;let G=new URLSearchParams(window.location.search).get("session_id");if(!G){try{sessionStorage.removeItem("keyutils_stripe_pending");}catch{}return}if(/^cs_(test|live)_/.test(G)&&!j&&!i?.success){let be=false;try{be=sessionStorage.getItem("keyutils_stripe_pending")==="1";}catch{}if(!be)return;try{sessionStorage.removeItem("keyutils_stripe_pending");}catch{}A(true);let he=new URL(window.location.href);he.searchParams.delete("session_id"),window.history.replaceState({},"",he.toString()),a("stripe",G,k.current);}},[j,i,a]),i?.success)return jsxRuntime.jsx("div",{className:f("flex flex-col items-center justify-center",e),style:t,children:jsxRuntime.jsx(ie,{result:i})});if(j||n)return jsxRuntime.jsx("div",{className:f("flex flex-col",e),style:t,children:jsxRuntime.jsx(le,{})});if(d)return jsxRuntime.jsx("div",{className:f("flex flex-col",e),style:t,children:jsxRuntime.jsx(le,{})});if(u||!s)return jsxRuntime.jsxs("div",{className:f("flex flex-col items-center justify-center gap-4 py-24",e),style:t,children:[jsxRuntime.jsxs("div",{className:"rounded-xl border border-red-500/20 bg-red-500/5 px-6 py-5 text-center max-w-sm",children:[jsxRuntime.jsx("p",{className:"text-sm font-medium text-foreground",children:"Unable to load pricing"}),jsxRuntime.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:u||"Please check your connection and try again."})]}),jsxRuntime.jsx("button",{onClick:()=>g(),className:"text-sm text-muted-foreground hover:text-foreground transition-colors",children:"Try again"})]});let H=async U=>{L(2),await a(P,U,c);},ee=()=>{m(s.priceCents,c);};return jsxRuntime.jsx("div",{className:f("flex flex-col",e),style:t,children:jsxRuntime.jsxs("div",{className:"space-y-6",children:[B===0&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[r.keyImage&&jsxRuntime.jsx("img",{src:r.keyImage,alt:"Node Key",className:r.keyImageClass||"w-1/2 mx-auto"}),jsxRuntime.jsxs("div",{className:"px-6 py-10 text-center",children:[jsxRuntime.jsxs("p",{className:"text-5xl font-bold tracking-tight text-foreground md:text-6xl",children:["$",s.priceUsd.toFixed(2)]}),jsxRuntime.jsxs("p",{className:"mt-2 text-base text-muted-foreground",children:["per key \xB7 ",s.tokenAllocationFormatted||T(s.tokenAllocation)," tokens included"]})]}),jsxRuntime.jsx(gt,{quantity:c,max:W,onChange:N}),jsxRuntime.jsx(Ee,{pricing:s,quantity:c}),jsxRuntime.jsx("button",{onClick:()=>L(1),className:"w-full rounded-2xl bg-foreground py-5 text-center text-base font-semibold text-background transition-colors hover:bg-foreground/90",children:"Continue to Payment"})]}),B===1&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[$.length>1&&jsxRuntime.jsx("div",{role:"tablist",className:"flex gap-1 rounded-2xl bg-muted/50 p-1.5",children:$.map(U=>jsxRuntime.jsxs("button",{role:"tab","aria-selected":P===U,onClick:()=>w(U),className:f("flex flex-1 items-center justify-center gap-2.5 rounded-xl py-4 text-sm font-medium transition-colors",P===U?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[U==="stripe"?jsxRuntime.jsx(lucideReact.CreditCard,{className:"h-5 w-5"}):jsxRuntime.jsx(lucideReact.Wallet,{className:"h-5 w-5"}),U==="stripe"?"Credit Card":"Crypto"]},U))}),jsxRuntime.jsx(Ee,{pricing:s,quantity:c}),P==="stripe"?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("button",{onClick:ee,disabled:l,className:"flex w-full items-center justify-center gap-2 rounded-2xl bg-foreground py-5 text-base font-semibold text-background transition-colors hover:bg-foreground/90 disabled:opacity-50",children:l?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(lucideReact.Loader2,{className:"h-5 w-5 animate-spin"}),"Redirecting to Stripe..."]}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(lucideReact.CreditCard,{className:"h-5 w-5"}),"Pay with Card"]})}),o&&jsxRuntime.jsx("p",{className:"text-center text-sm text-red-500",children:o})]}):P==="solana"?jsxRuntime.jsx(ae,{amountSol:s.priceSol??0,onSuccess:H,className:"rounded-2xl py-5 text-base"}):null,p&&jsxRuntime.jsx("p",{className:"text-center text-sm text-red-500",children:p}),jsxRuntime.jsx("button",{onClick:()=>L(0),className:"w-full py-3 text-center text-sm text-muted-foreground hover:text-foreground transition-colors",children:"\u2190 Back"})]})]})})}var ht={ios:"iOS",android:"Android",windows:"Windows",mac:"macOS",linux:"Linux"},vt=["mac","windows","linux","ios","android"];function de({downloads:e,className:t,style:r}){let{config:s}=v(),d=it.useMemo(()=>we(),[]),u=e||vt.map(n=>({platform:n,label:ht[n],url:"#",compatible:n===d})),g=u.find(n=>n.compatible)||u[0],a=u.filter(n=>n.platform!==g.platform);return jsxRuntime.jsxs("div",{className:f("space-y-8",t),style:r,children:[jsxRuntime.jsxs("div",{className:"flex flex-col items-center gap-6 pt-4 mt-4",children:[s.aispImage&&jsxRuntime.jsx("img",{src:s.aispImage,alt:"aiSP",className:"w-full sm:w-1/2 mx-auto px-4 sm:px-0"}),jsxRuntime.jsxs("div",{className:"text-center",children:[jsxRuntime.jsx("p",{className:"text-lg sm:text-2xl font-medium text-foreground",children:"Download the AI Service Provider App"}),jsxRuntime.jsx("p",{className:"mt-1 text-sm sm:text-base text-muted-foreground",children:"Load your keys and run your node."})]}),jsxRuntime.jsxs("a",{href:g.url,className:"inline-flex items-center gap-3 rounded-full px-10 py-4 text-lg font-semibold text-white transition-colors hover:opacity-90",style:{backgroundColor:"#0900f4"},children:[jsxRuntime.jsx(lucideReact.Download,{className:"h-5 w-5"}),"Get aiSP for ",g.label]})]}),jsxRuntime.jsxs("p",{className:"text-center text-sm text-muted-foreground",children:["aiSP is also available on"," ",a.map((n,i)=>jsxRuntime.jsxs(it__default.default.Fragment,{children:[i>0&&(i===a.length-1?" and ":", "),jsxRuntime.jsx("a",{href:n.url,className:"font-medium underline transition-colors hover:text-foreground",style:{color:"#066bff"},children:n.label})]},n.platform)),"."]}),jsxRuntime.jsxs("div",{className:"flex flex-col items-center gap-2 mt-12",children:[jsxRuntime.jsxs("p",{className:"text-center text-xs text-muted-foreground flex justify-center gap-0.5 flex-wrap",children:["Source code is available on",jsxRuntime.jsx("a",{href:"https://github.com/stack-net",target:"_blank",rel:"noopener noreferrer",className:"text-foreground underline hover:text-foreground/80 color-[#0900f4]",children:"Github"})]}),jsxRuntime.jsxs("p",{className:"text-center text-xs text-muted-foreground flex justify-center gap-0.5 flex-wrap",children:["By downloading, you agree to the",jsxRuntime.jsx("a",{href:s.termsUrl||"/terms",className:"text-foreground underline hover:text-foreground/80",children:"Open Source Applications Terms"})]})]})]})}function Pt(e){return {id:e.id||"",key:e.key||e.keyPrefix||"",userId:e.userId||e.user_id||"",status:e.status||"active",tokenBalance:e.tokenBalance??e.currentTokenBalance??e.current_token_balance??0,maxTokens:e.maxTokens??e.initialTokenBalance??e.initial_token_balance??0,createdAt:String(e.createdAt??e.created_at??""),expiresAt:e.expiresAt,label:e.label||e.keyPrefix||e.key_prefix||void 0,paperWork:e.paperWork||e.paper_work||void 0,stackId:e.stackId,stackName:e.stackName}}function J(){let{config:e}=v(),[t,r]=it.useState([]),[s,d]=it.useState(true),[u,g]=it.useState(null),a=it.useRef(true),n=e.apiBaseUrl,i=it.useCallback(async()=>{try{d(!0),g(null);let m=await fetch(`${n}/api/keys`);if(!m.ok){let c=`Failed to fetch keys (${m.status})`;try{let N=await m.json();N.error&&(c=N.error);}catch{}throw new Error(c)}let l=await m.json(),o=Array.isArray(l)?l:l.keys??[];a.current&&r(o.map(Pt));}catch(m){a.current&&g(m instanceof Error?m.message:"Failed to fetch keys");}finally{a.current&&d(false);}},[n]);it.useEffect(()=>(a.current=true,i(),()=>{a.current=false;}),[i]);let p=t.reduce((m,l)=>m+l.tokenBalance,0);return {keys:t,totalBalance:p,loading:s,error:u,refresh:i}}function Me(){let{config:e,callbacks:t}=v(),[r,s]=it.useState(false),[d,u]=it.useState(null),[g,a]=it.useState(null),n=it.useRef(true),i=it.useCallback(async(m,l)=>{try{s(!0),a(null);let o=await fetch(`${e.apiBaseUrl}/api/keys/${m}/list`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({askPriceCents:l,stackId:e.stackId,stackName:e.stackName})});if(!o.ok){let N=`Listing failed (${o.status})`;try{let P=await o.json();P.error&&(N=P.error);}catch{}throw new Error(N)}let c=await o.json();return n.current&&(u(c),t.onListingCreated?.(c)),c}catch(o){let c=o instanceof Error?o.message:"Listing failed";return n.current&&a(c),null}finally{n.current&&s(false);}},[e.apiBaseUrl,e.stackId,e.stackName,t]),p=it.useCallback(async m=>{try{s(!0),a(null);let l=await fetch(`${e.apiBaseUrl}/api/keys/${m}/list`,{method:"DELETE"});if(!l.ok){let o=`Delist failed (${l.status})`;try{let c=await l.json();c.error&&(o=c.error);}catch{}throw new Error(o)}return n.current&&u(null),!0}catch(l){let o=l instanceof Error?l.message:"Delist failed";return n.current&&a(o),false}finally{n.current&&s(false);}},[e.apiBaseUrl]);return {listKey:i,delistKey:p,listing:r,result:d,error:g}}function z({current:e,max:t,className:r,style:s,showLabel:d=true}){let u=Ne(e,t),g=ke(u);return jsxRuntime.jsxs("div",{className:f("w-full",r),style:s,children:[d&&jsxRuntime.jsxs("div",{className:"mb-1 flex items-center justify-between text-xs text-muted-foreground",children:[jsxRuntime.jsxs("span",{children:[T(e)," / ",T(t)]}),jsxRuntime.jsxs("span",{children:[u,"%"]})]}),jsxRuntime.jsx("div",{className:"h-2 w-full overflow-hidden rounded-full bg-muted",children:jsxRuntime.jsx("div",{className:f("h-full rounded-full transition-all duration-500",g),style:{width:`${u}%`}})})]})}function Rt({nodeKey:e,selected:t,onSelect:r}){return jsxRuntime.jsxs("button",{onClick:r,className:f("flex w-full items-start gap-3 rounded-xl border p-4 text-left transition-all",t?"border-foreground/30 bg-foreground/5 ring-1 ring-foreground/10":"border-border hover:border-foreground/20"),children:[jsxRuntime.jsx("div",{className:f("mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-2 transition-colors",t?"border-foreground bg-foreground":"border-muted-foreground/40"),children:t&&jsxRuntime.jsx(lucideReact.Check,{className:"h-3 w-3 text-background"})}),jsxRuntime.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsx("span",{className:"text-sm font-medium text-foreground",children:e.label||e.id.slice(0,16)}),jsxRuntime.jsx("span",{className:f("text-xs font-medium capitalize",e.status==="active"?"text-green-500":"text-muted-foreground"),children:e.status})]}),jsxRuntime.jsx(z,{current:e.tokenBalance,max:e.maxTokens,className:"mt-2"})]})]})}function pe({className:e,style:t}){let{config:r}=v(),{keys:s,loading:d,error:u,refresh:g}=J(),{listKey:a,listing:n,result:i,error:p}=Me(),[m,l]=it.useState(null),[o,c]=it.useState(""),[N,P]=it.useState(false),w=s.find(k=>k.id===m),B=parseInt(o.replace(/[^0-9]/g,""),10)||0,L=w&&B>0&&N&&!n,j=async()=>{if(!L||!w)return;let k=B*100;await a(w.id,k)&&g();};if(i)return jsxRuntime.jsxs("div",{className:f("flex flex-col items-center gap-4 rounded-xl border border-green-500/20 bg-green-500/10 py-12",e),style:t,children:[jsxRuntime.jsx(lucideReact.CheckCircle,{className:"h-12 w-12 text-green-500"}),jsxRuntime.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Key Listed!"}),jsxRuntime.jsx("p",{className:"text-sm text-muted-foreground",children:"Your key is now on the Global Open AI Network marketplace."}),jsxRuntime.jsxs("p",{className:"text-xs text-muted-foreground",children:["Listing ID: ",jsxRuntime.jsx("code",{children:i.listingId})]})]});if(d)return jsxRuntime.jsxs("div",{className:f("space-y-5 px-1",e),style:t,children:[jsxRuntime.jsx("h3",{className:"text-2xl mt-3 mb-2 font-semibold text-foreground",children:"Your Keys"}),jsxRuntime.jsx(Y,{count:2})]});if(u)return jsxRuntime.jsxs("div",{className:f("flex flex-col items-center justify-center gap-4 py-16",e),style:t,children:[jsxRuntime.jsxs("div",{className:"rounded-xl border border-red-500/20 bg-red-500/5 px-6 py-5 text-center max-w-sm",children:[jsxRuntime.jsx("p",{className:"text-sm font-medium text-foreground",children:"Unable to load your keys"}),jsxRuntime.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:u})]}),jsxRuntime.jsx("button",{onClick:()=>g(),className:"text-sm text-muted-foreground hover:text-foreground transition-colors",children:"Try again"})]});let A=s.filter(k=>k.status==="active");return A.length===0?jsxRuntime.jsxs("div",{className:f("flex flex-col items-center justify-center gap-3 rounded-xl border border-dashed py-16",e),style:t,children:[jsxRuntime.jsx(lucideReact.AlertTriangle,{className:"h-8 w-8 text-muted-foreground"}),jsxRuntime.jsx("p",{className:"text-sm text-muted-foreground",children:"No active keys to sell."})]}):jsxRuntime.jsxs("div",{className:f("space-y-5",e),style:t,children:[jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("h3",{className:"text-2xl mt-3 mb-2 font-semibold text-foreground",children:"Your Keys"}),jsxRuntime.jsx("div",{className:"space-y-2",children:A.map(k=>jsxRuntime.jsx(Rt,{nodeKey:k,selected:m===k.id,onSelect:()=>l(k.id)},k.id))})]}),w&&jsxRuntime.jsxs("div",{className:"rounded-xl border bg-muted/30 p-5 space-y-2 text-sm",children:[jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsx("span",{className:"text-muted-foreground",children:"Key ID"}),jsxRuntime.jsx("code",{className:"text-xs text-foreground",children:w.id})]}),jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsx("span",{className:"text-muted-foreground",children:"Originating Stack"}),jsxRuntime.jsx("span",{className:"text-foreground",children:r.stackName||"Unknown"})]}),jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsx("span",{className:"text-muted-foreground",children:"Tokens (remaining / total)"}),jsxRuntime.jsxs("span",{className:"text-foreground",children:[T(w.tokenBalance)," / ",T(w.maxTokens)]})]}),w.paperWork&&jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsx("span",{className:"text-muted-foreground",children:"Paper earned"}),jsxRuntime.jsx("span",{className:"text-foreground",children:w.paperWork})]}),jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsx("span",{className:"text-muted-foreground",children:"Created"}),jsxRuntime.jsx("span",{className:"text-foreground",children:F(w.createdAt)})]})]}),jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("label",{htmlFor:"listing-price",className:"mb-2 block text-sm sm:text-lg font-semibold text-foreground",children:"Listing Price (USD)"}),jsxRuntime.jsxs("div",{className:"relative",children:[jsxRuntime.jsx("span",{className:"absolute left-4 top-1/2 -translate-y-1/2 text-2xl font-bold text-muted-foreground",children:"$"}),jsxRuntime.jsx("input",{id:"listing-price",type:"text",inputMode:"numeric",value:o,onChange:k=>{let W=k.target.value.replace(/[^0-9]/g,""),$=parseInt(W,10);c(isNaN($)?"":$.toLocaleString("en-US"));},placeholder:"0",className:"w-full rounded-xl border bg-background py-5 pl-10 pr-4 text-3xl font-bold text-foreground placeholder:text-muted-foreground/30 focus:outline-none focus:ring-2 focus:ring-foreground/20"})]})]}),jsxRuntime.jsxs("label",{className:"flex items-start gap-3 cursor-pointer",children:[jsxRuntime.jsx("input",{type:"checkbox",checked:N,onChange:k=>P(k.target.checked),className:"sr-only"}),jsxRuntime.jsx("div",{"aria-hidden":"true",className:f("mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded border-2 transition-colors",N?"border-foreground bg-foreground":"border-muted-foreground/40"),children:N&&jsxRuntime.jsx(lucideReact.Check,{className:"h-3 w-3 text-background"})}),jsxRuntime.jsxs("span",{className:"text-xs text-muted-foreground leading-relaxed",children:["I agree to list this key on the Global Open AI Network marketplace. The key will be deactivated upon sale and transferred to the buyer. Listing fees may apply."," ",jsxRuntime.jsx("a",{href:r.termsUrl||"/terms",className:"text-foreground underline",children:"Terms"})]})]}),p&&jsxRuntime.jsx("p",{className:"text-sm text-red-500",children:p}),jsxRuntime.jsxs("button",{onClick:j,disabled:!L,className:f("flex w-full items-center justify-center gap-2 rounded-xl py-4 text-sm font-semibold transition-colors",L?"bg-foreground text-background hover:bg-foreground/90":"bg-muted text-muted-foreground cursor-not-allowed"),children:[jsxRuntime.jsx(lucideReact.ExternalLink,{className:"h-4 w-4"}),n?"Listing...":"List on Marketplace"]})]})}var Lt=[{id:"buy",label:"Buy"},{id:"use",label:"Use"},{id:"sell",label:"Sell"}];function Tt({active:e,onChange:t}){return jsxRuntime.jsx("div",{role:"tablist","aria-label":"Key actions",className:"flex gap-1 rounded-2xl bg-muted/50 p-1.5",children:Lt.map(({id:r,label:s})=>jsxRuntime.jsx("button",{role:"tab","aria-selected":e===r,"aria-controls":`panel-${r}`,id:`tab-${r}`,onClick:()=>t(r),className:f("flex flex-1 items-center justify-center gap-2.5 rounded-xl py-3.5 text-sm font-medium transition-all",e===r?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:jsxRuntime.jsx("span",{className:"inline",children:s})},r))})}function Et({defaultTab:e="buy",className:t,style:r}){let[s,d]=it.useState(e);return jsxRuntime.jsxs("div",{className:f("flex flex-col",t),style:r,children:[jsxRuntime.jsx("div",{className:"sticky top-0 z-10 bg-background/80 px-5 pb-3 pt-2 sm:pt-5 backdrop-blur-sm sm:px-10 md:px-16 lg:px-20",children:jsxRuntime.jsx("div",{className:"mx-auto max-w-xl",children:jsxRuntime.jsx(Tt,{active:s,onChange:d})})}),jsxRuntime.jsx("div",{className:"flex flex-1 flex-col px-5 pb-8 sm:px-10 md:px-16 md:pb-12 lg:px-20",children:jsxRuntime.jsx("div",{className:"mx-auto w-full max-w-xl flex-1",children:jsxRuntime.jsxs("div",{role:"tabpanel",id:`panel-${s}`,"aria-labelledby":`tab-${s}`,children:[s==="buy"&&jsxRuntime.jsx(ce,{className:"flex-1"}),s==="use"&&jsxRuntime.jsx(de,{className:"flex-1"}),s==="sell"&&jsxRuntime.jsx(pe,{className:"flex-1"})]})})})]})}function It({apiBaseUrl:e,stackId:t,stackName:r,paymentMethods:s,merchantWallet:d,stripePublicKey:u,theme:g,maxQuantity:a,keyImage:n,keyImageClass:i,aispImage:p,termsUrl:m,onMintSuccess:l,onMintError:o,onPaymentStart:c,onPaymentComplete:N,onListingCreated:P,defaultTab:w,className:B,style:L}){return jsxRuntime.jsx(te,{config:{apiBaseUrl:e,stackId:t,stackName:r,paymentMethods:s,merchantWallet:d,stripePublicKey:u,theme:g,maxQuantity:a,keyImage:n,keyImageClass:i,aispImage:p,termsUrl:m},callbacks:{onMintSuccess:l,onMintError:o,onPaymentStart:c,onPaymentComplete:N,onListingCreated:P},children:jsxRuntime.jsx(Et,{defaultTab:w,className:B,style:L})})}function $e(e){let{config:t}=v(),[r,s]=it.useState([]),[d,u]=it.useState(false),[g,a]=it.useState(null),n=it.useRef(true),i=t.apiBaseUrl,p=it.useCallback(async()=>{if(e)try{u(!0),a(null);let m=await fetch(`${i}/api/keys/${e}/ledger`);if(!m.ok){let o=`Failed to fetch ledger (${m.status})`;try{let c=await m.json();c.error&&(o=c.error);}catch{}throw new Error(o)}let l=await m.json();n.current&&s(Array.isArray(l)?l:l.entries??[]);}catch(m){n.current&&a(m instanceof Error?m.message:"Failed to fetch ledger");}finally{n.current&&u(false);}},[i,e]);return it.useEffect(()=>(n.current=true,p(),()=>{n.current=false;}),[p]),{entries:r,loading:d,error:g,refresh:p}}var xe=20;function ye({nodeKey:e,className:t,style:r}){let[s,d]=it.useState(false),[u,g]=it.useState(false),a=it.useRef(null),{entries:n,loading:i}=$e(s?e.id:null);it.useEffect(()=>()=>{a.current&&clearTimeout(a.current);},[]);let p=it.useCallback(()=>{e.key&&(navigator.clipboard.writeText(e.key),g(true),a.current&&clearTimeout(a.current),a.current=setTimeout(()=>g(false),2e3));},[e.key]),m=e.status==="active"?"text-green-500":e.status==="expired"?"text-red-500":"text-yellow-500",l=n.slice(0,xe);return jsxRuntime.jsxs("div",{className:f("rounded-lg border bg-background",t),style:r,children:[jsxRuntime.jsxs("div",{className:"p-4",children:[jsxRuntime.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsx("button",{onClick:()=>d(!s),"aria-expanded":s,"aria-label":s?"Collapse ledger":"Expand ledger",className:"text-muted-foreground hover:text-foreground",children:s?jsxRuntime.jsx(lucideReact.ChevronDown,{className:"h-4 w-4"}):jsxRuntime.jsx(lucideReact.ChevronRight,{className:"h-4 w-4"})}),jsxRuntime.jsx("span",{className:"text-sm font-medium text-foreground",children:e.label||`Key ${e.id.slice(0,8)}`})]}),jsxRuntime.jsx("span",{className:f("text-xs font-medium capitalize",m),children:e.status})]}),e.key&&jsxRuntime.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[jsxRuntime.jsx("code",{className:"flex-1 truncate rounded bg-muted px-2 py-1 text-xs text-muted-foreground",children:e.key}),jsxRuntime.jsx("button",{onClick:p,"aria-label":"Copy key to clipboard",className:"shrink-0 rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground",children:u?jsxRuntime.jsx(lucideReact.Check,{className:"h-3.5 w-3.5 text-green-500"}):jsxRuntime.jsx(lucideReact.Copy,{className:"h-3.5 w-3.5"})})]}),jsxRuntime.jsx(z,{current:e.tokenBalance,max:e.maxTokens}),jsxRuntime.jsxs("div",{className:"mt-2 flex items-center justify-between text-xs text-muted-foreground",children:[jsxRuntime.jsxs("span",{children:["Created ",F(e.createdAt)]}),e.expiresAt&&jsxRuntime.jsxs("span",{children:["Expires ",F(e.expiresAt)]})]})]}),s&&jsxRuntime.jsxs("div",{className:"border-t px-4 py-3",children:[jsxRuntime.jsx("h4",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Ledger"}),i?jsxRuntime.jsx("p",{className:"text-xs text-muted-foreground",children:"Loading..."}):l.length===0?jsxRuntime.jsx("p",{className:"text-xs text-muted-foreground",children:"No ledger entries."}):jsxRuntime.jsxs("div",{className:"space-y-1.5",children:[l.map(o=>jsxRuntime.jsxs("div",{className:"flex items-center justify-between text-xs",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsxs("span",{className:f("font-medium",o.type==="credit"||o.type==="reward"?"text-green-500":"text-red-500"),children:[o.type==="credit"||o.type==="reward"?"+":"-",T(Math.abs(o.amount))]}),jsxRuntime.jsx("span",{className:"text-muted-foreground",children:o.description})]}),jsxRuntime.jsx("span",{className:"text-muted-foreground",children:F(o.createdAt)})]},o.id)),n.length>xe&&jsxRuntime.jsxs("p",{className:"pt-1 text-xs text-muted-foreground",children:["Showing ",xe," of ",n.length," entries"]})]})]})]})}var qt=[{id:"buy",label:"Buy"},{id:"use",label:"Use"},{id:"sell",label:"Sell"}];function X({baseHref:e}){return jsxRuntime.jsx("div",{className:"flex gap-1 rounded-2xl bg-muted/50 p-1.5 mb-6",children:qt.map(({id:t,label:r})=>jsxRuntime.jsx("a",{href:`${e}?tab=${t}`,className:"flex flex-1 items-center justify-center gap-2.5 rounded-xl py-3.5 text-sm font-medium text-muted-foreground hover:text-foreground transition-all",children:r},t))})}function Vt({getKeyHref:e="/keys/get",showTabs:t=true,className:r,style:s}){let{keys:d,totalBalance:u,loading:g,error:a,refresh:n}=J();return g?jsxRuntime.jsxs("div",{className:f("space-y-4",r),style:s,children:[t&&e&&jsxRuntime.jsx(X,{baseHref:e}),jsxRuntime.jsx(Y,{count:3})]}):a?jsxRuntime.jsxs("div",{className:f("space-y-4",r),style:s,children:[t&&e&&jsxRuntime.jsx(X,{baseHref:e}),jsxRuntime.jsxs("div",{className:"flex flex-col items-center justify-center gap-4 py-12",children:[jsxRuntime.jsxs("div",{className:"rounded-xl border border-red-500/20 bg-red-500/5 px-6 py-5 text-center max-w-sm",children:[jsxRuntime.jsx("p",{className:"text-sm font-medium text-foreground",children:"Unable to load your keys"}),jsxRuntime.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:a})]}),jsxRuntime.jsx("button",{onClick:()=>n(),className:"text-sm text-muted-foreground hover:text-foreground transition-colors",children:"Try again"})]})]}):d.length===0?jsxRuntime.jsxs("div",{className:f("space-y-4",r),style:s,children:[t&&e&&jsxRuntime.jsx(X,{baseHref:e}),jsxRuntime.jsxs("div",{className:"flex flex-col items-center justify-center gap-4 rounded-lg border border-dashed py-12",children:[jsxRuntime.jsx(lucideReact.KeyRound,{className:"h-10 w-10 text-muted-foreground"}),jsxRuntime.jsxs("div",{className:"text-center",children:[jsxRuntime.jsx("p",{className:"text-sm font-medium text-foreground",children:"No keys yet"}),jsxRuntime.jsx("p",{className:"text-xs text-muted-foreground",children:"Get your first node key to start earning."})]}),e&&jsxRuntime.jsx("a",{href:e,className:"rounded-lg bg-foreground px-4 py-2 text-sm font-medium text-background transition-colors hover:bg-foreground/90",children:"Get a Key"})]})]}):jsxRuntime.jsxs("div",{className:f("space-y-4",r),style:s,children:[t&&e&&jsxRuntime.jsx(X,{baseHref:e}),jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsxs("p",{className:"text-sm text-muted-foreground",children:[d.length," key",d.length!==1?"s":""," \xB7 Total balance: ",T(u)]}),e&&jsxRuntime.jsx("a",{href:e,className:"rounded-md bg-foreground px-3 py-1.5 text-xs font-medium text-background transition-colors hover:bg-foreground/90",children:"Get a Key"})]}),d.map(i=>jsxRuntime.jsx(ye,{nodeKey:i},i.id))]})}
2
- exports.BuyKeyWidget=It;exports.BuyPanel=ce;exports.KeyBalanceBar=z;exports.KeyCard=ye;exports.KeyList=Vt;exports.KeyUtilsProvider=te;exports.MintSuccess=ie;exports.SellPanel=pe;exports.SolanaPayButton=ae;exports.UsePanel=de;exports.useKeyUtilsContext=v;
1
+ 'use strict';var yt=require('react'),jsxRuntime=require('react/jsx-runtime'),clsx=require('clsx'),tailwindMerge=require('tailwind-merge'),lucideReact=require('lucide-react');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var yt__default=/*#__PURE__*/_interopDefault(yt);var Ce=yt.createContext(null);function C(){let e=yt.useContext(Ce);if(!e)throw new Error("useKeyUtilsContext must be used within a KeyUtilsProvider");return e}function oe({config:e,callbacks:t={},children:r}){typeof e.apiBaseUrl!="string"&&console.error("[KeyUtils] apiBaseUrl must be a string");let s=yt.useMemo(()=>({config:e,callbacks:t}),[e,t]);return jsxRuntime.jsx(Ce.Provider,{value:s,children:r})}function u(...e){return tailwindMerge.twMerge(clsx.clsx(e))}function I(e){return e==null?"0":e>=1e9?`${(e/1e9).toFixed(1)}B`:e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:e.toLocaleString()}function Se(e,t){return t<=0?0:Math.min(100,Math.round(e/t*100))}function Ke(e){return e>=70?"bg-green-500":e>=30?"bg-yellow-500":"bg-red-500"}function z(e){let t=typeof e=="string"&&/^\d+$/.test(e)?Number(e):e,r=new Date(t);return isNaN(r.getTime())?String(e):r.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}function Re(){if(typeof navigator>"u")return "mac";let e=navigator.userAgent.toLowerCase();return /iphone|ipad|ipod/.test(e)?"ios":/android/.test(e)?"android":/win/.test(e)?"windows":/linux/.test(e)?"linux":"mac"}function Ue(){let{config:e}=C(),[t,r]=yt.useState(null),[s,g]=yt.useState(true),[m,f]=yt.useState(null),a=yt.useRef(true),n=yt.useRef(e.apiBaseUrl);n.current=e.apiBaseUrl;let c=async()=>{try{a.current&&(g(!0),f(null));let d=await fetch(`${n.current}/api/keys/pricing`);if(!d.ok){let i=`Pricing unavailable (${d.status})`;try{let o=await d.json();o.error&&(i=o.error);}catch{}throw new Error(i)}let p=await d.json();a.current&&r(p);}catch(d){a.current&&f(d instanceof Error?d.message:"Failed to fetch pricing");}finally{a.current&&g(false);}};return yt.useEffect(()=>{a.current=true,c();let d=setInterval(c,6e4);return ()=>{a.current=false,clearInterval(d);}},[]),{pricing:t,loading:s,error:m,refresh:c}}function Be(){let{config:e,callbacks:t}=C(),[r,s]=yt.useState(false),[g,m]=yt.useState(null),[f,a]=yt.useState(null);return {mint:yt.useCallback(async(c,d,p=1)=>{try{s(!0),a(null),t.onPaymentComplete?.(c,d);let i=await fetch(`${e.apiBaseUrl}/api/keys/mint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paymentMethod:c,paymentRef:d,quantity:p})});if(!i.ok){let w="Key generation failed";try{let P=await i.json();P.error&&(w=P.error);}catch{}throw new Error(w)}let o=await i.json(),l=o.keys?.[0]||o,b={success:!0,key:{id:l.keyId||l.id||"",key:l.key||"",userId:l.userId||"",status:"active",tokenBalance:l.tokenBalance??l.currentTokenBalance??0,maxTokens:l.initialTokenBalance??l.tokenBalance??0,createdAt:String(l.createdAt||Date.now())},transactionId:d};return m(b),t.onMintSuccess?.(b),b}catch(i){let o=i instanceof Error?i:new Error("Key generation failed");return a(o.message),t.onMintError?.(o),{success:false,error:o.message}}finally{s(false);}},[e.apiBaseUrl,t]),minting:r,result:g,error:f}}function Le(){let{config:e}=C(),[t,r]=yt.useState(false),[s,g]=yt.useState(null),m=yt.useRef(true);return {createSession:yt.useCallback(async(a,n)=>{try{r(!0),g(null);let c=await fetch(`${e.apiBaseUrl}/api/keys/stripe-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({priceCents:a,quantity:n,stackId:e.stackId,referrerUrl:window.location.href})});if(!c.ok){let p=`Checkout failed (${c.status})`;try{let i=await c.json();i.error&&(p=i.error);}catch{}throw new Error(p)}let{url:d}=await c.json();if(d){try{sessionStorage.setItem("keyutils_stripe_pending","1");}catch{}window.location.href=d;}else throw new Error("No checkout URL returned")}catch(c){if(m.current){let d=c instanceof Error?c.message:"Checkout failed";g(d),r(false);}}},[e.apiBaseUrl,e.stackId]),loading:t,error:s}}var je=/^[1-9A-HJ-NP-Za-km-z]{32,44}$/;function de({amountSol:e,onSuccess:t,onError:r,disabled:s,className:g,style:m}){let{config:f}=C(),[a,n]=yt.useState(false),[c,d]=yt.useState(null),p=!!(f.merchantWallet&&je.test(f.merchantWallet)),i=yt.useCallback(async()=>{if(p)try{n(!0),d(null);let{Connection:o,PublicKey:l,Transaction:b,SystemProgram:w,LAMPORTS_PER_SOL:P}=await import('@solana/web3.js'),T=typeof window<"u"?window.solana:void 0;if(!T||typeof T!="object"||!T.isPhantom)throw new Error("Phantom wallet not found. Please install Phantom.");let j=T,k;try{k=new l(f.merchantWallet);}catch{throw new Error("Invalid merchant wallet address.")}let q=await j.connect(),_=new l(q.publicKey.toString()),K=new o(f.solanaRpcUrl||"https://api.mainnet-beta.solana.com"),{blockhash:F}=await K.getLatestBlockhash(),W=BigInt(Math.floor(e*1e9)),Z=f.protocolTreasuryWallet,B=f.protocolFeeBps??500,D=new b({recentBlockhash:F,feePayer:_});if(Z&&je.test(Z)&&B>0){let X=W*BigInt(B)/10000n,Je=W-X,Ze=new l(Z);D.add(w.transfer({fromPubkey:_,toPubkey:k,lamports:Number(Je)}),w.transfer({fromPubkey:_,toPubkey:Ze,lamports:Number(X)}));}else D.add(w.transfer({fromPubkey:_,toPubkey:k,lamports:Number(W)}));let{signature:re}=await j.signAndSendTransaction(D);t(re);}catch(o){let l=o instanceof Error?o:new Error("Payment failed");d(l.message),r?.(l);}finally{n(false);}},[e,f.merchantWallet,p,t,r]);return jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("button",{onClick:i,disabled:s||a||!p,"aria-label":`Pay ${e.toFixed(4)} SOL`,className:u("flex w-full items-center justify-center gap-2 rounded-lg bg-purple-600 px-4 py-6 font-medium text-white transition-colors hover:bg-purple-700 disabled:opacity-50 disabled:cursor-not-allowed",g),style:m,children:a?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(lucideReact.Loader2,{className:"h-4 w-4 animate-spin"}),"Processing..."]}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:["Pay ",e.toFixed(4)," SOL"]})}),c&&jsxRuntime.jsx("p",{className:"mt-2 text-center text-xs text-red-500",children:c})]})}function ue({result:e,className:t,style:r}){let[s,g]=yt.useState(false),m=yt.useRef(null);yt.useEffect(()=>()=>{m.current&&clearTimeout(m.current);},[]);let f=yt.useCallback(()=>{e.key?.key&&(navigator.clipboard.writeText(e.key.key),g(true),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>g(false),2e3));},[e.key?.key]);return !e.success||!e.key?null:jsxRuntime.jsxs("div",{className:u("rounded-lg border border-green-500/20 bg-green-500/10 p-6 text-center",t),style:r,children:[jsxRuntime.jsx(lucideReact.CheckCircle,{className:"mx-auto mb-3 h-12 w-12 text-green-500"}),jsxRuntime.jsx("h3",{className:"mb-2 text-lg font-semibold text-foreground",children:"Key Generated!"}),jsxRuntime.jsx("p",{className:"mb-4 text-sm text-muted-foreground",children:"Your node key has been successfully generated."}),jsxRuntime.jsxs("div",{className:"mx-auto flex max-w-md items-center gap-2 rounded-md border bg-background p-3",children:[jsxRuntime.jsx("code",{className:"flex-1 truncate text-xs text-foreground",children:e.key.key}),jsxRuntime.jsx("button",{onClick:f,"aria-label":"Copy key to clipboard",className:"shrink-0 rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:s?jsxRuntime.jsx(lucideReact.Check,{className:"h-4 w-4 text-green-500"}):jsxRuntime.jsx(lucideReact.Copy,{className:"h-4 w-4"})})]})]})}function A({className:e}){return jsxRuntime.jsx("div",{className:u("animate-pulse rounded-xl bg-muted",e)})}function me(){return jsxRuntime.jsxs("div",{className:"space-y-6",children:[jsxRuntime.jsxs("div",{className:"px-6 py-10 flex flex-col items-center gap-3",children:[jsxRuntime.jsx(A,{className:"h-14 w-48"}),jsxRuntime.jsx(A,{className:"h-5 w-64"})]}),jsxRuntime.jsx(A,{className:"h-[72px] w-full rounded-2xl"}),jsxRuntime.jsx(A,{className:"h-[68px] w-full rounded-2xl"}),jsxRuntime.jsx(A,{className:"h-[60px] w-full rounded-2xl"})]})}function Y({count:e=3}){return jsxRuntime.jsx("div",{className:"space-y-3",children:Array.from({length:e}).map((t,r)=>jsxRuntime.jsxs("div",{className:"rounded-xl border p-4 space-y-3",children:[jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsx(A,{className:"h-4 w-32"}),jsxRuntime.jsx(A,{className:"h-4 w-16"})]}),jsxRuntime.jsx(A,{className:"h-2 w-full rounded-full"}),jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsx(A,{className:"h-3 w-24"}),jsxRuntime.jsx(A,{className:"h-3 w-20"})]})]},r))})}function Ct({quantity:e,max:t,onChange:r}){return jsxRuntime.jsxs("div",{className:"flex items-center justify-between rounded-2xl bg-muted/20 px-6 py-6",children:[jsxRuntime.jsx("span",{className:"text-sm font-medium text-foreground",children:"Quantity"}),jsxRuntime.jsxs("div",{className:"flex items-center gap-0 rounded-xl bg-background",children:[jsxRuntime.jsx("button",{onClick:()=>r(Math.max(1,e-1)),disabled:e<=1,"aria-label":"Decrease quantity",className:"flex h-12 w-12 items-center justify-center rounded-l-xl text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-30",children:jsxRuntime.jsx(lucideReact.Minus,{className:"h-5 w-5"})}),jsxRuntime.jsx("span",{className:"flex h-12 w-14 items-center justify-center border-x text-xl font-bold text-foreground","aria-live":"polite",children:e}),jsxRuntime.jsx("button",{onClick:()=>r(Math.min(t,e+1)),disabled:e>=t,"aria-label":"Increase quantity",className:"flex h-12 w-12 items-center justify-center rounded-r-xl text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-30",children:jsxRuntime.jsx(lucideReact.Plus,{className:"h-5 w-5"})})]})]})}function $e({pricing:e,quantity:t}){let[r,s]=yt.useState(false),g=e.priceUsd*t;return jsxRuntime.jsxs("div",{className:"rounded-2xl border bg-background",children:[jsxRuntime.jsxs("button",{onClick:()=>s(!r),"aria-expanded":r,className:"flex w-full items-center justify-between px-6 py-6 text-left",children:[jsxRuntime.jsxs("span",{className:"text-foreground",children:[jsxRuntime.jsxs("span",{className:"text-xl font-bold",children:["$",g.toFixed(2)]})," ",jsxRuntime.jsx("span",{className:"text-sm text-muted-foreground",children:"total fees included"})]}),r?jsxRuntime.jsx(lucideReact.ChevronUp,{className:"h-5 w-5 text-muted-foreground"}):jsxRuntime.jsx(lucideReact.ChevronDown,{className:"h-5 w-5 text-muted-foreground"})]}),r&&jsxRuntime.jsxs("div",{className:"border-t px-6 pb-8 pt-4 space-y-3 text-sm",children:[jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsxs("span",{className:"text-muted-foreground",children:["Node Key \xD7 ",t]}),jsxRuntime.jsxs("span",{className:"text-foreground",children:["$",(e.priceUsd*t).toFixed(2)]})]}),jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsx("span",{className:"text-muted-foreground",children:"Keys sold"}),jsxRuntime.jsx("span",{className:"text-foreground",children:e.keysSold})]}),e.daysUntilHalving>0&&jsxRuntime.jsxs("div",{className:"flex justify-between text-muted-foreground",children:[jsxRuntime.jsx("span",{children:"Next refresh"}),jsxRuntime.jsxs("span",{children:[e.daysUntilHalving," day",e.daysUntilHalving!==1?"s":""]})]}),jsxRuntime.jsxs("div",{className:"flex justify-between border-t pt-3 font-semibold",children:[jsxRuntime.jsx("span",{className:"text-foreground",children:"Total"}),jsxRuntime.jsxs("span",{className:"text-foreground",children:["$",g.toFixed(2)]})]})]})]})}function fe({className:e,style:t}){let{config:r}=C(),{pricing:s,loading:g,error:m,refresh:f}=Ue(),{mint:a,minting:n,result:c,error:d}=Be(),{createSession:p,loading:i,error:o}=Le(),[l,b]=yt.useState(1),[w,P]=yt.useState(r.paymentMethods?.includes("stripe")?"stripe":"solana"),[T,j]=yt.useState(0),[k,q]=yt.useState(false),_=yt__default.default.useRef(l);_.current=l;let K=Math.max(1,r.maxQuantity||5),F=[...r.paymentMethods||["solana"]].sort((B,D)=>B==="stripe"?-1:D==="stripe"?1:0);if(yt.useEffect(()=>{if(typeof window>"u")return;let D=new URLSearchParams(window.location.search).get("session_id");if(!D){try{sessionStorage.removeItem("keyutils_stripe_pending");}catch{}return}if(/^cs_(test|live)_/.test(D)&&!k&&!c?.success){let re=false;try{re=sessionStorage.getItem("keyutils_stripe_pending")==="1";}catch{}if(!re)return;try{sessionStorage.removeItem("keyutils_stripe_pending");}catch{}q(true);let X=new URL(window.location.href);X.searchParams.delete("session_id"),window.history.replaceState({},"",X.toString()),a("stripe",D,_.current);}},[k,c,a]),c?.success)return jsxRuntime.jsx("div",{className:u("flex flex-col items-center justify-center",e),style:t,children:jsxRuntime.jsx(ue,{result:c})});if(k||n)return jsxRuntime.jsx("div",{className:u("flex flex-col",e),style:t,children:jsxRuntime.jsx(me,{})});if(g)return jsxRuntime.jsx("div",{className:u("flex flex-col",e),style:t,children:jsxRuntime.jsx(me,{})});if(m||!s)return jsxRuntime.jsxs("div",{className:u("flex flex-col items-center justify-center gap-4 py-24",e),style:t,children:[jsxRuntime.jsxs("div",{className:"rounded-xl border border-red-500/20 bg-red-500/5 px-6 py-5 text-center max-w-sm",children:[jsxRuntime.jsx("p",{className:"text-sm font-medium text-foreground",children:"Unable to load pricing"}),jsxRuntime.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:m||"Please check your connection and try again."})]}),jsxRuntime.jsx("button",{onClick:()=>f(),className:"text-sm text-muted-foreground hover:text-foreground transition-colors",children:"Try again"})]});let W=async B=>{j(2),await a(w,B,l);},Z=()=>{p(s.priceCents,l);};return jsxRuntime.jsx("div",{className:u("flex flex-col",e),style:t,children:jsxRuntime.jsxs("div",{className:"space-y-6",children:[T===0&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[r.keyImage&&jsxRuntime.jsx("img",{src:r.keyImage,alt:"Node Key",className:r.keyImageClass||"w-1/2 mx-auto"}),jsxRuntime.jsxs("div",{className:"px-6 py-10 text-center",children:[jsxRuntime.jsxs("p",{className:"text-5xl font-bold tracking-tight text-foreground md:text-6xl",children:["$",s.priceUsd.toFixed(2)]}),jsxRuntime.jsxs("p",{className:"mt-2 text-base text-muted-foreground",children:["per key \xB7 ",s.tokenAllocationFormatted||I(s.tokenAllocation)," tokens included"]})]}),jsxRuntime.jsx(Ct,{quantity:l,max:K,onChange:b}),jsxRuntime.jsx($e,{pricing:s,quantity:l}),jsxRuntime.jsx("button",{onClick:()=>j(1),className:"w-full rounded-2xl bg-foreground py-6 text-center text-base font-semibold text-background transition-colors hover:bg-foreground/90",children:"Continue to Payment"})]}),T===1&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[F.length>1&&jsxRuntime.jsx("div",{role:"tablist",className:"flex gap-1 rounded-2xl bg-muted/50 p-1.5",children:F.map(B=>jsxRuntime.jsxs("button",{role:"tab","aria-selected":w===B,onClick:()=>P(B),className:u("flex flex-1 items-center justify-center gap-2.5 rounded-xl py-4 text-sm font-medium transition-colors",w===B?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[B==="stripe"?jsxRuntime.jsx(lucideReact.CreditCard,{className:"h-5 w-5"}):jsxRuntime.jsx(lucideReact.Wallet,{className:"h-5 w-5"}),B==="stripe"?"Credit Card":"Crypto"]},B))}),jsxRuntime.jsx($e,{pricing:s,quantity:l}),w==="stripe"?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("button",{onClick:Z,disabled:i,className:"flex w-full items-center justify-center gap-2 rounded-2xl bg-foreground py-6 text-base font-semibold text-background transition-colors hover:bg-foreground/90 disabled:opacity-50",children:i?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(lucideReact.Loader2,{className:"h-5 w-5 animate-spin"}),"Redirecting to Stripe..."]}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(lucideReact.CreditCard,{className:"h-5 w-5"}),"Pay with Card"]})}),o&&jsxRuntime.jsx("p",{className:"text-center text-sm text-red-500",children:o})]}):w==="solana"?jsxRuntime.jsx(de,{amountSol:s.priceSol??0,onSuccess:W,className:"rounded-2xl py-5 text-base"}):null,d&&jsxRuntime.jsx("p",{className:"text-center text-sm text-red-500",children:d}),jsxRuntime.jsx("button",{onClick:()=>j(0),className:"w-full py-3 text-center text-sm text-muted-foreground hover:text-foreground transition-colors",children:"\u2190 Back"})]})]})})}var Tt={ios:"iOS",android:"Android",windows:"Windows",mac:"macOS",linux:"Linux"},Ut=["mac","windows","linux","ios","android"];function pe({downloads:e,className:t,style:r}){let{config:s}=C(),g=yt.useMemo(()=>Re(),[]),m=e||Ut.map(n=>({platform:n,label:Tt[n],url:"#",compatible:n===g})),f=m.find(n=>n.compatible)||m[0],a=m.filter(n=>n.platform!==f.platform);return jsxRuntime.jsxs("div",{className:u("space-y-8",t),style:r,children:[jsxRuntime.jsxs("div",{className:"flex flex-col items-center gap-6 pt-4 mt-4",children:[s.aispImage&&jsxRuntime.jsx("img",{src:s.aispImage,alt:"aiSP",className:"w-full sm:w-1/2 mx-auto px-4 sm:px-0"}),jsxRuntime.jsxs("div",{className:"text-center",children:[jsxRuntime.jsx("p",{className:"text-lg sm:text-2xl font-medium text-foreground",children:"Download the AI Service Provider App"}),jsxRuntime.jsx("p",{className:"mt-1 text-sm sm:text-base text-muted-foreground",children:"Load your keys and run your node."})]}),jsxRuntime.jsxs("a",{href:f.url,className:"inline-flex items-center gap-3 rounded-full px-10 py-4 text-lg font-semibold text-white transition-colors hover:opacity-90",style:{backgroundColor:"#0900f4"},children:[jsxRuntime.jsx(lucideReact.Download,{className:"h-5 w-5"}),"Get aiSP for ",f.label]})]}),jsxRuntime.jsxs("p",{className:"text-center text-sm text-muted-foreground",children:["aiSP is also available on"," ",a.map((n,c)=>jsxRuntime.jsxs(yt__default.default.Fragment,{children:[c>0&&(c===a.length-1?" and ":", "),jsxRuntime.jsx("a",{href:n.url,className:"font-medium underline transition-colors hover:text-foreground",style:{color:"#066bff"},children:n.label})]},n.platform)),"."]}),jsxRuntime.jsxs("div",{className:"flex flex-col items-center gap-2 mt-12",children:[jsxRuntime.jsxs("p",{className:"text-center text-xs text-muted-foreground flex justify-center gap-0.5 flex-wrap",children:["Source code is available on",jsxRuntime.jsx("a",{href:"https://github.com/stack-net",target:"_blank",rel:"noopener noreferrer",className:"text-foreground underline hover:text-foreground/80 color-[#0900f4]",children:"Github"})]}),jsxRuntime.jsxs("p",{className:"text-center text-xs text-muted-foreground flex justify-center gap-0.5 flex-wrap",children:["By downloading, you agree to the",jsxRuntime.jsx("a",{href:s.termsUrl||"/terms",className:"text-foreground underline hover:text-foreground/80",children:"Open Source Applications Terms"})]})]})]})}function Et(e){return {id:e.id||"",keyIndex:e.keyIndex??e.key_index??null,key:e.key||e.keyPrefix||"",userId:e.userId||e.user_id||"",status:e.status||"active",tokenBalance:e.tokenBalance??e.currentTokenBalance??e.current_token_balance??0,maxTokens:e.maxTokens??e.initialTokenBalance??e.initial_token_balance??0,createdAt:String(e.createdAt??e.created_at??""),expiresAt:e.expiresAt,label:e.label||e.keyPrefix||e.key_prefix||void 0,paperWork:e.paperWork||e.paper_work||void 0,stackId:e.stackId,stackName:e.stackName}}function J(){let{config:e}=C(),[t,r]=yt.useState([]),[s,g]=yt.useState(true),[m,f]=yt.useState(null),a=yt.useRef(true),n=e.apiBaseUrl,c=yt.useCallback(async()=>{try{g(!0),f(null);let p=await fetch(`${n}/api/keys`);if(!p.ok){let l=`Failed to fetch keys (${p.status})`;try{let b=await p.json();b.error&&(l=b.error);}catch{}throw new Error(l)}let i=await p.json(),o=Array.isArray(i)?i:i.keys??[];a.current&&r(o.map(Et));}catch(p){a.current&&f(p instanceof Error?p.message:"Failed to fetch keys");}finally{a.current&&g(false);}},[n]);yt.useEffect(()=>(a.current=true,c(),()=>{a.current=false;}),[c]);let d=t.reduce((p,i)=>p+i.tokenBalance,0);return {keys:t,totalBalance:d,loading:s,error:m,refresh:c}}function Oe(){let{config:e,callbacks:t}=C(),[r,s]=yt.useState(false),[g,m]=yt.useState(null),[f,a]=yt.useState(null),n=yt.useRef(true),c=yt.useCallback(async(p,i)=>{try{s(!0),a(null);let o=await fetch(`${e.apiBaseUrl}/api/keys/${p}/list`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({askPriceCents:i,stackId:e.stackId,stackName:e.stackName})});if(!o.ok){let b=`Listing failed (${o.status})`;try{let w=await o.json();w.error&&(b=w.error);}catch{}throw new Error(b)}let l=await o.json();return n.current&&(m(l),t.onListingCreated?.(l)),l}catch(o){let l=o instanceof Error?o.message:"Listing failed";return n.current&&a(l),null}finally{n.current&&s(false);}},[e.apiBaseUrl,e.stackId,e.stackName,t]),d=yt.useCallback(async p=>{try{s(!0),a(null);let i=await fetch(`${e.apiBaseUrl}/api/keys/${p}/list`,{method:"DELETE"});if(!i.ok){let o=`Delist failed (${i.status})`;try{let l=await i.json();l.error&&(o=l.error);}catch{}throw new Error(o)}return n.current&&m(null),!0}catch(i){let o=i instanceof Error?i.message:"Delist failed";return n.current&&a(o),false}finally{n.current&&s(false);}},[e.apiBaseUrl]);return {listKey:c,delistKey:d,listing:r,result:g,error:f}}function V({current:e,max:t,className:r,style:s,showLabel:g=true}){let m=Se(e,t),f=Ke(m);return jsxRuntime.jsxs("div",{className:u("w-full",r),style:s,children:[g&&jsxRuntime.jsxs("div",{className:"mb-1 flex items-center justify-between text-xs text-muted-foreground",children:[jsxRuntime.jsxs("span",{children:[I(e)," / ",I(t)]}),jsxRuntime.jsxs("span",{children:[m,"%"]})]}),jsxRuntime.jsx("div",{className:"h-2 w-full overflow-hidden rounded-full bg-muted",children:jsxRuntime.jsx("div",{className:u("h-full rounded-full transition-all duration-500",f),style:{width:`${m}%`}})})]})}function At({nodeKey:e,selected:t,onSelect:r}){return jsxRuntime.jsxs("button",{onClick:r,className:u("flex w-full items-start gap-3 rounded-xl border p-4 text-left transition-all",t?"border-foreground/30 bg-foreground/5 ring-1 ring-foreground/10":"border-border hover:border-foreground/20"),children:[jsxRuntime.jsx("div",{className:u("mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-2 transition-colors",t?"border-foreground bg-foreground":"border-muted-foreground/40"),children:t&&jsxRuntime.jsx(lucideReact.Check,{className:"h-3 w-3 text-background"})}),jsxRuntime.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsxs("span",{className:"text-sm font-medium text-foreground",children:[e.keyIndex?`#${e.keyIndex} `:"",e.label||e.id.slice(0,16)]}),jsxRuntime.jsx("span",{className:u("text-xs font-medium capitalize",e.status==="active"?"text-green-500":"text-muted-foreground"),children:e.status})]}),jsxRuntime.jsx(V,{current:e.tokenBalance,max:e.maxTokens,className:"mt-2"})]})]})}function be({className:e,style:t}){let{config:r}=C(),{keys:s,loading:g,error:m,refresh:f}=J(),{listKey:a,listing:n,result:c,error:d}=Oe(),[p,i]=yt.useState(null),[o,l]=yt.useState(""),[b,w]=yt.useState(false),P=s.find(K=>K.id===p),T=parseInt(o.replace(/[^0-9]/g,""),10)||0,j=T>0&&Number.isFinite(T),k=!!P&&j&&b&&!n,q=async()=>{if(!k||!P)return;let K=T*100;await a(P.id,K)&&f();};if(c)return jsxRuntime.jsxs("div",{className:u("flex flex-col items-center gap-4 rounded-xl bg-green-500/10 py-12",e),style:t,children:[jsxRuntime.jsx(lucideReact.CheckCircle,{className:"h-12 w-12 text-green-500"}),jsxRuntime.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Key Listed!"}),jsxRuntime.jsx("p",{className:"text-sm text-muted-foreground",children:"Your key is now on the Global Open AI Network marketplace."}),jsxRuntime.jsxs("p",{className:"text-xs text-muted-foreground",children:["Listing ID: ",jsxRuntime.jsx("code",{children:c.listingId})]}),jsxRuntime.jsxs("a",{href:`https://market.stacknet.org/keys/${c.keyId}`,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 rounded-xl bg-foreground px-6 py-3 text-sm font-semibold text-background transition-colors hover:bg-foreground/90",children:[jsxRuntime.jsx(lucideReact.ExternalLink,{className:"h-4 w-4"}),"View Listing"]})]});if(g)return jsxRuntime.jsxs("div",{className:u("space-y-5 px-1",e),style:t,children:[jsxRuntime.jsx("h3",{className:"text-2xl mt-3 mb-2 font-semibold text-foreground",children:"Your Keys"}),jsxRuntime.jsx(Y,{count:2})]});if(m)return jsxRuntime.jsxs("div",{className:u("flex flex-col items-center justify-center gap-4 py-16",e),style:t,children:[jsxRuntime.jsxs("div",{className:"rounded-xl border border-red-500/20 bg-red-500/5 px-6 py-5 text-center max-w-sm",children:[jsxRuntime.jsx("p",{className:"text-sm font-medium text-foreground",children:"Unable to load your keys"}),jsxRuntime.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:m})]}),jsxRuntime.jsx("button",{onClick:()=>f(),className:"text-sm text-muted-foreground hover:text-foreground transition-colors",children:"Try again"})]});let _=s.filter(K=>K.status==="active");return _.length===0?jsxRuntime.jsxs("div",{className:u("flex flex-col items-center justify-center gap-3 rounded-xl border border-dashed py-16",e),style:t,children:[jsxRuntime.jsx(lucideReact.AlertTriangle,{className:"h-8 w-8 text-muted-foreground"}),jsxRuntime.jsx("p",{className:"text-sm text-muted-foreground",children:"No active keys to sell."})]}):jsxRuntime.jsxs("div",{className:u("space-y-5",e),style:t,children:[jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("h3",{className:"text-2xl mt-3 mb-2 font-semibold text-foreground",children:"Your Keys"}),jsxRuntime.jsx("div",{className:"space-y-2",children:_.map(K=>jsxRuntime.jsx(At,{nodeKey:K,selected:p===K.id,onSelect:()=>i(K.id)},K.id))})]}),P&&jsxRuntime.jsxs("div",{className:"rounded-xl border bg-muted/30 p-5 space-y-2 text-sm",children:[P.keyIndex&&jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsx("span",{className:"text-muted-foreground",children:"Key #"}),jsxRuntime.jsxs("span",{className:"text-foreground font-semibold",children:["#",P.keyIndex]})]}),jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsx("span",{className:"text-muted-foreground",children:"Key ID"}),jsxRuntime.jsx("code",{className:"text-xs text-foreground",children:P.id})]}),jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsx("span",{className:"text-muted-foreground",children:"Originating Stack"}),jsxRuntime.jsx("span",{className:"text-foreground",children:r.stackName||"Unknown"})]}),jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsx("span",{className:"text-muted-foreground",children:"Tokens (remaining / total)"}),jsxRuntime.jsxs("span",{className:"text-foreground",children:[I(P.tokenBalance)," / ",I(P.maxTokens)]})]}),P.paperWork&&jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsx("span",{className:"text-muted-foreground",children:"Paper earned"}),jsxRuntime.jsx("span",{className:"text-foreground",children:P.paperWork})]}),jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsx("span",{className:"text-muted-foreground",children:"Created"}),jsxRuntime.jsx("span",{className:"text-foreground",children:z(P.createdAt)})]})]}),jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("label",{htmlFor:"listing-price",className:"mb-2 block text-sm sm:text-lg font-semibold text-foreground",children:"Listing Price (USD)"}),jsxRuntime.jsxs("div",{className:"relative",children:[jsxRuntime.jsx("span",{className:"absolute left-4 top-1/2 -translate-y-1/2 text-2xl font-bold text-muted-foreground",children:"$"}),jsxRuntime.jsx("input",{id:"listing-price",type:"text",inputMode:"numeric",value:o,onChange:K=>{let F=K.target.value.replace(/[^0-9]/g,""),W=parseInt(F,10);l(isNaN(W)?"":W.toLocaleString("en-US"));},placeholder:"0",className:"w-full rounded-xl border bg-background py-6 pl-10 pr-4 text-3xl font-bold text-foreground placeholder:text-muted-foreground/30 focus:outline-none focus:ring-2 focus:ring-foreground/20"})]})]}),jsxRuntime.jsxs("div",{className:"flex items-start gap-3",children:[jsxRuntime.jsx("button",{type:"button",role:"checkbox","aria-checked":b,onClick:()=>w(!b),className:u("mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded border-2 transition-colors cursor-pointer",b?"border-foreground bg-foreground":"border-muted-foreground/40"),children:b&&jsxRuntime.jsx(lucideReact.Check,{className:"h-3 w-3 text-background"})}),jsxRuntime.jsxs("span",{className:"text-xs text-muted-foreground leading-relaxed",children:["I agree to list this key on the Global Open AI Network marketplace. The key will be deactivated upon sale and transferred to the buyer. Listing fees may apply."," ",jsxRuntime.jsx("a",{href:r.termsUrl||"/terms",className:"text-foreground underline",target:"_blank",rel:"noopener noreferrer",children:"Terms"})]})]}),d&&jsxRuntime.jsx("p",{className:"text-sm text-red-500",children:d}),jsxRuntime.jsxs("button",{onClick:q,disabled:!k,className:u("flex w-full items-center justify-center gap-2 rounded-xl py-4 text-sm font-semibold transition-colors",k?"bg-foreground text-background hover:bg-foreground/90":"bg-muted text-muted-foreground cursor-not-allowed"),children:[jsxRuntime.jsx(lucideReact.ExternalLink,{className:"h-4 w-4"}),n?"Listing...":"List on Marketplace"]})]})}function Qe(){let{config:e,callbacks:t}=C(),[r,s]=yt.useState(false),[g,m]=yt.useState(null),[f,a]=yt.useState(null),n=yt.useRef(true);return {transferKey:yt.useCallback(async(d,p)=>{try{s(!0),a(null);let i=await fetch(`${e.apiBaseUrl}/api/keys/${d}/transfer`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recipientId:p})});if(!i.ok){let l=`Transfer failed (${i.status})`;try{let b=await i.json();b.error&&(l=b.error);}catch{}throw new Error(l)}let o=await i.json();return n.current&&(m(o),t.onTransferComplete?.(o)),o}catch(i){let o=i instanceof Error?i.message:"Transfer failed";return n.current&&a(o),null}finally{n.current&&s(false);}},[e.apiBaseUrl,t]),transferring:r,result:g,error:f}}function Qt({nodeKey:e,selected:t,onSelect:r}){return jsxRuntime.jsxs("button",{onClick:r,className:u("flex w-full items-start gap-3 rounded-xl border p-4 text-left transition-all",t?"border-foreground/30 bg-foreground/5 ring-1 ring-foreground/10":"border-border hover:border-foreground/20"),children:[jsxRuntime.jsx("div",{className:u("mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-2 transition-colors",t?"border-foreground bg-foreground":"border-muted-foreground/40"),children:t&&jsxRuntime.jsx(lucideReact.Check,{className:"h-3 w-3 text-background"})}),jsxRuntime.jsxs("div",{className:"min-w-0 flex-1",children:[jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsxs("span",{className:"text-sm font-medium text-foreground",children:[e.keyIndex?`#${e.keyIndex} `:"",e.label||e.id.slice(0,16)]}),jsxRuntime.jsx("span",{className:"text-xs font-medium capitalize text-green-500",children:e.status})]}),jsxRuntime.jsx(V,{current:e.tokenBalance,max:e.maxTokens,className:"mt-2"})]})]})}function ve({className:e,style:t}){let{keys:r,loading:s}=J(),{transferKey:g,transferring:m,result:f,error:a}=Qe(),[n,c]=yt.useState(null),[d,p]=yt.useState(""),[i,o]=yt.useState(false),l=r.filter(k=>k.status==="active"),b=l.find(k=>k.id===n),w=b&&d.trim()===b.userId,P=n&&d.trim().length>0&&i&&!w&&!m,T=async()=>{!n||!d.trim()||await g(n,d.trim());},j=()=>{c(null),p(""),o(false);};return f?jsxRuntime.jsxs("div",{className:u("flex flex-col items-center gap-4 py-8",e),style:t,children:[jsxRuntime.jsx(lucideReact.CheckCircle,{className:"h-12 w-12 text-green-500"}),jsxRuntime.jsxs("div",{className:"text-center",children:[jsxRuntime.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Transfer Complete"}),jsxRuntime.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Key transferred successfully"})]}),jsxRuntime.jsxs("div",{className:"w-full max-w-sm space-y-2 rounded-xl border border-border bg-muted/30 p-4 text-sm",children:[jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsx("span",{className:"text-muted-foreground",children:"Key"}),jsxRuntime.jsxs("span",{className:"font-mono text-foreground",children:[f.keyId.slice(0,20),"..."]})]}),jsxRuntime.jsxs("div",{className:"flex justify-between",children:[jsxRuntime.jsx("span",{className:"text-muted-foreground",children:"Recipient"}),jsxRuntime.jsxs("span",{className:"font-mono text-foreground",children:[f.toUserId.slice(0,20),"..."]})]})]}),jsxRuntime.jsx("button",{onClick:j,className:"mt-2 rounded-lg border border-border px-4 py-2 text-sm font-medium text-foreground hover:bg-muted/50 transition-colors",children:"Transfer Another"})]}):jsxRuntime.jsxs("div",{className:u("space-y-5",e),style:t,children:[jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("h3",{className:"mb-3 text-sm font-medium text-foreground",children:"Select Key to Transfer"}),s?jsxRuntime.jsx(Y,{count:2}):l.length===0?jsxRuntime.jsx("p",{className:"text-sm text-muted-foreground",children:"No active keys available for transfer."}):jsxRuntime.jsx("div",{className:"space-y-2",children:l.map(k=>jsxRuntime.jsx(Qt,{nodeKey:k,selected:n===k.id,onSelect:()=>c(k.id)},k.id))})]}),n&&jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("label",{className:"mb-1.5 block text-sm font-medium text-foreground",children:"Recipient User ID"}),jsxRuntime.jsx("input",{type:"text",value:d,onChange:k=>{p(k.target.value),o(false);},placeholder:"Enter recipient's user ID or global ID",className:"w-full rounded-lg border border-border bg-background px-3 py-2.5 text-sm text-foreground placeholder:text-muted-foreground focus:border-foreground/30 focus:outline-none focus:ring-1 focus:ring-foreground/10"}),w&&jsxRuntime.jsx("p",{className:"mt-1.5 text-xs text-red-500",children:"Cannot transfer a key to yourself"})]}),b&&d.trim().length>0&&!w&&jsxRuntime.jsx("div",{className:"rounded-xl border border-amber-500/30 bg-amber-500/5 p-4",children:jsxRuntime.jsxs("div",{className:"flex items-start gap-3",children:[jsxRuntime.jsx(lucideReact.AlertTriangle,{className:"mt-0.5 h-5 w-5 shrink-0 text-amber-500"}),jsxRuntime.jsxs("div",{className:"space-y-3",children:[jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("p",{className:"text-sm font-medium text-foreground",children:"Confirm Transfer"}),jsxRuntime.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["You are about to transfer key"," ",jsxRuntime.jsx("span",{className:"font-mono font-medium",children:b.keyIndex?`#${b.keyIndex}`:b.id.slice(0,12)})," ","(",I(b.tokenBalance)," tokens) to"," ",jsxRuntime.jsxs("span",{className:"font-mono font-medium",children:[d.trim().slice(0,20),"..."]})]})]}),jsxRuntime.jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[jsxRuntime.jsx("input",{type:"checkbox",checked:i,onChange:k=>o(k.target.checked),className:"mt-0.5 h-4 w-4 rounded border-border"}),jsxRuntime.jsx("span",{className:"text-xs text-muted-foreground",children:"I confirm this transfer is permanent and cannot be undone."})]})]})]})}),a&&jsxRuntime.jsx("p",{className:"text-sm text-red-500",children:a}),jsxRuntime.jsx("button",{onClick:T,disabled:!P,className:u("flex w-full items-center justify-center gap-2 rounded-lg px-4 py-3 text-sm font-medium transition-all",P?"bg-foreground text-background hover:opacity-90":"bg-muted text-muted-foreground cursor-not-allowed"),children:m?jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Transferring..."]}):jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(lucideReact.Send,{className:"h-4 w-4"}),"Transfer Key"]})})]})}var qt=[{id:"buy",label:"Buy"},{id:"use",label:"Use"},{id:"sell",label:"Sell"},{id:"transfer",label:"Transfer"}];function zt({active:e,onChange:t}){return jsxRuntime.jsx("div",{role:"tablist","aria-label":"Key actions",className:"flex gap-1 rounded-2xl bg-muted/50 p-1.5",children:qt.map(({id:r,label:s})=>jsxRuntime.jsx("button",{role:"tab","aria-selected":e===r,"aria-controls":`panel-${r}`,id:`tab-${r}`,onClick:()=>t(r),className:u("flex flex-1 items-center justify-center gap-2.5 rounded-xl py-3.5 text-sm font-medium transition-all",e===r?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:jsxRuntime.jsx("span",{className:"inline",children:s})},r))})}function Yt({defaultTab:e="buy",className:t,style:r}){let[s,g]=yt.useState(e);return jsxRuntime.jsxs("div",{className:u("flex flex-col",t),style:r,children:[jsxRuntime.jsx("div",{className:"sticky top-0 z-10 bg-background/80 px-5 pb-3 pt-2 sm:pt-5 backdrop-blur-sm sm:px-10 md:px-16 lg:px-20",children:jsxRuntime.jsx("div",{className:"mx-auto max-w-xl",children:jsxRuntime.jsx(zt,{active:s,onChange:g})})}),jsxRuntime.jsx("div",{className:"flex flex-1 flex-col px-5 pb-8 sm:px-10 md:px-16 md:pb-12 lg:px-20",children:jsxRuntime.jsx("div",{className:"mx-auto w-full max-w-xl flex-1",children:jsxRuntime.jsxs("div",{role:"tabpanel",id:`panel-${s}`,"aria-labelledby":`tab-${s}`,children:[s==="buy"&&jsxRuntime.jsx(fe,{className:"flex-1"}),s==="use"&&jsxRuntime.jsx(pe,{className:"flex-1"}),s==="sell"&&jsxRuntime.jsx(be,{className:"flex-1"}),s==="transfer"&&jsxRuntime.jsx(ve,{className:"flex-1"})]})})})]})}function Jt({apiBaseUrl:e,stackId:t,stackName:r,paymentMethods:s,merchantWallet:g,stripePublicKey:m,theme:f,maxQuantity:a,keyImage:n,keyImageClass:c,aispImage:d,termsUrl:p,onMintSuccess:i,onMintError:o,onPaymentStart:l,onPaymentComplete:b,onListingCreated:w,onTransferComplete:P,defaultTab:T,className:j,style:k}){return jsxRuntime.jsx(oe,{config:{apiBaseUrl:e,stackId:t,stackName:r,paymentMethods:s,merchantWallet:g,stripePublicKey:m,theme:f,maxQuantity:a,keyImage:n,keyImageClass:c,aispImage:d,termsUrl:p},callbacks:{onMintSuccess:i,onMintError:o,onPaymentStart:l,onPaymentComplete:b,onListingCreated:w,onTransferComplete:P},children:jsxRuntime.jsx(Yt,{defaultTab:T,className:j,style:k})})}function ze(e){let{config:t}=C(),[r,s]=yt.useState([]),[g,m]=yt.useState(false),[f,a]=yt.useState(null),n=yt.useRef(true),c=t.apiBaseUrl,d=yt.useCallback(async()=>{if(e)try{m(!0),a(null);let p=await fetch(`${c}/api/keys/${e}/ledger`);if(!p.ok){let o=`Failed to fetch ledger (${p.status})`;try{let l=await p.json();l.error&&(o=l.error);}catch{}throw new Error(o)}let i=await p.json();n.current&&s(Array.isArray(i)?i:i.entries??[]);}catch(p){n.current&&a(p instanceof Error?p.message:"Failed to fetch ledger");}finally{n.current&&m(false);}},[c,e]);return yt.useEffect(()=>(n.current=true,d(),()=>{n.current=false;}),[d]),{entries:r,loading:g,error:f,refresh:d}}var we=20;function Pe({nodeKey:e,className:t,style:r}){let[s,g]=yt.useState(false),[m,f]=yt.useState(false),a=yt.useRef(null),{entries:n,loading:c}=ze(s?e.id:null);yt.useEffect(()=>()=>{a.current&&clearTimeout(a.current);},[]);let d=yt.useCallback(()=>{e.key&&(navigator.clipboard.writeText(e.key),f(true),a.current&&clearTimeout(a.current),a.current=setTimeout(()=>f(false),2e3));},[e.key]),p=e.status==="active"?"text-green-500":e.status==="expired"?"text-red-500":"text-yellow-500",i=n.slice(0,we);return jsxRuntime.jsxs("div",{className:u("rounded-lg border bg-background",t),style:r,children:[jsxRuntime.jsxs("div",{className:"p-4",children:[jsxRuntime.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsx("button",{onClick:()=>g(!s),"aria-expanded":s,"aria-label":s?"Collapse ledger":"Expand ledger",className:"text-muted-foreground hover:text-foreground",children:s?jsxRuntime.jsx(lucideReact.ChevronDown,{className:"h-4 w-4"}):jsxRuntime.jsx(lucideReact.ChevronRight,{className:"h-4 w-4"})}),jsxRuntime.jsxs("span",{className:"text-sm font-medium text-foreground",children:[e.keyIndex?`#${e.keyIndex} `:"",e.label||e.id.slice(0,16)]})]}),jsxRuntime.jsx("span",{className:u("text-xs font-medium capitalize",p),children:e.status})]}),e.key&&jsxRuntime.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[jsxRuntime.jsx("code",{className:"flex-1 truncate rounded bg-muted px-2 py-1 text-xs text-muted-foreground",children:e.key}),jsxRuntime.jsx("button",{onClick:d,"aria-label":"Copy key to clipboard",className:"shrink-0 rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground",children:m?jsxRuntime.jsx(lucideReact.Check,{className:"h-3.5 w-3.5 text-green-500"}):jsxRuntime.jsx(lucideReact.Copy,{className:"h-3.5 w-3.5"})})]}),jsxRuntime.jsx(V,{current:e.tokenBalance,max:e.maxTokens}),jsxRuntime.jsxs("div",{className:"mt-2 flex items-center justify-between text-xs text-muted-foreground",children:[jsxRuntime.jsxs("span",{children:["Created ",z(e.createdAt)]}),e.expiresAt&&jsxRuntime.jsxs("span",{children:["Expires ",z(e.expiresAt)]})]})]}),s&&jsxRuntime.jsxs("div",{className:"border-t px-4 py-3",children:[jsxRuntime.jsx("h4",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Ledger"}),c?jsxRuntime.jsx("p",{className:"text-xs text-muted-foreground",children:"Loading..."}):i.length===0?jsxRuntime.jsx("p",{className:"text-xs text-muted-foreground",children:"No ledger entries."}):jsxRuntime.jsxs("div",{className:"space-y-1.5",children:[i.map(o=>jsxRuntime.jsxs("div",{className:"flex items-center justify-between text-xs",children:[jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsxs("span",{className:u("font-medium",o.type==="credit"||o.type==="reward"?"text-green-500":"text-red-500"),children:[o.type==="credit"||o.type==="reward"?"+":"-",I(Math.abs(o.amount))]}),jsxRuntime.jsx("span",{className:"text-muted-foreground",children:o.description})]}),jsxRuntime.jsx("span",{className:"text-muted-foreground",children:z(o.createdAt)})]},o.id)),n.length>we&&jsxRuntime.jsxs("p",{className:"pt-1 text-xs text-muted-foreground",children:["Showing ",we," of ",n.length," entries"]})]})]})]})}var lr=[{id:"buy",label:"Buy"},{id:"use",label:"Use"},{id:"sell",label:"Sell"}];function ne({baseHref:e}){return jsxRuntime.jsx("div",{className:"flex gap-1 rounded-2xl bg-muted/50 p-1.5 mb-6",children:lr.map(({id:t,label:r})=>jsxRuntime.jsx("a",{href:`${e}?tab=${t}`,className:"flex flex-1 items-center justify-center gap-2.5 rounded-xl py-3.5 text-sm font-medium text-muted-foreground hover:text-foreground transition-all",children:r},t))})}function cr({getKeyHref:e="/keys/get",showTabs:t=true,className:r,style:s}){let{keys:g,totalBalance:m,loading:f,error:a,refresh:n}=J();return f?jsxRuntime.jsxs("div",{className:u("space-y-4",r),style:s,children:[t&&e&&jsxRuntime.jsx(ne,{baseHref:e}),jsxRuntime.jsx(Y,{count:3})]}):a?jsxRuntime.jsxs("div",{className:u("space-y-4",r),style:s,children:[t&&e&&jsxRuntime.jsx(ne,{baseHref:e}),jsxRuntime.jsxs("div",{className:"flex flex-col items-center justify-center gap-4 py-12",children:[jsxRuntime.jsxs("div",{className:"rounded-xl border border-red-500/20 bg-red-500/5 px-6 py-5 text-center max-w-sm",children:[jsxRuntime.jsx("p",{className:"text-sm font-medium text-foreground",children:"Unable to load your keys"}),jsxRuntime.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:a})]}),jsxRuntime.jsx("button",{onClick:()=>n(),className:"text-sm text-muted-foreground hover:text-foreground transition-colors",children:"Try again"})]})]}):g.length===0?jsxRuntime.jsxs("div",{className:u("space-y-4",r),style:s,children:[t&&e&&jsxRuntime.jsx(ne,{baseHref:e}),jsxRuntime.jsxs("div",{className:"flex flex-col items-center justify-center gap-4 rounded-lg border border-dashed py-12",children:[jsxRuntime.jsx(lucideReact.KeyRound,{className:"h-10 w-10 text-muted-foreground"}),jsxRuntime.jsxs("div",{className:"text-center",children:[jsxRuntime.jsx("p",{className:"text-sm font-medium text-foreground",children:"No keys yet"}),jsxRuntime.jsx("p",{className:"text-xs text-muted-foreground",children:"Get your first node key to start earning."})]}),e&&jsxRuntime.jsx("a",{href:e,className:"rounded-lg bg-foreground px-4 py-2 text-sm font-medium text-background transition-colors hover:bg-foreground/90",children:"Get a Key"})]})]}):jsxRuntime.jsxs("div",{className:u("space-y-4",r),style:s,children:[t&&e&&jsxRuntime.jsx(ne,{baseHref:e}),jsxRuntime.jsxs("div",{className:"flex items-center justify-between",children:[jsxRuntime.jsxs("p",{className:"text-sm text-muted-foreground",children:[g.length," key",g.length!==1?"s":""," \xB7 Total balance: ",I(m)]}),e&&jsxRuntime.jsx("a",{href:e,className:"rounded-md bg-foreground px-3 py-1.5 text-xs font-medium text-background transition-colors hover:bg-foreground/90",children:"Get a Key"})]}),g.map(c=>jsxRuntime.jsx(Pe,{nodeKey:c},c.id))]})}
2
+ exports.BuyKeyWidget=Jt;exports.BuyPanel=fe;exports.KeyBalanceBar=V;exports.KeyCard=Pe;exports.KeyList=cr;exports.KeyUtilsProvider=oe;exports.MintSuccess=ue;exports.SellPanel=be;exports.SolanaPayButton=de;exports.TransferPanel=ve;exports.UsePanel=pe;exports.useKeyUtilsContext=C;
@@ -19,7 +19,7 @@ interface BuyKeyWidgetProps extends KeyUtilsConfig, KeyUtilsCallbacks {
19
19
  className?: string;
20
20
  style?: React.CSSProperties;
21
21
  }
22
- declare function BuyKeyWidget({ apiBaseUrl, stackId, stackName, paymentMethods, merchantWallet, stripePublicKey, theme, maxQuantity, keyImage, keyImageClass, aispImage, termsUrl, onMintSuccess, onMintError, onPaymentStart, onPaymentComplete, onListingCreated, defaultTab, className, style, }: BuyKeyWidgetProps): react_jsx_runtime.JSX.Element;
22
+ declare function BuyKeyWidget({ apiBaseUrl, stackId, stackName, paymentMethods, merchantWallet, stripePublicKey, theme, maxQuantity, keyImage, keyImageClass, aispImage, termsUrl, onMintSuccess, onMintError, onPaymentStart, onPaymentComplete, onListingCreated, onTransferComplete, defaultTab, className, style, }: BuyKeyWidgetProps): react_jsx_runtime.JSX.Element;
23
23
 
24
24
  interface BuyPanelProps {
25
25
  className?: string;
@@ -81,4 +81,10 @@ interface MintSuccessProps {
81
81
  }
82
82
  declare function MintSuccess({ result, className, style }: MintSuccessProps): react_jsx_runtime.JSX.Element | null;
83
83
 
84
- export { BuyKeyWidget, type BuyKeyWidgetProps, BuyPanel, type BuyPanelProps, KeyBalanceBar, type KeyBalanceBarProps, KeyCard, type KeyCardProps, KeyList, type KeyListProps, KeyUtilsProvider, type KeyUtilsProviderProps, MintSuccess, type MintSuccessProps, SellPanel, type SellPanelProps, SolanaPayButton, type SolanaPayButtonProps, UsePanel, type UsePanelProps, useKeyUtilsContext };
84
+ interface TransferPanelProps {
85
+ className?: string;
86
+ style?: React.CSSProperties;
87
+ }
88
+ declare function TransferPanel({ className, style }: TransferPanelProps): react_jsx_runtime.JSX.Element;
89
+
90
+ export { BuyKeyWidget, type BuyKeyWidgetProps, BuyPanel, type BuyPanelProps, KeyBalanceBar, type KeyBalanceBarProps, KeyCard, type KeyCardProps, KeyList, type KeyListProps, KeyUtilsProvider, type KeyUtilsProviderProps, MintSuccess, type MintSuccessProps, SellPanel, type SellPanelProps, SolanaPayButton, type SolanaPayButtonProps, TransferPanel, type TransferPanelProps, UsePanel, type UsePanelProps, useKeyUtilsContext };
@@ -19,7 +19,7 @@ interface BuyKeyWidgetProps extends KeyUtilsConfig, KeyUtilsCallbacks {
19
19
  className?: string;
20
20
  style?: React.CSSProperties;
21
21
  }
22
- declare function BuyKeyWidget({ apiBaseUrl, stackId, stackName, paymentMethods, merchantWallet, stripePublicKey, theme, maxQuantity, keyImage, keyImageClass, aispImage, termsUrl, onMintSuccess, onMintError, onPaymentStart, onPaymentComplete, onListingCreated, defaultTab, className, style, }: BuyKeyWidgetProps): react_jsx_runtime.JSX.Element;
22
+ declare function BuyKeyWidget({ apiBaseUrl, stackId, stackName, paymentMethods, merchantWallet, stripePublicKey, theme, maxQuantity, keyImage, keyImageClass, aispImage, termsUrl, onMintSuccess, onMintError, onPaymentStart, onPaymentComplete, onListingCreated, onTransferComplete, defaultTab, className, style, }: BuyKeyWidgetProps): react_jsx_runtime.JSX.Element;
23
23
 
24
24
  interface BuyPanelProps {
25
25
  className?: string;
@@ -81,4 +81,10 @@ interface MintSuccessProps {
81
81
  }
82
82
  declare function MintSuccess({ result, className, style }: MintSuccessProps): react_jsx_runtime.JSX.Element | null;
83
83
 
84
- export { BuyKeyWidget, type BuyKeyWidgetProps, BuyPanel, type BuyPanelProps, KeyBalanceBar, type KeyBalanceBarProps, KeyCard, type KeyCardProps, KeyList, type KeyListProps, KeyUtilsProvider, type KeyUtilsProviderProps, MintSuccess, type MintSuccessProps, SellPanel, type SellPanelProps, SolanaPayButton, type SolanaPayButtonProps, UsePanel, type UsePanelProps, useKeyUtilsContext };
84
+ interface TransferPanelProps {
85
+ className?: string;
86
+ style?: React.CSSProperties;
87
+ }
88
+ declare function TransferPanel({ className, style }: TransferPanelProps): react_jsx_runtime.JSX.Element;
89
+
90
+ export { BuyKeyWidget, type BuyKeyWidgetProps, BuyPanel, type BuyPanelProps, KeyBalanceBar, type KeyBalanceBarProps, KeyCard, type KeyCardProps, KeyList, type KeyListProps, KeyUtilsProvider, type KeyUtilsProviderProps, MintSuccess, type MintSuccessProps, SellPanel, type SellPanelProps, SolanaPayButton, type SolanaPayButtonProps, TransferPanel, type TransferPanelProps, UsePanel, type UsePanelProps, useKeyUtilsContext };
@@ -1,2 +1,2 @@
1
- import it,{createContext,useContext,useMemo,useState,useCallback,useRef,useEffect}from'react';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {clsx}from'clsx';import {twMerge}from'tailwind-merge';import {Loader2,CheckCircle,Check,Copy,CreditCard,Wallet,Download,AlertTriangle,ExternalLink,ChevronDown,ChevronRight,KeyRound,Minus,Plus,ChevronUp}from'lucide-react';var ve=createContext(null);function v(){let e=useContext(ve);if(!e)throw new Error("useKeyUtilsContext must be used within a KeyUtilsProvider");return e}function te({config:e,callbacks:t={},children:r}){typeof e.apiBaseUrl!="string"&&console.error("[KeyUtils] apiBaseUrl must be a string");let s=useMemo(()=>({config:e,callbacks:t}),[e,t]);return jsx(ve.Provider,{value:s,children:r})}function f(...e){return twMerge(clsx(e))}function T(e){return e==null?"0":e>=1e9?`${(e/1e9).toFixed(1)}B`:e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:e.toLocaleString()}function Ne(e,t){return t<=0?0:Math.min(100,Math.round(e/t*100))}function ke(e){return e>=70?"bg-green-500":e>=30?"bg-yellow-500":"bg-red-500"}function F(e){let t=typeof e=="string"&&/^\d+$/.test(e)?Number(e):e,r=new Date(t);return isNaN(r.getTime())?String(e):r.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}function we(){if(typeof navigator>"u")return "mac";let e=navigator.userAgent.toLowerCase();return /iphone|ipad|ipod/.test(e)?"ios":/android/.test(e)?"android":/win/.test(e)?"windows":/linux/.test(e)?"linux":"mac"}function Ce(){let{config:e}=v(),[t,r]=useState(null),[s,d]=useState(true),[u,g]=useState(null),a=useRef(true),n=useRef(e.apiBaseUrl);n.current=e.apiBaseUrl;let i=async()=>{try{a.current&&(d(!0),g(null));let p=await fetch(`${n.current}/api/keys/pricing`);if(!p.ok){let l=`Pricing unavailable (${p.status})`;try{let o=await p.json();o.error&&(l=o.error);}catch{}throw new Error(l)}let m=await p.json();a.current&&r(m);}catch(p){a.current&&g(p instanceof Error?p.message:"Failed to fetch pricing");}finally{a.current&&d(false);}};return useEffect(()=>{a.current=true,i();let p=setInterval(i,6e4);return ()=>{a.current=false,clearInterval(p);}},[]),{pricing:t,loading:s,error:u,refresh:i}}function Se(){let{config:e,callbacks:t}=v(),[r,s]=useState(false),[d,u]=useState(null),[g,a]=useState(null);return {mint:useCallback(async(i,p,m=1)=>{try{s(!0),a(null),t.onPaymentComplete?.(i,p);let l=await fetch(`${e.apiBaseUrl}/api/keys/mint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paymentMethod:i,paymentRef:p,quantity:m})});if(!l.ok){let P="Key generation failed";try{let w=await l.json();w.error&&(P=w.error);}catch{}throw new Error(P)}let o=await l.json(),c=o.keys?.[0]||o,N={success:!0,key:{id:c.keyId||c.id||"",key:c.key||"",userId:c.userId||"",status:"active",tokenBalance:c.tokenBalance??c.currentTokenBalance??0,maxTokens:c.initialTokenBalance??c.tokenBalance??0,createdAt:String(c.createdAt||Date.now())},transactionId:p};return u(N),t.onMintSuccess?.(N),N}catch(l){let o=l instanceof Error?l:new Error("Key generation failed");return a(o.message),t.onMintError?.(o),{success:false,error:o.message}}finally{s(false);}},[e.apiBaseUrl,t]),minting:r,result:d,error:g}}function Ue(){let{config:e}=v(),[t,r]=useState(false),[s,d]=useState(null),u=useRef(true);return {createSession:useCallback(async(a,n)=>{try{r(!0),d(null);let i=await fetch(`${e.apiBaseUrl}/api/keys/stripe-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({priceCents:a,quantity:n,stackId:e.stackId,referrerUrl:window.location.href})});if(!i.ok){let m=`Checkout failed (${i.status})`;try{let l=await i.json();l.error&&(m=l.error);}catch{}throw new Error(m)}let{url:p}=await i.json();if(p){try{sessionStorage.setItem("keyutils_stripe_pending","1");}catch{}window.location.href=p;}else throw new Error("No checkout URL returned")}catch(i){if(u.current){let p=i instanceof Error?i.message:"Checkout failed";d(p),r(false);}}},[e.apiBaseUrl,e.stackId]),loading:t,error:s}}var He=/^[1-9A-HJ-NP-Za-km-z]{32,44}$/;function ae({amountSol:e,onSuccess:t,onError:r,disabled:s,className:d,style:u}){let{config:g}=v(),[a,n]=useState(false),[i,p]=useState(null),m=!!(g.merchantWallet&&He.test(g.merchantWallet)),l=useCallback(async()=>{if(m)try{n(!0),p(null);let{Connection:o,PublicKey:c,Transaction:N,SystemProgram:P,LAMPORTS_PER_SOL:w}=await import('@solana/web3.js'),B=typeof window<"u"?window.solana:void 0;if(!B||typeof B!="object"||!B.isPhantom)throw new Error("Phantom wallet not found. Please install Phantom.");let L=B,j;try{j=new c(g.merchantWallet);}catch{throw new Error("Invalid merchant wallet address.")}let A=await L.connect(),k=new c(A.publicKey.toString()),W=new o(g.solanaRpcUrl||"https://api.mainnet-beta.solana.com"),{blockhash:$}=await W.getLatestBlockhash(),H=BigInt(Math.floor(e*1e9)),ee=new N({recentBlockhash:$,feePayer:k}).add(P.transfer({fromPubkey:k,toPubkey:j,lamports:Number(H)})),{signature:U}=await L.signAndSendTransaction(ee);t(U);}catch(o){let c=o instanceof Error?o:new Error("Payment failed");p(c.message),r?.(c);}finally{n(false);}},[e,g.merchantWallet,m,t,r]);return jsxs("div",{children:[jsx("button",{onClick:l,disabled:s||a||!m,"aria-label":`Pay ${e.toFixed(4)} SOL`,className:f("flex w-full items-center justify-center gap-2 rounded-lg bg-purple-600 px-4 py-3 font-medium text-white transition-colors hover:bg-purple-700 disabled:opacity-50 disabled:cursor-not-allowed",d),style:u,children:a?jsxs(Fragment,{children:[jsx(Loader2,{className:"h-4 w-4 animate-spin"}),"Processing..."]}):jsxs(Fragment,{children:["Pay ",e.toFixed(4)," SOL"]})}),i&&jsx("p",{className:"mt-2 text-center text-xs text-red-500",children:i})]})}function ie({result:e,className:t,style:r}){let[s,d]=useState(false),u=useRef(null);useEffect(()=>()=>{u.current&&clearTimeout(u.current);},[]);let g=useCallback(()=>{e.key?.key&&(navigator.clipboard.writeText(e.key.key),d(true),u.current&&clearTimeout(u.current),u.current=setTimeout(()=>d(false),2e3));},[e.key?.key]);return !e.success||!e.key?null:jsxs("div",{className:f("rounded-lg border border-green-500/20 bg-green-500/10 p-6 text-center",t),style:r,children:[jsx(CheckCircle,{className:"mx-auto mb-3 h-12 w-12 text-green-500"}),jsx("h3",{className:"mb-2 text-lg font-semibold text-foreground",children:"Key Generated!"}),jsx("p",{className:"mb-4 text-sm text-muted-foreground",children:"Your node key has been successfully generated."}),jsxs("div",{className:"mx-auto flex max-w-md items-center gap-2 rounded-md border bg-background p-3",children:[jsx("code",{className:"flex-1 truncate text-xs text-foreground",children:e.key.key}),jsx("button",{onClick:g,"aria-label":"Copy key to clipboard",className:"shrink-0 rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:s?jsx(Check,{className:"h-4 w-4 text-green-500"}):jsx(Copy,{className:"h-4 w-4"})})]})]})}function I({className:e}){return jsx("div",{className:f("animate-pulse rounded-xl bg-muted",e)})}function le(){return jsxs("div",{className:"space-y-6",children:[jsxs("div",{className:"px-6 py-10 flex flex-col items-center gap-3",children:[jsx(I,{className:"h-14 w-48"}),jsx(I,{className:"h-5 w-64"})]}),jsx(I,{className:"h-[72px] w-full rounded-2xl"}),jsx(I,{className:"h-[68px] w-full rounded-2xl"}),jsx(I,{className:"h-[60px] w-full rounded-2xl"})]})}function Y({count:e=3}){return jsx("div",{className:"space-y-3",children:Array.from({length:e}).map((t,r)=>jsxs("div",{className:"rounded-xl border p-4 space-y-3",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx(I,{className:"h-4 w-32"}),jsx(I,{className:"h-4 w-16"})]}),jsx(I,{className:"h-2 w-full rounded-full"}),jsxs("div",{className:"flex justify-between",children:[jsx(I,{className:"h-3 w-24"}),jsx(I,{className:"h-3 w-20"})]})]},r))})}function gt({quantity:e,max:t,onChange:r}){return jsxs("div",{className:"flex items-center justify-between rounded-2xl border bg-muted/20 px-6 py-5",children:[jsx("span",{className:"text-sm font-medium text-foreground",children:"Quantity"}),jsxs("div",{className:"flex items-center gap-0 rounded-xl border bg-background",children:[jsx("button",{onClick:()=>r(Math.max(1,e-1)),disabled:e<=1,"aria-label":"Decrease quantity",className:"flex h-12 w-12 items-center justify-center rounded-l-xl text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-30",children:jsx(Minus,{className:"h-5 w-5"})}),jsx("span",{className:"flex h-12 w-14 items-center justify-center border-x text-xl font-bold text-foreground","aria-live":"polite",children:e}),jsx("button",{onClick:()=>r(Math.min(t,e+1)),disabled:e>=t,"aria-label":"Increase quantity",className:"flex h-12 w-12 items-center justify-center rounded-r-xl text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-30",children:jsx(Plus,{className:"h-5 w-5"})})]})]})}function Ee({pricing:e,quantity:t}){let[r,s]=useState(false),d=e.priceUsd*t;return jsxs("div",{className:"rounded-2xl border bg-background",children:[jsxs("button",{onClick:()=>s(!r),"aria-expanded":r,className:"flex w-full items-center justify-between px-6 py-5 text-left",children:[jsxs("span",{className:"text-foreground",children:[jsxs("span",{className:"text-xl font-bold",children:["$",d.toFixed(2)]})," ",jsx("span",{className:"text-sm text-muted-foreground",children:"total fees included"})]}),r?jsx(ChevronUp,{className:"h-5 w-5 text-muted-foreground"}):jsx(ChevronDown,{className:"h-5 w-5 text-muted-foreground"})]}),r&&jsxs("div",{className:"border-t px-6 pb-8 pt-4 space-y-3 text-sm",children:[jsxs("div",{className:"flex justify-between",children:[jsxs("span",{className:"text-muted-foreground",children:["Node Key \xD7 ",t]}),jsxs("span",{className:"text-foreground",children:["$",(e.priceUsd*t).toFixed(2)]})]}),jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Keys sold"}),jsx("span",{className:"text-foreground",children:e.keysSold})]}),e.daysUntilHalving>0&&jsxs("div",{className:"flex justify-between text-muted-foreground",children:[jsx("span",{children:"Next refresh"}),jsxs("span",{children:[e.daysUntilHalving," day",e.daysUntilHalving!==1?"s":""]})]}),jsxs("div",{className:"flex justify-between border-t pt-3 font-semibold",children:[jsx("span",{className:"text-foreground",children:"Total"}),jsxs("span",{className:"text-foreground",children:["$",d.toFixed(2)]})]})]})]})}function ce({className:e,style:t}){let{config:r}=v(),{pricing:s,loading:d,error:u,refresh:g}=Ce(),{mint:a,minting:n,result:i,error:p}=Se(),{createSession:m,loading:l,error:o}=Ue(),[c,N]=useState(1),[P,w]=useState(r.paymentMethods?.includes("stripe")?"stripe":"solana"),[B,L]=useState(0),[j,A]=useState(false),k=it.useRef(c);k.current=c;let W=Math.max(1,r.maxQuantity||5),$=[...r.paymentMethods||["solana"]].sort((U,G)=>U==="stripe"?-1:G==="stripe"?1:0);if(useEffect(()=>{if(typeof window>"u")return;let G=new URLSearchParams(window.location.search).get("session_id");if(!G){try{sessionStorage.removeItem("keyutils_stripe_pending");}catch{}return}if(/^cs_(test|live)_/.test(G)&&!j&&!i?.success){let be=false;try{be=sessionStorage.getItem("keyutils_stripe_pending")==="1";}catch{}if(!be)return;try{sessionStorage.removeItem("keyutils_stripe_pending");}catch{}A(true);let he=new URL(window.location.href);he.searchParams.delete("session_id"),window.history.replaceState({},"",he.toString()),a("stripe",G,k.current);}},[j,i,a]),i?.success)return jsx("div",{className:f("flex flex-col items-center justify-center",e),style:t,children:jsx(ie,{result:i})});if(j||n)return jsx("div",{className:f("flex flex-col",e),style:t,children:jsx(le,{})});if(d)return jsx("div",{className:f("flex flex-col",e),style:t,children:jsx(le,{})});if(u||!s)return jsxs("div",{className:f("flex flex-col items-center justify-center gap-4 py-24",e),style:t,children:[jsxs("div",{className:"rounded-xl border border-red-500/20 bg-red-500/5 px-6 py-5 text-center max-w-sm",children:[jsx("p",{className:"text-sm font-medium text-foreground",children:"Unable to load pricing"}),jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:u||"Please check your connection and try again."})]}),jsx("button",{onClick:()=>g(),className:"text-sm text-muted-foreground hover:text-foreground transition-colors",children:"Try again"})]});let H=async U=>{L(2),await a(P,U,c);},ee=()=>{m(s.priceCents,c);};return jsx("div",{className:f("flex flex-col",e),style:t,children:jsxs("div",{className:"space-y-6",children:[B===0&&jsxs(Fragment,{children:[r.keyImage&&jsx("img",{src:r.keyImage,alt:"Node Key",className:r.keyImageClass||"w-1/2 mx-auto"}),jsxs("div",{className:"px-6 py-10 text-center",children:[jsxs("p",{className:"text-5xl font-bold tracking-tight text-foreground md:text-6xl",children:["$",s.priceUsd.toFixed(2)]}),jsxs("p",{className:"mt-2 text-base text-muted-foreground",children:["per key \xB7 ",s.tokenAllocationFormatted||T(s.tokenAllocation)," tokens included"]})]}),jsx(gt,{quantity:c,max:W,onChange:N}),jsx(Ee,{pricing:s,quantity:c}),jsx("button",{onClick:()=>L(1),className:"w-full rounded-2xl bg-foreground py-5 text-center text-base font-semibold text-background transition-colors hover:bg-foreground/90",children:"Continue to Payment"})]}),B===1&&jsxs(Fragment,{children:[$.length>1&&jsx("div",{role:"tablist",className:"flex gap-1 rounded-2xl bg-muted/50 p-1.5",children:$.map(U=>jsxs("button",{role:"tab","aria-selected":P===U,onClick:()=>w(U),className:f("flex flex-1 items-center justify-center gap-2.5 rounded-xl py-4 text-sm font-medium transition-colors",P===U?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[U==="stripe"?jsx(CreditCard,{className:"h-5 w-5"}):jsx(Wallet,{className:"h-5 w-5"}),U==="stripe"?"Credit Card":"Crypto"]},U))}),jsx(Ee,{pricing:s,quantity:c}),P==="stripe"?jsxs(Fragment,{children:[jsx("button",{onClick:ee,disabled:l,className:"flex w-full items-center justify-center gap-2 rounded-2xl bg-foreground py-5 text-base font-semibold text-background transition-colors hover:bg-foreground/90 disabled:opacity-50",children:l?jsxs(Fragment,{children:[jsx(Loader2,{className:"h-5 w-5 animate-spin"}),"Redirecting to Stripe..."]}):jsxs(Fragment,{children:[jsx(CreditCard,{className:"h-5 w-5"}),"Pay with Card"]})}),o&&jsx("p",{className:"text-center text-sm text-red-500",children:o})]}):P==="solana"?jsx(ae,{amountSol:s.priceSol??0,onSuccess:H,className:"rounded-2xl py-5 text-base"}):null,p&&jsx("p",{className:"text-center text-sm text-red-500",children:p}),jsx("button",{onClick:()=>L(0),className:"w-full py-3 text-center text-sm text-muted-foreground hover:text-foreground transition-colors",children:"\u2190 Back"})]})]})})}var ht={ios:"iOS",android:"Android",windows:"Windows",mac:"macOS",linux:"Linux"},vt=["mac","windows","linux","ios","android"];function de({downloads:e,className:t,style:r}){let{config:s}=v(),d=useMemo(()=>we(),[]),u=e||vt.map(n=>({platform:n,label:ht[n],url:"#",compatible:n===d})),g=u.find(n=>n.compatible)||u[0],a=u.filter(n=>n.platform!==g.platform);return jsxs("div",{className:f("space-y-8",t),style:r,children:[jsxs("div",{className:"flex flex-col items-center gap-6 pt-4 mt-4",children:[s.aispImage&&jsx("img",{src:s.aispImage,alt:"aiSP",className:"w-full sm:w-1/2 mx-auto px-4 sm:px-0"}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-lg sm:text-2xl font-medium text-foreground",children:"Download the AI Service Provider App"}),jsx("p",{className:"mt-1 text-sm sm:text-base text-muted-foreground",children:"Load your keys and run your node."})]}),jsxs("a",{href:g.url,className:"inline-flex items-center gap-3 rounded-full px-10 py-4 text-lg font-semibold text-white transition-colors hover:opacity-90",style:{backgroundColor:"#0900f4"},children:[jsx(Download,{className:"h-5 w-5"}),"Get aiSP for ",g.label]})]}),jsxs("p",{className:"text-center text-sm text-muted-foreground",children:["aiSP is also available on"," ",a.map((n,i)=>jsxs(it.Fragment,{children:[i>0&&(i===a.length-1?" and ":", "),jsx("a",{href:n.url,className:"font-medium underline transition-colors hover:text-foreground",style:{color:"#066bff"},children:n.label})]},n.platform)),"."]}),jsxs("div",{className:"flex flex-col items-center gap-2 mt-12",children:[jsxs("p",{className:"text-center text-xs text-muted-foreground flex justify-center gap-0.5 flex-wrap",children:["Source code is available on",jsx("a",{href:"https://github.com/stack-net",target:"_blank",rel:"noopener noreferrer",className:"text-foreground underline hover:text-foreground/80 color-[#0900f4]",children:"Github"})]}),jsxs("p",{className:"text-center text-xs text-muted-foreground flex justify-center gap-0.5 flex-wrap",children:["By downloading, you agree to the",jsx("a",{href:s.termsUrl||"/terms",className:"text-foreground underline hover:text-foreground/80",children:"Open Source Applications Terms"})]})]})]})}function Pt(e){return {id:e.id||"",key:e.key||e.keyPrefix||"",userId:e.userId||e.user_id||"",status:e.status||"active",tokenBalance:e.tokenBalance??e.currentTokenBalance??e.current_token_balance??0,maxTokens:e.maxTokens??e.initialTokenBalance??e.initial_token_balance??0,createdAt:String(e.createdAt??e.created_at??""),expiresAt:e.expiresAt,label:e.label||e.keyPrefix||e.key_prefix||void 0,paperWork:e.paperWork||e.paper_work||void 0,stackId:e.stackId,stackName:e.stackName}}function J(){let{config:e}=v(),[t,r]=useState([]),[s,d]=useState(true),[u,g]=useState(null),a=useRef(true),n=e.apiBaseUrl,i=useCallback(async()=>{try{d(!0),g(null);let m=await fetch(`${n}/api/keys`);if(!m.ok){let c=`Failed to fetch keys (${m.status})`;try{let N=await m.json();N.error&&(c=N.error);}catch{}throw new Error(c)}let l=await m.json(),o=Array.isArray(l)?l:l.keys??[];a.current&&r(o.map(Pt));}catch(m){a.current&&g(m instanceof Error?m.message:"Failed to fetch keys");}finally{a.current&&d(false);}},[n]);useEffect(()=>(a.current=true,i(),()=>{a.current=false;}),[i]);let p=t.reduce((m,l)=>m+l.tokenBalance,0);return {keys:t,totalBalance:p,loading:s,error:u,refresh:i}}function Me(){let{config:e,callbacks:t}=v(),[r,s]=useState(false),[d,u]=useState(null),[g,a]=useState(null),n=useRef(true),i=useCallback(async(m,l)=>{try{s(!0),a(null);let o=await fetch(`${e.apiBaseUrl}/api/keys/${m}/list`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({askPriceCents:l,stackId:e.stackId,stackName:e.stackName})});if(!o.ok){let N=`Listing failed (${o.status})`;try{let P=await o.json();P.error&&(N=P.error);}catch{}throw new Error(N)}let c=await o.json();return n.current&&(u(c),t.onListingCreated?.(c)),c}catch(o){let c=o instanceof Error?o.message:"Listing failed";return n.current&&a(c),null}finally{n.current&&s(false);}},[e.apiBaseUrl,e.stackId,e.stackName,t]),p=useCallback(async m=>{try{s(!0),a(null);let l=await fetch(`${e.apiBaseUrl}/api/keys/${m}/list`,{method:"DELETE"});if(!l.ok){let o=`Delist failed (${l.status})`;try{let c=await l.json();c.error&&(o=c.error);}catch{}throw new Error(o)}return n.current&&u(null),!0}catch(l){let o=l instanceof Error?l.message:"Delist failed";return n.current&&a(o),false}finally{n.current&&s(false);}},[e.apiBaseUrl]);return {listKey:i,delistKey:p,listing:r,result:d,error:g}}function z({current:e,max:t,className:r,style:s,showLabel:d=true}){let u=Ne(e,t),g=ke(u);return jsxs("div",{className:f("w-full",r),style:s,children:[d&&jsxs("div",{className:"mb-1 flex items-center justify-between text-xs text-muted-foreground",children:[jsxs("span",{children:[T(e)," / ",T(t)]}),jsxs("span",{children:[u,"%"]})]}),jsx("div",{className:"h-2 w-full overflow-hidden rounded-full bg-muted",children:jsx("div",{className:f("h-full rounded-full transition-all duration-500",g),style:{width:`${u}%`}})})]})}function Rt({nodeKey:e,selected:t,onSelect:r}){return jsxs("button",{onClick:r,className:f("flex w-full items-start gap-3 rounded-xl border p-4 text-left transition-all",t?"border-foreground/30 bg-foreground/5 ring-1 ring-foreground/10":"border-border hover:border-foreground/20"),children:[jsx("div",{className:f("mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-2 transition-colors",t?"border-foreground bg-foreground":"border-muted-foreground/40"),children:t&&jsx(Check,{className:"h-3 w-3 text-background"})}),jsxs("div",{className:"min-w-0 flex-1",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("span",{className:"text-sm font-medium text-foreground",children:e.label||e.id.slice(0,16)}),jsx("span",{className:f("text-xs font-medium capitalize",e.status==="active"?"text-green-500":"text-muted-foreground"),children:e.status})]}),jsx(z,{current:e.tokenBalance,max:e.maxTokens,className:"mt-2"})]})]})}function pe({className:e,style:t}){let{config:r}=v(),{keys:s,loading:d,error:u,refresh:g}=J(),{listKey:a,listing:n,result:i,error:p}=Me(),[m,l]=useState(null),[o,c]=useState(""),[N,P]=useState(false),w=s.find(k=>k.id===m),B=parseInt(o.replace(/[^0-9]/g,""),10)||0,L=w&&B>0&&N&&!n,j=async()=>{if(!L||!w)return;let k=B*100;await a(w.id,k)&&g();};if(i)return jsxs("div",{className:f("flex flex-col items-center gap-4 rounded-xl border border-green-500/20 bg-green-500/10 py-12",e),style:t,children:[jsx(CheckCircle,{className:"h-12 w-12 text-green-500"}),jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Key Listed!"}),jsx("p",{className:"text-sm text-muted-foreground",children:"Your key is now on the Global Open AI Network marketplace."}),jsxs("p",{className:"text-xs text-muted-foreground",children:["Listing ID: ",jsx("code",{children:i.listingId})]})]});if(d)return jsxs("div",{className:f("space-y-5 px-1",e),style:t,children:[jsx("h3",{className:"text-2xl mt-3 mb-2 font-semibold text-foreground",children:"Your Keys"}),jsx(Y,{count:2})]});if(u)return jsxs("div",{className:f("flex flex-col items-center justify-center gap-4 py-16",e),style:t,children:[jsxs("div",{className:"rounded-xl border border-red-500/20 bg-red-500/5 px-6 py-5 text-center max-w-sm",children:[jsx("p",{className:"text-sm font-medium text-foreground",children:"Unable to load your keys"}),jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:u})]}),jsx("button",{onClick:()=>g(),className:"text-sm text-muted-foreground hover:text-foreground transition-colors",children:"Try again"})]});let A=s.filter(k=>k.status==="active");return A.length===0?jsxs("div",{className:f("flex flex-col items-center justify-center gap-3 rounded-xl border border-dashed py-16",e),style:t,children:[jsx(AlertTriangle,{className:"h-8 w-8 text-muted-foreground"}),jsx("p",{className:"text-sm text-muted-foreground",children:"No active keys to sell."})]}):jsxs("div",{className:f("space-y-5",e),style:t,children:[jsxs("div",{children:[jsx("h3",{className:"text-2xl mt-3 mb-2 font-semibold text-foreground",children:"Your Keys"}),jsx("div",{className:"space-y-2",children:A.map(k=>jsx(Rt,{nodeKey:k,selected:m===k.id,onSelect:()=>l(k.id)},k.id))})]}),w&&jsxs("div",{className:"rounded-xl border bg-muted/30 p-5 space-y-2 text-sm",children:[jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Key ID"}),jsx("code",{className:"text-xs text-foreground",children:w.id})]}),jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Originating Stack"}),jsx("span",{className:"text-foreground",children:r.stackName||"Unknown"})]}),jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Tokens (remaining / total)"}),jsxs("span",{className:"text-foreground",children:[T(w.tokenBalance)," / ",T(w.maxTokens)]})]}),w.paperWork&&jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Paper earned"}),jsx("span",{className:"text-foreground",children:w.paperWork})]}),jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Created"}),jsx("span",{className:"text-foreground",children:F(w.createdAt)})]})]}),jsxs("div",{children:[jsx("label",{htmlFor:"listing-price",className:"mb-2 block text-sm sm:text-lg font-semibold text-foreground",children:"Listing Price (USD)"}),jsxs("div",{className:"relative",children:[jsx("span",{className:"absolute left-4 top-1/2 -translate-y-1/2 text-2xl font-bold text-muted-foreground",children:"$"}),jsx("input",{id:"listing-price",type:"text",inputMode:"numeric",value:o,onChange:k=>{let W=k.target.value.replace(/[^0-9]/g,""),$=parseInt(W,10);c(isNaN($)?"":$.toLocaleString("en-US"));},placeholder:"0",className:"w-full rounded-xl border bg-background py-5 pl-10 pr-4 text-3xl font-bold text-foreground placeholder:text-muted-foreground/30 focus:outline-none focus:ring-2 focus:ring-foreground/20"})]})]}),jsxs("label",{className:"flex items-start gap-3 cursor-pointer",children:[jsx("input",{type:"checkbox",checked:N,onChange:k=>P(k.target.checked),className:"sr-only"}),jsx("div",{"aria-hidden":"true",className:f("mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded border-2 transition-colors",N?"border-foreground bg-foreground":"border-muted-foreground/40"),children:N&&jsx(Check,{className:"h-3 w-3 text-background"})}),jsxs("span",{className:"text-xs text-muted-foreground leading-relaxed",children:["I agree to list this key on the Global Open AI Network marketplace. The key will be deactivated upon sale and transferred to the buyer. Listing fees may apply."," ",jsx("a",{href:r.termsUrl||"/terms",className:"text-foreground underline",children:"Terms"})]})]}),p&&jsx("p",{className:"text-sm text-red-500",children:p}),jsxs("button",{onClick:j,disabled:!L,className:f("flex w-full items-center justify-center gap-2 rounded-xl py-4 text-sm font-semibold transition-colors",L?"bg-foreground text-background hover:bg-foreground/90":"bg-muted text-muted-foreground cursor-not-allowed"),children:[jsx(ExternalLink,{className:"h-4 w-4"}),n?"Listing...":"List on Marketplace"]})]})}var Lt=[{id:"buy",label:"Buy"},{id:"use",label:"Use"},{id:"sell",label:"Sell"}];function Tt({active:e,onChange:t}){return jsx("div",{role:"tablist","aria-label":"Key actions",className:"flex gap-1 rounded-2xl bg-muted/50 p-1.5",children:Lt.map(({id:r,label:s})=>jsx("button",{role:"tab","aria-selected":e===r,"aria-controls":`panel-${r}`,id:`tab-${r}`,onClick:()=>t(r),className:f("flex flex-1 items-center justify-center gap-2.5 rounded-xl py-3.5 text-sm font-medium transition-all",e===r?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:jsx("span",{className:"inline",children:s})},r))})}function Et({defaultTab:e="buy",className:t,style:r}){let[s,d]=useState(e);return jsxs("div",{className:f("flex flex-col",t),style:r,children:[jsx("div",{className:"sticky top-0 z-10 bg-background/80 px-5 pb-3 pt-2 sm:pt-5 backdrop-blur-sm sm:px-10 md:px-16 lg:px-20",children:jsx("div",{className:"mx-auto max-w-xl",children:jsx(Tt,{active:s,onChange:d})})}),jsx("div",{className:"flex flex-1 flex-col px-5 pb-8 sm:px-10 md:px-16 md:pb-12 lg:px-20",children:jsx("div",{className:"mx-auto w-full max-w-xl flex-1",children:jsxs("div",{role:"tabpanel",id:`panel-${s}`,"aria-labelledby":`tab-${s}`,children:[s==="buy"&&jsx(ce,{className:"flex-1"}),s==="use"&&jsx(de,{className:"flex-1"}),s==="sell"&&jsx(pe,{className:"flex-1"})]})})})]})}function It({apiBaseUrl:e,stackId:t,stackName:r,paymentMethods:s,merchantWallet:d,stripePublicKey:u,theme:g,maxQuantity:a,keyImage:n,keyImageClass:i,aispImage:p,termsUrl:m,onMintSuccess:l,onMintError:o,onPaymentStart:c,onPaymentComplete:N,onListingCreated:P,defaultTab:w,className:B,style:L}){return jsx(te,{config:{apiBaseUrl:e,stackId:t,stackName:r,paymentMethods:s,merchantWallet:d,stripePublicKey:u,theme:g,maxQuantity:a,keyImage:n,keyImageClass:i,aispImage:p,termsUrl:m},callbacks:{onMintSuccess:l,onMintError:o,onPaymentStart:c,onPaymentComplete:N,onListingCreated:P},children:jsx(Et,{defaultTab:w,className:B,style:L})})}function $e(e){let{config:t}=v(),[r,s]=useState([]),[d,u]=useState(false),[g,a]=useState(null),n=useRef(true),i=t.apiBaseUrl,p=useCallback(async()=>{if(e)try{u(!0),a(null);let m=await fetch(`${i}/api/keys/${e}/ledger`);if(!m.ok){let o=`Failed to fetch ledger (${m.status})`;try{let c=await m.json();c.error&&(o=c.error);}catch{}throw new Error(o)}let l=await m.json();n.current&&s(Array.isArray(l)?l:l.entries??[]);}catch(m){n.current&&a(m instanceof Error?m.message:"Failed to fetch ledger");}finally{n.current&&u(false);}},[i,e]);return useEffect(()=>(n.current=true,p(),()=>{n.current=false;}),[p]),{entries:r,loading:d,error:g,refresh:p}}var xe=20;function ye({nodeKey:e,className:t,style:r}){let[s,d]=useState(false),[u,g]=useState(false),a=useRef(null),{entries:n,loading:i}=$e(s?e.id:null);useEffect(()=>()=>{a.current&&clearTimeout(a.current);},[]);let p=useCallback(()=>{e.key&&(navigator.clipboard.writeText(e.key),g(true),a.current&&clearTimeout(a.current),a.current=setTimeout(()=>g(false),2e3));},[e.key]),m=e.status==="active"?"text-green-500":e.status==="expired"?"text-red-500":"text-yellow-500",l=n.slice(0,xe);return jsxs("div",{className:f("rounded-lg border bg-background",t),style:r,children:[jsxs("div",{className:"p-4",children:[jsxs("div",{className:"mb-3 flex items-center justify-between",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("button",{onClick:()=>d(!s),"aria-expanded":s,"aria-label":s?"Collapse ledger":"Expand ledger",className:"text-muted-foreground hover:text-foreground",children:s?jsx(ChevronDown,{className:"h-4 w-4"}):jsx(ChevronRight,{className:"h-4 w-4"})}),jsx("span",{className:"text-sm font-medium text-foreground",children:e.label||`Key ${e.id.slice(0,8)}`})]}),jsx("span",{className:f("text-xs font-medium capitalize",m),children:e.status})]}),e.key&&jsxs("div",{className:"mb-3 flex items-center gap-2",children:[jsx("code",{className:"flex-1 truncate rounded bg-muted px-2 py-1 text-xs text-muted-foreground",children:e.key}),jsx("button",{onClick:p,"aria-label":"Copy key to clipboard",className:"shrink-0 rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground",children:u?jsx(Check,{className:"h-3.5 w-3.5 text-green-500"}):jsx(Copy,{className:"h-3.5 w-3.5"})})]}),jsx(z,{current:e.tokenBalance,max:e.maxTokens}),jsxs("div",{className:"mt-2 flex items-center justify-between text-xs text-muted-foreground",children:[jsxs("span",{children:["Created ",F(e.createdAt)]}),e.expiresAt&&jsxs("span",{children:["Expires ",F(e.expiresAt)]})]})]}),s&&jsxs("div",{className:"border-t px-4 py-3",children:[jsx("h4",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Ledger"}),i?jsx("p",{className:"text-xs text-muted-foreground",children:"Loading..."}):l.length===0?jsx("p",{className:"text-xs text-muted-foreground",children:"No ledger entries."}):jsxs("div",{className:"space-y-1.5",children:[l.map(o=>jsxs("div",{className:"flex items-center justify-between text-xs",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsxs("span",{className:f("font-medium",o.type==="credit"||o.type==="reward"?"text-green-500":"text-red-500"),children:[o.type==="credit"||o.type==="reward"?"+":"-",T(Math.abs(o.amount))]}),jsx("span",{className:"text-muted-foreground",children:o.description})]}),jsx("span",{className:"text-muted-foreground",children:F(o.createdAt)})]},o.id)),n.length>xe&&jsxs("p",{className:"pt-1 text-xs text-muted-foreground",children:["Showing ",xe," of ",n.length," entries"]})]})]})]})}var qt=[{id:"buy",label:"Buy"},{id:"use",label:"Use"},{id:"sell",label:"Sell"}];function X({baseHref:e}){return jsx("div",{className:"flex gap-1 rounded-2xl bg-muted/50 p-1.5 mb-6",children:qt.map(({id:t,label:r})=>jsx("a",{href:`${e}?tab=${t}`,className:"flex flex-1 items-center justify-center gap-2.5 rounded-xl py-3.5 text-sm font-medium text-muted-foreground hover:text-foreground transition-all",children:r},t))})}function Vt({getKeyHref:e="/keys/get",showTabs:t=true,className:r,style:s}){let{keys:d,totalBalance:u,loading:g,error:a,refresh:n}=J();return g?jsxs("div",{className:f("space-y-4",r),style:s,children:[t&&e&&jsx(X,{baseHref:e}),jsx(Y,{count:3})]}):a?jsxs("div",{className:f("space-y-4",r),style:s,children:[t&&e&&jsx(X,{baseHref:e}),jsxs("div",{className:"flex flex-col items-center justify-center gap-4 py-12",children:[jsxs("div",{className:"rounded-xl border border-red-500/20 bg-red-500/5 px-6 py-5 text-center max-w-sm",children:[jsx("p",{className:"text-sm font-medium text-foreground",children:"Unable to load your keys"}),jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:a})]}),jsx("button",{onClick:()=>n(),className:"text-sm text-muted-foreground hover:text-foreground transition-colors",children:"Try again"})]})]}):d.length===0?jsxs("div",{className:f("space-y-4",r),style:s,children:[t&&e&&jsx(X,{baseHref:e}),jsxs("div",{className:"flex flex-col items-center justify-center gap-4 rounded-lg border border-dashed py-12",children:[jsx(KeyRound,{className:"h-10 w-10 text-muted-foreground"}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-sm font-medium text-foreground",children:"No keys yet"}),jsx("p",{className:"text-xs text-muted-foreground",children:"Get your first node key to start earning."})]}),e&&jsx("a",{href:e,className:"rounded-lg bg-foreground px-4 py-2 text-sm font-medium text-background transition-colors hover:bg-foreground/90",children:"Get a Key"})]})]}):jsxs("div",{className:f("space-y-4",r),style:s,children:[t&&e&&jsx(X,{baseHref:e}),jsxs("div",{className:"flex items-center justify-between",children:[jsxs("p",{className:"text-sm text-muted-foreground",children:[d.length," key",d.length!==1?"s":""," \xB7 Total balance: ",T(u)]}),e&&jsx("a",{href:e,className:"rounded-md bg-foreground px-3 py-1.5 text-xs font-medium text-background transition-colors hover:bg-foreground/90",children:"Get a Key"})]}),d.map(i=>jsx(ye,{nodeKey:i},i.id))]})}
2
- export{It as BuyKeyWidget,ce as BuyPanel,z as KeyBalanceBar,ye as KeyCard,Vt as KeyList,te as KeyUtilsProvider,ie as MintSuccess,pe as SellPanel,ae as SolanaPayButton,de as UsePanel,v as useKeyUtilsContext};
1
+ import yt,{createContext,useContext,useMemo,useState,useCallback,useRef,useEffect}from'react';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {clsx}from'clsx';import {twMerge}from'tailwind-merge';import {Loader2,CheckCircle,Check,Copy,CreditCard,Wallet,Download,ExternalLink,AlertTriangle,Send,ChevronDown,ChevronRight,KeyRound,Minus,Plus,ChevronUp}from'lucide-react';var Ce=createContext(null);function C(){let e=useContext(Ce);if(!e)throw new Error("useKeyUtilsContext must be used within a KeyUtilsProvider");return e}function oe({config:e,callbacks:t={},children:r}){typeof e.apiBaseUrl!="string"&&console.error("[KeyUtils] apiBaseUrl must be a string");let s=useMemo(()=>({config:e,callbacks:t}),[e,t]);return jsx(Ce.Provider,{value:s,children:r})}function u(...e){return twMerge(clsx(e))}function I(e){return e==null?"0":e>=1e9?`${(e/1e9).toFixed(1)}B`:e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:e.toLocaleString()}function Se(e,t){return t<=0?0:Math.min(100,Math.round(e/t*100))}function Ke(e){return e>=70?"bg-green-500":e>=30?"bg-yellow-500":"bg-red-500"}function z(e){let t=typeof e=="string"&&/^\d+$/.test(e)?Number(e):e,r=new Date(t);return isNaN(r.getTime())?String(e):r.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}function Re(){if(typeof navigator>"u")return "mac";let e=navigator.userAgent.toLowerCase();return /iphone|ipad|ipod/.test(e)?"ios":/android/.test(e)?"android":/win/.test(e)?"windows":/linux/.test(e)?"linux":"mac"}function Ue(){let{config:e}=C(),[t,r]=useState(null),[s,g]=useState(true),[m,f]=useState(null),a=useRef(true),n=useRef(e.apiBaseUrl);n.current=e.apiBaseUrl;let c=async()=>{try{a.current&&(g(!0),f(null));let d=await fetch(`${n.current}/api/keys/pricing`);if(!d.ok){let i=`Pricing unavailable (${d.status})`;try{let o=await d.json();o.error&&(i=o.error);}catch{}throw new Error(i)}let p=await d.json();a.current&&r(p);}catch(d){a.current&&f(d instanceof Error?d.message:"Failed to fetch pricing");}finally{a.current&&g(false);}};return useEffect(()=>{a.current=true,c();let d=setInterval(c,6e4);return ()=>{a.current=false,clearInterval(d);}},[]),{pricing:t,loading:s,error:m,refresh:c}}function Be(){let{config:e,callbacks:t}=C(),[r,s]=useState(false),[g,m]=useState(null),[f,a]=useState(null);return {mint:useCallback(async(c,d,p=1)=>{try{s(!0),a(null),t.onPaymentComplete?.(c,d);let i=await fetch(`${e.apiBaseUrl}/api/keys/mint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paymentMethod:c,paymentRef:d,quantity:p})});if(!i.ok){let w="Key generation failed";try{let P=await i.json();P.error&&(w=P.error);}catch{}throw new Error(w)}let o=await i.json(),l=o.keys?.[0]||o,b={success:!0,key:{id:l.keyId||l.id||"",key:l.key||"",userId:l.userId||"",status:"active",tokenBalance:l.tokenBalance??l.currentTokenBalance??0,maxTokens:l.initialTokenBalance??l.tokenBalance??0,createdAt:String(l.createdAt||Date.now())},transactionId:d};return m(b),t.onMintSuccess?.(b),b}catch(i){let o=i instanceof Error?i:new Error("Key generation failed");return a(o.message),t.onMintError?.(o),{success:false,error:o.message}}finally{s(false);}},[e.apiBaseUrl,t]),minting:r,result:g,error:f}}function Le(){let{config:e}=C(),[t,r]=useState(false),[s,g]=useState(null),m=useRef(true);return {createSession:useCallback(async(a,n)=>{try{r(!0),g(null);let c=await fetch(`${e.apiBaseUrl}/api/keys/stripe-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({priceCents:a,quantity:n,stackId:e.stackId,referrerUrl:window.location.href})});if(!c.ok){let p=`Checkout failed (${c.status})`;try{let i=await c.json();i.error&&(p=i.error);}catch{}throw new Error(p)}let{url:d}=await c.json();if(d){try{sessionStorage.setItem("keyutils_stripe_pending","1");}catch{}window.location.href=d;}else throw new Error("No checkout URL returned")}catch(c){if(m.current){let d=c instanceof Error?c.message:"Checkout failed";g(d),r(false);}}},[e.apiBaseUrl,e.stackId]),loading:t,error:s}}var je=/^[1-9A-HJ-NP-Za-km-z]{32,44}$/;function de({amountSol:e,onSuccess:t,onError:r,disabled:s,className:g,style:m}){let{config:f}=C(),[a,n]=useState(false),[c,d]=useState(null),p=!!(f.merchantWallet&&je.test(f.merchantWallet)),i=useCallback(async()=>{if(p)try{n(!0),d(null);let{Connection:o,PublicKey:l,Transaction:b,SystemProgram:w,LAMPORTS_PER_SOL:P}=await import('@solana/web3.js'),T=typeof window<"u"?window.solana:void 0;if(!T||typeof T!="object"||!T.isPhantom)throw new Error("Phantom wallet not found. Please install Phantom.");let j=T,k;try{k=new l(f.merchantWallet);}catch{throw new Error("Invalid merchant wallet address.")}let q=await j.connect(),_=new l(q.publicKey.toString()),K=new o(f.solanaRpcUrl||"https://api.mainnet-beta.solana.com"),{blockhash:F}=await K.getLatestBlockhash(),W=BigInt(Math.floor(e*1e9)),Z=f.protocolTreasuryWallet,B=f.protocolFeeBps??500,D=new b({recentBlockhash:F,feePayer:_});if(Z&&je.test(Z)&&B>0){let X=W*BigInt(B)/10000n,Je=W-X,Ze=new l(Z);D.add(w.transfer({fromPubkey:_,toPubkey:k,lamports:Number(Je)}),w.transfer({fromPubkey:_,toPubkey:Ze,lamports:Number(X)}));}else D.add(w.transfer({fromPubkey:_,toPubkey:k,lamports:Number(W)}));let{signature:re}=await j.signAndSendTransaction(D);t(re);}catch(o){let l=o instanceof Error?o:new Error("Payment failed");d(l.message),r?.(l);}finally{n(false);}},[e,f.merchantWallet,p,t,r]);return jsxs("div",{children:[jsx("button",{onClick:i,disabled:s||a||!p,"aria-label":`Pay ${e.toFixed(4)} SOL`,className:u("flex w-full items-center justify-center gap-2 rounded-lg bg-purple-600 px-4 py-6 font-medium text-white transition-colors hover:bg-purple-700 disabled:opacity-50 disabled:cursor-not-allowed",g),style:m,children:a?jsxs(Fragment,{children:[jsx(Loader2,{className:"h-4 w-4 animate-spin"}),"Processing..."]}):jsxs(Fragment,{children:["Pay ",e.toFixed(4)," SOL"]})}),c&&jsx("p",{className:"mt-2 text-center text-xs text-red-500",children:c})]})}function ue({result:e,className:t,style:r}){let[s,g]=useState(false),m=useRef(null);useEffect(()=>()=>{m.current&&clearTimeout(m.current);},[]);let f=useCallback(()=>{e.key?.key&&(navigator.clipboard.writeText(e.key.key),g(true),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>g(false),2e3));},[e.key?.key]);return !e.success||!e.key?null:jsxs("div",{className:u("rounded-lg border border-green-500/20 bg-green-500/10 p-6 text-center",t),style:r,children:[jsx(CheckCircle,{className:"mx-auto mb-3 h-12 w-12 text-green-500"}),jsx("h3",{className:"mb-2 text-lg font-semibold text-foreground",children:"Key Generated!"}),jsx("p",{className:"mb-4 text-sm text-muted-foreground",children:"Your node key has been successfully generated."}),jsxs("div",{className:"mx-auto flex max-w-md items-center gap-2 rounded-md border bg-background p-3",children:[jsx("code",{className:"flex-1 truncate text-xs text-foreground",children:e.key.key}),jsx("button",{onClick:f,"aria-label":"Copy key to clipboard",className:"shrink-0 rounded-md p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:s?jsx(Check,{className:"h-4 w-4 text-green-500"}):jsx(Copy,{className:"h-4 w-4"})})]})]})}function A({className:e}){return jsx("div",{className:u("animate-pulse rounded-xl bg-muted",e)})}function me(){return jsxs("div",{className:"space-y-6",children:[jsxs("div",{className:"px-6 py-10 flex flex-col items-center gap-3",children:[jsx(A,{className:"h-14 w-48"}),jsx(A,{className:"h-5 w-64"})]}),jsx(A,{className:"h-[72px] w-full rounded-2xl"}),jsx(A,{className:"h-[68px] w-full rounded-2xl"}),jsx(A,{className:"h-[60px] w-full rounded-2xl"})]})}function Y({count:e=3}){return jsx("div",{className:"space-y-3",children:Array.from({length:e}).map((t,r)=>jsxs("div",{className:"rounded-xl border p-4 space-y-3",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx(A,{className:"h-4 w-32"}),jsx(A,{className:"h-4 w-16"})]}),jsx(A,{className:"h-2 w-full rounded-full"}),jsxs("div",{className:"flex justify-between",children:[jsx(A,{className:"h-3 w-24"}),jsx(A,{className:"h-3 w-20"})]})]},r))})}function Ct({quantity:e,max:t,onChange:r}){return jsxs("div",{className:"flex items-center justify-between rounded-2xl bg-muted/20 px-6 py-6",children:[jsx("span",{className:"text-sm font-medium text-foreground",children:"Quantity"}),jsxs("div",{className:"flex items-center gap-0 rounded-xl bg-background",children:[jsx("button",{onClick:()=>r(Math.max(1,e-1)),disabled:e<=1,"aria-label":"Decrease quantity",className:"flex h-12 w-12 items-center justify-center rounded-l-xl text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-30",children:jsx(Minus,{className:"h-5 w-5"})}),jsx("span",{className:"flex h-12 w-14 items-center justify-center border-x text-xl font-bold text-foreground","aria-live":"polite",children:e}),jsx("button",{onClick:()=>r(Math.min(t,e+1)),disabled:e>=t,"aria-label":"Increase quantity",className:"flex h-12 w-12 items-center justify-center rounded-r-xl text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:opacity-30",children:jsx(Plus,{className:"h-5 w-5"})})]})]})}function $e({pricing:e,quantity:t}){let[r,s]=useState(false),g=e.priceUsd*t;return jsxs("div",{className:"rounded-2xl border bg-background",children:[jsxs("button",{onClick:()=>s(!r),"aria-expanded":r,className:"flex w-full items-center justify-between px-6 py-6 text-left",children:[jsxs("span",{className:"text-foreground",children:[jsxs("span",{className:"text-xl font-bold",children:["$",g.toFixed(2)]})," ",jsx("span",{className:"text-sm text-muted-foreground",children:"total fees included"})]}),r?jsx(ChevronUp,{className:"h-5 w-5 text-muted-foreground"}):jsx(ChevronDown,{className:"h-5 w-5 text-muted-foreground"})]}),r&&jsxs("div",{className:"border-t px-6 pb-8 pt-4 space-y-3 text-sm",children:[jsxs("div",{className:"flex justify-between",children:[jsxs("span",{className:"text-muted-foreground",children:["Node Key \xD7 ",t]}),jsxs("span",{className:"text-foreground",children:["$",(e.priceUsd*t).toFixed(2)]})]}),jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Keys sold"}),jsx("span",{className:"text-foreground",children:e.keysSold})]}),e.daysUntilHalving>0&&jsxs("div",{className:"flex justify-between text-muted-foreground",children:[jsx("span",{children:"Next refresh"}),jsxs("span",{children:[e.daysUntilHalving," day",e.daysUntilHalving!==1?"s":""]})]}),jsxs("div",{className:"flex justify-between border-t pt-3 font-semibold",children:[jsx("span",{className:"text-foreground",children:"Total"}),jsxs("span",{className:"text-foreground",children:["$",g.toFixed(2)]})]})]})]})}function fe({className:e,style:t}){let{config:r}=C(),{pricing:s,loading:g,error:m,refresh:f}=Ue(),{mint:a,minting:n,result:c,error:d}=Be(),{createSession:p,loading:i,error:o}=Le(),[l,b]=useState(1),[w,P]=useState(r.paymentMethods?.includes("stripe")?"stripe":"solana"),[T,j]=useState(0),[k,q]=useState(false),_=yt.useRef(l);_.current=l;let K=Math.max(1,r.maxQuantity||5),F=[...r.paymentMethods||["solana"]].sort((B,D)=>B==="stripe"?-1:D==="stripe"?1:0);if(useEffect(()=>{if(typeof window>"u")return;let D=new URLSearchParams(window.location.search).get("session_id");if(!D){try{sessionStorage.removeItem("keyutils_stripe_pending");}catch{}return}if(/^cs_(test|live)_/.test(D)&&!k&&!c?.success){let re=false;try{re=sessionStorage.getItem("keyutils_stripe_pending")==="1";}catch{}if(!re)return;try{sessionStorage.removeItem("keyutils_stripe_pending");}catch{}q(true);let X=new URL(window.location.href);X.searchParams.delete("session_id"),window.history.replaceState({},"",X.toString()),a("stripe",D,_.current);}},[k,c,a]),c?.success)return jsx("div",{className:u("flex flex-col items-center justify-center",e),style:t,children:jsx(ue,{result:c})});if(k||n)return jsx("div",{className:u("flex flex-col",e),style:t,children:jsx(me,{})});if(g)return jsx("div",{className:u("flex flex-col",e),style:t,children:jsx(me,{})});if(m||!s)return jsxs("div",{className:u("flex flex-col items-center justify-center gap-4 py-24",e),style:t,children:[jsxs("div",{className:"rounded-xl border border-red-500/20 bg-red-500/5 px-6 py-5 text-center max-w-sm",children:[jsx("p",{className:"text-sm font-medium text-foreground",children:"Unable to load pricing"}),jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:m||"Please check your connection and try again."})]}),jsx("button",{onClick:()=>f(),className:"text-sm text-muted-foreground hover:text-foreground transition-colors",children:"Try again"})]});let W=async B=>{j(2),await a(w,B,l);},Z=()=>{p(s.priceCents,l);};return jsx("div",{className:u("flex flex-col",e),style:t,children:jsxs("div",{className:"space-y-6",children:[T===0&&jsxs(Fragment,{children:[r.keyImage&&jsx("img",{src:r.keyImage,alt:"Node Key",className:r.keyImageClass||"w-1/2 mx-auto"}),jsxs("div",{className:"px-6 py-10 text-center",children:[jsxs("p",{className:"text-5xl font-bold tracking-tight text-foreground md:text-6xl",children:["$",s.priceUsd.toFixed(2)]}),jsxs("p",{className:"mt-2 text-base text-muted-foreground",children:["per key \xB7 ",s.tokenAllocationFormatted||I(s.tokenAllocation)," tokens included"]})]}),jsx(Ct,{quantity:l,max:K,onChange:b}),jsx($e,{pricing:s,quantity:l}),jsx("button",{onClick:()=>j(1),className:"w-full rounded-2xl bg-foreground py-6 text-center text-base font-semibold text-background transition-colors hover:bg-foreground/90",children:"Continue to Payment"})]}),T===1&&jsxs(Fragment,{children:[F.length>1&&jsx("div",{role:"tablist",className:"flex gap-1 rounded-2xl bg-muted/50 p-1.5",children:F.map(B=>jsxs("button",{role:"tab","aria-selected":w===B,onClick:()=>P(B),className:u("flex flex-1 items-center justify-center gap-2.5 rounded-xl py-4 text-sm font-medium transition-colors",w===B?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[B==="stripe"?jsx(CreditCard,{className:"h-5 w-5"}):jsx(Wallet,{className:"h-5 w-5"}),B==="stripe"?"Credit Card":"Crypto"]},B))}),jsx($e,{pricing:s,quantity:l}),w==="stripe"?jsxs(Fragment,{children:[jsx("button",{onClick:Z,disabled:i,className:"flex w-full items-center justify-center gap-2 rounded-2xl bg-foreground py-6 text-base font-semibold text-background transition-colors hover:bg-foreground/90 disabled:opacity-50",children:i?jsxs(Fragment,{children:[jsx(Loader2,{className:"h-5 w-5 animate-spin"}),"Redirecting to Stripe..."]}):jsxs(Fragment,{children:[jsx(CreditCard,{className:"h-5 w-5"}),"Pay with Card"]})}),o&&jsx("p",{className:"text-center text-sm text-red-500",children:o})]}):w==="solana"?jsx(de,{amountSol:s.priceSol??0,onSuccess:W,className:"rounded-2xl py-5 text-base"}):null,d&&jsx("p",{className:"text-center text-sm text-red-500",children:d}),jsx("button",{onClick:()=>j(0),className:"w-full py-3 text-center text-sm text-muted-foreground hover:text-foreground transition-colors",children:"\u2190 Back"})]})]})})}var Tt={ios:"iOS",android:"Android",windows:"Windows",mac:"macOS",linux:"Linux"},Ut=["mac","windows","linux","ios","android"];function pe({downloads:e,className:t,style:r}){let{config:s}=C(),g=useMemo(()=>Re(),[]),m=e||Ut.map(n=>({platform:n,label:Tt[n],url:"#",compatible:n===g})),f=m.find(n=>n.compatible)||m[0],a=m.filter(n=>n.platform!==f.platform);return jsxs("div",{className:u("space-y-8",t),style:r,children:[jsxs("div",{className:"flex flex-col items-center gap-6 pt-4 mt-4",children:[s.aispImage&&jsx("img",{src:s.aispImage,alt:"aiSP",className:"w-full sm:w-1/2 mx-auto px-4 sm:px-0"}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-lg sm:text-2xl font-medium text-foreground",children:"Download the AI Service Provider App"}),jsx("p",{className:"mt-1 text-sm sm:text-base text-muted-foreground",children:"Load your keys and run your node."})]}),jsxs("a",{href:f.url,className:"inline-flex items-center gap-3 rounded-full px-10 py-4 text-lg font-semibold text-white transition-colors hover:opacity-90",style:{backgroundColor:"#0900f4"},children:[jsx(Download,{className:"h-5 w-5"}),"Get aiSP for ",f.label]})]}),jsxs("p",{className:"text-center text-sm text-muted-foreground",children:["aiSP is also available on"," ",a.map((n,c)=>jsxs(yt.Fragment,{children:[c>0&&(c===a.length-1?" and ":", "),jsx("a",{href:n.url,className:"font-medium underline transition-colors hover:text-foreground",style:{color:"#066bff"},children:n.label})]},n.platform)),"."]}),jsxs("div",{className:"flex flex-col items-center gap-2 mt-12",children:[jsxs("p",{className:"text-center text-xs text-muted-foreground flex justify-center gap-0.5 flex-wrap",children:["Source code is available on",jsx("a",{href:"https://github.com/stack-net",target:"_blank",rel:"noopener noreferrer",className:"text-foreground underline hover:text-foreground/80 color-[#0900f4]",children:"Github"})]}),jsxs("p",{className:"text-center text-xs text-muted-foreground flex justify-center gap-0.5 flex-wrap",children:["By downloading, you agree to the",jsx("a",{href:s.termsUrl||"/terms",className:"text-foreground underline hover:text-foreground/80",children:"Open Source Applications Terms"})]})]})]})}function Et(e){return {id:e.id||"",keyIndex:e.keyIndex??e.key_index??null,key:e.key||e.keyPrefix||"",userId:e.userId||e.user_id||"",status:e.status||"active",tokenBalance:e.tokenBalance??e.currentTokenBalance??e.current_token_balance??0,maxTokens:e.maxTokens??e.initialTokenBalance??e.initial_token_balance??0,createdAt:String(e.createdAt??e.created_at??""),expiresAt:e.expiresAt,label:e.label||e.keyPrefix||e.key_prefix||void 0,paperWork:e.paperWork||e.paper_work||void 0,stackId:e.stackId,stackName:e.stackName}}function J(){let{config:e}=C(),[t,r]=useState([]),[s,g]=useState(true),[m,f]=useState(null),a=useRef(true),n=e.apiBaseUrl,c=useCallback(async()=>{try{g(!0),f(null);let p=await fetch(`${n}/api/keys`);if(!p.ok){let l=`Failed to fetch keys (${p.status})`;try{let b=await p.json();b.error&&(l=b.error);}catch{}throw new Error(l)}let i=await p.json(),o=Array.isArray(i)?i:i.keys??[];a.current&&r(o.map(Et));}catch(p){a.current&&f(p instanceof Error?p.message:"Failed to fetch keys");}finally{a.current&&g(false);}},[n]);useEffect(()=>(a.current=true,c(),()=>{a.current=false;}),[c]);let d=t.reduce((p,i)=>p+i.tokenBalance,0);return {keys:t,totalBalance:d,loading:s,error:m,refresh:c}}function Oe(){let{config:e,callbacks:t}=C(),[r,s]=useState(false),[g,m]=useState(null),[f,a]=useState(null),n=useRef(true),c=useCallback(async(p,i)=>{try{s(!0),a(null);let o=await fetch(`${e.apiBaseUrl}/api/keys/${p}/list`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({askPriceCents:i,stackId:e.stackId,stackName:e.stackName})});if(!o.ok){let b=`Listing failed (${o.status})`;try{let w=await o.json();w.error&&(b=w.error);}catch{}throw new Error(b)}let l=await o.json();return n.current&&(m(l),t.onListingCreated?.(l)),l}catch(o){let l=o instanceof Error?o.message:"Listing failed";return n.current&&a(l),null}finally{n.current&&s(false);}},[e.apiBaseUrl,e.stackId,e.stackName,t]),d=useCallback(async p=>{try{s(!0),a(null);let i=await fetch(`${e.apiBaseUrl}/api/keys/${p}/list`,{method:"DELETE"});if(!i.ok){let o=`Delist failed (${i.status})`;try{let l=await i.json();l.error&&(o=l.error);}catch{}throw new Error(o)}return n.current&&m(null),!0}catch(i){let o=i instanceof Error?i.message:"Delist failed";return n.current&&a(o),false}finally{n.current&&s(false);}},[e.apiBaseUrl]);return {listKey:c,delistKey:d,listing:r,result:g,error:f}}function V({current:e,max:t,className:r,style:s,showLabel:g=true}){let m=Se(e,t),f=Ke(m);return jsxs("div",{className:u("w-full",r),style:s,children:[g&&jsxs("div",{className:"mb-1 flex items-center justify-between text-xs text-muted-foreground",children:[jsxs("span",{children:[I(e)," / ",I(t)]}),jsxs("span",{children:[m,"%"]})]}),jsx("div",{className:"h-2 w-full overflow-hidden rounded-full bg-muted",children:jsx("div",{className:u("h-full rounded-full transition-all duration-500",f),style:{width:`${m}%`}})})]})}function At({nodeKey:e,selected:t,onSelect:r}){return jsxs("button",{onClick:r,className:u("flex w-full items-start gap-3 rounded-xl border p-4 text-left transition-all",t?"border-foreground/30 bg-foreground/5 ring-1 ring-foreground/10":"border-border hover:border-foreground/20"),children:[jsx("div",{className:u("mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-2 transition-colors",t?"border-foreground bg-foreground":"border-muted-foreground/40"),children:t&&jsx(Check,{className:"h-3 w-3 text-background"})}),jsxs("div",{className:"min-w-0 flex-1",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsxs("span",{className:"text-sm font-medium text-foreground",children:[e.keyIndex?`#${e.keyIndex} `:"",e.label||e.id.slice(0,16)]}),jsx("span",{className:u("text-xs font-medium capitalize",e.status==="active"?"text-green-500":"text-muted-foreground"),children:e.status})]}),jsx(V,{current:e.tokenBalance,max:e.maxTokens,className:"mt-2"})]})]})}function be({className:e,style:t}){let{config:r}=C(),{keys:s,loading:g,error:m,refresh:f}=J(),{listKey:a,listing:n,result:c,error:d}=Oe(),[p,i]=useState(null),[o,l]=useState(""),[b,w]=useState(false),P=s.find(K=>K.id===p),T=parseInt(o.replace(/[^0-9]/g,""),10)||0,j=T>0&&Number.isFinite(T),k=!!P&&j&&b&&!n,q=async()=>{if(!k||!P)return;let K=T*100;await a(P.id,K)&&f();};if(c)return jsxs("div",{className:u("flex flex-col items-center gap-4 rounded-xl bg-green-500/10 py-12",e),style:t,children:[jsx(CheckCircle,{className:"h-12 w-12 text-green-500"}),jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Key Listed!"}),jsx("p",{className:"text-sm text-muted-foreground",children:"Your key is now on the Global Open AI Network marketplace."}),jsxs("p",{className:"text-xs text-muted-foreground",children:["Listing ID: ",jsx("code",{children:c.listingId})]}),jsxs("a",{href:`https://market.stacknet.org/keys/${c.keyId}`,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 rounded-xl bg-foreground px-6 py-3 text-sm font-semibold text-background transition-colors hover:bg-foreground/90",children:[jsx(ExternalLink,{className:"h-4 w-4"}),"View Listing"]})]});if(g)return jsxs("div",{className:u("space-y-5 px-1",e),style:t,children:[jsx("h3",{className:"text-2xl mt-3 mb-2 font-semibold text-foreground",children:"Your Keys"}),jsx(Y,{count:2})]});if(m)return jsxs("div",{className:u("flex flex-col items-center justify-center gap-4 py-16",e),style:t,children:[jsxs("div",{className:"rounded-xl border border-red-500/20 bg-red-500/5 px-6 py-5 text-center max-w-sm",children:[jsx("p",{className:"text-sm font-medium text-foreground",children:"Unable to load your keys"}),jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:m})]}),jsx("button",{onClick:()=>f(),className:"text-sm text-muted-foreground hover:text-foreground transition-colors",children:"Try again"})]});let _=s.filter(K=>K.status==="active");return _.length===0?jsxs("div",{className:u("flex flex-col items-center justify-center gap-3 rounded-xl border border-dashed py-16",e),style:t,children:[jsx(AlertTriangle,{className:"h-8 w-8 text-muted-foreground"}),jsx("p",{className:"text-sm text-muted-foreground",children:"No active keys to sell."})]}):jsxs("div",{className:u("space-y-5",e),style:t,children:[jsxs("div",{children:[jsx("h3",{className:"text-2xl mt-3 mb-2 font-semibold text-foreground",children:"Your Keys"}),jsx("div",{className:"space-y-2",children:_.map(K=>jsx(At,{nodeKey:K,selected:p===K.id,onSelect:()=>i(K.id)},K.id))})]}),P&&jsxs("div",{className:"rounded-xl border bg-muted/30 p-5 space-y-2 text-sm",children:[P.keyIndex&&jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Key #"}),jsxs("span",{className:"text-foreground font-semibold",children:["#",P.keyIndex]})]}),jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Key ID"}),jsx("code",{className:"text-xs text-foreground",children:P.id})]}),jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Originating Stack"}),jsx("span",{className:"text-foreground",children:r.stackName||"Unknown"})]}),jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Tokens (remaining / total)"}),jsxs("span",{className:"text-foreground",children:[I(P.tokenBalance)," / ",I(P.maxTokens)]})]}),P.paperWork&&jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Paper earned"}),jsx("span",{className:"text-foreground",children:P.paperWork})]}),jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Created"}),jsx("span",{className:"text-foreground",children:z(P.createdAt)})]})]}),jsxs("div",{children:[jsx("label",{htmlFor:"listing-price",className:"mb-2 block text-sm sm:text-lg font-semibold text-foreground",children:"Listing Price (USD)"}),jsxs("div",{className:"relative",children:[jsx("span",{className:"absolute left-4 top-1/2 -translate-y-1/2 text-2xl font-bold text-muted-foreground",children:"$"}),jsx("input",{id:"listing-price",type:"text",inputMode:"numeric",value:o,onChange:K=>{let F=K.target.value.replace(/[^0-9]/g,""),W=parseInt(F,10);l(isNaN(W)?"":W.toLocaleString("en-US"));},placeholder:"0",className:"w-full rounded-xl border bg-background py-6 pl-10 pr-4 text-3xl font-bold text-foreground placeholder:text-muted-foreground/30 focus:outline-none focus:ring-2 focus:ring-foreground/20"})]})]}),jsxs("div",{className:"flex items-start gap-3",children:[jsx("button",{type:"button",role:"checkbox","aria-checked":b,onClick:()=>w(!b),className:u("mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded border-2 transition-colors cursor-pointer",b?"border-foreground bg-foreground":"border-muted-foreground/40"),children:b&&jsx(Check,{className:"h-3 w-3 text-background"})}),jsxs("span",{className:"text-xs text-muted-foreground leading-relaxed",children:["I agree to list this key on the Global Open AI Network marketplace. The key will be deactivated upon sale and transferred to the buyer. Listing fees may apply."," ",jsx("a",{href:r.termsUrl||"/terms",className:"text-foreground underline",target:"_blank",rel:"noopener noreferrer",children:"Terms"})]})]}),d&&jsx("p",{className:"text-sm text-red-500",children:d}),jsxs("button",{onClick:q,disabled:!k,className:u("flex w-full items-center justify-center gap-2 rounded-xl py-4 text-sm font-semibold transition-colors",k?"bg-foreground text-background hover:bg-foreground/90":"bg-muted text-muted-foreground cursor-not-allowed"),children:[jsx(ExternalLink,{className:"h-4 w-4"}),n?"Listing...":"List on Marketplace"]})]})}function Qe(){let{config:e,callbacks:t}=C(),[r,s]=useState(false),[g,m]=useState(null),[f,a]=useState(null),n=useRef(true);return {transferKey:useCallback(async(d,p)=>{try{s(!0),a(null);let i=await fetch(`${e.apiBaseUrl}/api/keys/${d}/transfer`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recipientId:p})});if(!i.ok){let l=`Transfer failed (${i.status})`;try{let b=await i.json();b.error&&(l=b.error);}catch{}throw new Error(l)}let o=await i.json();return n.current&&(m(o),t.onTransferComplete?.(o)),o}catch(i){let o=i instanceof Error?i.message:"Transfer failed";return n.current&&a(o),null}finally{n.current&&s(false);}},[e.apiBaseUrl,t]),transferring:r,result:g,error:f}}function Qt({nodeKey:e,selected:t,onSelect:r}){return jsxs("button",{onClick:r,className:u("flex w-full items-start gap-3 rounded-xl border p-4 text-left transition-all",t?"border-foreground/30 bg-foreground/5 ring-1 ring-foreground/10":"border-border hover:border-foreground/20"),children:[jsx("div",{className:u("mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded-full border-2 transition-colors",t?"border-foreground bg-foreground":"border-muted-foreground/40"),children:t&&jsx(Check,{className:"h-3 w-3 text-background"})}),jsxs("div",{className:"min-w-0 flex-1",children:[jsxs("div",{className:"flex items-center justify-between",children:[jsxs("span",{className:"text-sm font-medium text-foreground",children:[e.keyIndex?`#${e.keyIndex} `:"",e.label||e.id.slice(0,16)]}),jsx("span",{className:"text-xs font-medium capitalize text-green-500",children:e.status})]}),jsx(V,{current:e.tokenBalance,max:e.maxTokens,className:"mt-2"})]})]})}function ve({className:e,style:t}){let{keys:r,loading:s}=J(),{transferKey:g,transferring:m,result:f,error:a}=Qe(),[n,c]=useState(null),[d,p]=useState(""),[i,o]=useState(false),l=r.filter(k=>k.status==="active"),b=l.find(k=>k.id===n),w=b&&d.trim()===b.userId,P=n&&d.trim().length>0&&i&&!w&&!m,T=async()=>{!n||!d.trim()||await g(n,d.trim());},j=()=>{c(null),p(""),o(false);};return f?jsxs("div",{className:u("flex flex-col items-center gap-4 py-8",e),style:t,children:[jsx(CheckCircle,{className:"h-12 w-12 text-green-500"}),jsxs("div",{className:"text-center",children:[jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Transfer Complete"}),jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Key transferred successfully"})]}),jsxs("div",{className:"w-full max-w-sm space-y-2 rounded-xl border border-border bg-muted/30 p-4 text-sm",children:[jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Key"}),jsxs("span",{className:"font-mono text-foreground",children:[f.keyId.slice(0,20),"..."]})]}),jsxs("div",{className:"flex justify-between",children:[jsx("span",{className:"text-muted-foreground",children:"Recipient"}),jsxs("span",{className:"font-mono text-foreground",children:[f.toUserId.slice(0,20),"..."]})]})]}),jsx("button",{onClick:j,className:"mt-2 rounded-lg border border-border px-4 py-2 text-sm font-medium text-foreground hover:bg-muted/50 transition-colors",children:"Transfer Another"})]}):jsxs("div",{className:u("space-y-5",e),style:t,children:[jsxs("div",{children:[jsx("h3",{className:"mb-3 text-sm font-medium text-foreground",children:"Select Key to Transfer"}),s?jsx(Y,{count:2}):l.length===0?jsx("p",{className:"text-sm text-muted-foreground",children:"No active keys available for transfer."}):jsx("div",{className:"space-y-2",children:l.map(k=>jsx(Qt,{nodeKey:k,selected:n===k.id,onSelect:()=>c(k.id)},k.id))})]}),n&&jsxs("div",{children:[jsx("label",{className:"mb-1.5 block text-sm font-medium text-foreground",children:"Recipient User ID"}),jsx("input",{type:"text",value:d,onChange:k=>{p(k.target.value),o(false);},placeholder:"Enter recipient's user ID or global ID",className:"w-full rounded-lg border border-border bg-background px-3 py-2.5 text-sm text-foreground placeholder:text-muted-foreground focus:border-foreground/30 focus:outline-none focus:ring-1 focus:ring-foreground/10"}),w&&jsx("p",{className:"mt-1.5 text-xs text-red-500",children:"Cannot transfer a key to yourself"})]}),b&&d.trim().length>0&&!w&&jsx("div",{className:"rounded-xl border border-amber-500/30 bg-amber-500/5 p-4",children:jsxs("div",{className:"flex items-start gap-3",children:[jsx(AlertTriangle,{className:"mt-0.5 h-5 w-5 shrink-0 text-amber-500"}),jsxs("div",{className:"space-y-3",children:[jsxs("div",{children:[jsx("p",{className:"text-sm font-medium text-foreground",children:"Confirm Transfer"}),jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["You are about to transfer key"," ",jsx("span",{className:"font-mono font-medium",children:b.keyIndex?`#${b.keyIndex}`:b.id.slice(0,12)})," ","(",I(b.tokenBalance)," tokens) to"," ",jsxs("span",{className:"font-mono font-medium",children:[d.trim().slice(0,20),"..."]})]})]}),jsxs("label",{className:"flex items-start gap-2 cursor-pointer",children:[jsx("input",{type:"checkbox",checked:i,onChange:k=>o(k.target.checked),className:"mt-0.5 h-4 w-4 rounded border-border"}),jsx("span",{className:"text-xs text-muted-foreground",children:"I confirm this transfer is permanent and cannot be undone."})]})]})]})}),a&&jsx("p",{className:"text-sm text-red-500",children:a}),jsx("button",{onClick:T,disabled:!P,className:u("flex w-full items-center justify-center gap-2 rounded-lg px-4 py-3 text-sm font-medium transition-all",P?"bg-foreground text-background hover:opacity-90":"bg-muted text-muted-foreground cursor-not-allowed"),children:m?jsxs(Fragment,{children:[jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent"}),"Transferring..."]}):jsxs(Fragment,{children:[jsx(Send,{className:"h-4 w-4"}),"Transfer Key"]})})]})}var qt=[{id:"buy",label:"Buy"},{id:"use",label:"Use"},{id:"sell",label:"Sell"},{id:"transfer",label:"Transfer"}];function zt({active:e,onChange:t}){return jsx("div",{role:"tablist","aria-label":"Key actions",className:"flex gap-1 rounded-2xl bg-muted/50 p-1.5",children:qt.map(({id:r,label:s})=>jsx("button",{role:"tab","aria-selected":e===r,"aria-controls":`panel-${r}`,id:`tab-${r}`,onClick:()=>t(r),className:u("flex flex-1 items-center justify-center gap-2.5 rounded-xl py-3.5 text-sm font-medium transition-all",e===r?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:jsx("span",{className:"inline",children:s})},r))})}function Yt({defaultTab:e="buy",className:t,style:r}){let[s,g]=useState(e);return jsxs("div",{className:u("flex flex-col",t),style:r,children:[jsx("div",{className:"sticky top-0 z-10 bg-background/80 px-5 pb-3 pt-2 sm:pt-5 backdrop-blur-sm sm:px-10 md:px-16 lg:px-20",children:jsx("div",{className:"mx-auto max-w-xl",children:jsx(zt,{active:s,onChange:g})})}),jsx("div",{className:"flex flex-1 flex-col px-5 pb-8 sm:px-10 md:px-16 md:pb-12 lg:px-20",children:jsx("div",{className:"mx-auto w-full max-w-xl flex-1",children:jsxs("div",{role:"tabpanel",id:`panel-${s}`,"aria-labelledby":`tab-${s}`,children:[s==="buy"&&jsx(fe,{className:"flex-1"}),s==="use"&&jsx(pe,{className:"flex-1"}),s==="sell"&&jsx(be,{className:"flex-1"}),s==="transfer"&&jsx(ve,{className:"flex-1"})]})})})]})}function Jt({apiBaseUrl:e,stackId:t,stackName:r,paymentMethods:s,merchantWallet:g,stripePublicKey:m,theme:f,maxQuantity:a,keyImage:n,keyImageClass:c,aispImage:d,termsUrl:p,onMintSuccess:i,onMintError:o,onPaymentStart:l,onPaymentComplete:b,onListingCreated:w,onTransferComplete:P,defaultTab:T,className:j,style:k}){return jsx(oe,{config:{apiBaseUrl:e,stackId:t,stackName:r,paymentMethods:s,merchantWallet:g,stripePublicKey:m,theme:f,maxQuantity:a,keyImage:n,keyImageClass:c,aispImage:d,termsUrl:p},callbacks:{onMintSuccess:i,onMintError:o,onPaymentStart:l,onPaymentComplete:b,onListingCreated:w,onTransferComplete:P},children:jsx(Yt,{defaultTab:T,className:j,style:k})})}function ze(e){let{config:t}=C(),[r,s]=useState([]),[g,m]=useState(false),[f,a]=useState(null),n=useRef(true),c=t.apiBaseUrl,d=useCallback(async()=>{if(e)try{m(!0),a(null);let p=await fetch(`${c}/api/keys/${e}/ledger`);if(!p.ok){let o=`Failed to fetch ledger (${p.status})`;try{let l=await p.json();l.error&&(o=l.error);}catch{}throw new Error(o)}let i=await p.json();n.current&&s(Array.isArray(i)?i:i.entries??[]);}catch(p){n.current&&a(p instanceof Error?p.message:"Failed to fetch ledger");}finally{n.current&&m(false);}},[c,e]);return useEffect(()=>(n.current=true,d(),()=>{n.current=false;}),[d]),{entries:r,loading:g,error:f,refresh:d}}var we=20;function Pe({nodeKey:e,className:t,style:r}){let[s,g]=useState(false),[m,f]=useState(false),a=useRef(null),{entries:n,loading:c}=ze(s?e.id:null);useEffect(()=>()=>{a.current&&clearTimeout(a.current);},[]);let d=useCallback(()=>{e.key&&(navigator.clipboard.writeText(e.key),f(true),a.current&&clearTimeout(a.current),a.current=setTimeout(()=>f(false),2e3));},[e.key]),p=e.status==="active"?"text-green-500":e.status==="expired"?"text-red-500":"text-yellow-500",i=n.slice(0,we);return jsxs("div",{className:u("rounded-lg border bg-background",t),style:r,children:[jsxs("div",{className:"p-4",children:[jsxs("div",{className:"mb-3 flex items-center justify-between",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsx("button",{onClick:()=>g(!s),"aria-expanded":s,"aria-label":s?"Collapse ledger":"Expand ledger",className:"text-muted-foreground hover:text-foreground",children:s?jsx(ChevronDown,{className:"h-4 w-4"}):jsx(ChevronRight,{className:"h-4 w-4"})}),jsxs("span",{className:"text-sm font-medium text-foreground",children:[e.keyIndex?`#${e.keyIndex} `:"",e.label||e.id.slice(0,16)]})]}),jsx("span",{className:u("text-xs font-medium capitalize",p),children:e.status})]}),e.key&&jsxs("div",{className:"mb-3 flex items-center gap-2",children:[jsx("code",{className:"flex-1 truncate rounded bg-muted px-2 py-1 text-xs text-muted-foreground",children:e.key}),jsx("button",{onClick:d,"aria-label":"Copy key to clipboard",className:"shrink-0 rounded p-1 text-muted-foreground hover:bg-muted hover:text-foreground",children:m?jsx(Check,{className:"h-3.5 w-3.5 text-green-500"}):jsx(Copy,{className:"h-3.5 w-3.5"})})]}),jsx(V,{current:e.tokenBalance,max:e.maxTokens}),jsxs("div",{className:"mt-2 flex items-center justify-between text-xs text-muted-foreground",children:[jsxs("span",{children:["Created ",z(e.createdAt)]}),e.expiresAt&&jsxs("span",{children:["Expires ",z(e.expiresAt)]})]})]}),s&&jsxs("div",{className:"border-t px-4 py-3",children:[jsx("h4",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Ledger"}),c?jsx("p",{className:"text-xs text-muted-foreground",children:"Loading..."}):i.length===0?jsx("p",{className:"text-xs text-muted-foreground",children:"No ledger entries."}):jsxs("div",{className:"space-y-1.5",children:[i.map(o=>jsxs("div",{className:"flex items-center justify-between text-xs",children:[jsxs("div",{className:"flex items-center gap-2",children:[jsxs("span",{className:u("font-medium",o.type==="credit"||o.type==="reward"?"text-green-500":"text-red-500"),children:[o.type==="credit"||o.type==="reward"?"+":"-",I(Math.abs(o.amount))]}),jsx("span",{className:"text-muted-foreground",children:o.description})]}),jsx("span",{className:"text-muted-foreground",children:z(o.createdAt)})]},o.id)),n.length>we&&jsxs("p",{className:"pt-1 text-xs text-muted-foreground",children:["Showing ",we," of ",n.length," entries"]})]})]})]})}var lr=[{id:"buy",label:"Buy"},{id:"use",label:"Use"},{id:"sell",label:"Sell"}];function ne({baseHref:e}){return jsx("div",{className:"flex gap-1 rounded-2xl bg-muted/50 p-1.5 mb-6",children:lr.map(({id:t,label:r})=>jsx("a",{href:`${e}?tab=${t}`,className:"flex flex-1 items-center justify-center gap-2.5 rounded-xl py-3.5 text-sm font-medium text-muted-foreground hover:text-foreground transition-all",children:r},t))})}function cr({getKeyHref:e="/keys/get",showTabs:t=true,className:r,style:s}){let{keys:g,totalBalance:m,loading:f,error:a,refresh:n}=J();return f?jsxs("div",{className:u("space-y-4",r),style:s,children:[t&&e&&jsx(ne,{baseHref:e}),jsx(Y,{count:3})]}):a?jsxs("div",{className:u("space-y-4",r),style:s,children:[t&&e&&jsx(ne,{baseHref:e}),jsxs("div",{className:"flex flex-col items-center justify-center gap-4 py-12",children:[jsxs("div",{className:"rounded-xl border border-red-500/20 bg-red-500/5 px-6 py-5 text-center max-w-sm",children:[jsx("p",{className:"text-sm font-medium text-foreground",children:"Unable to load your keys"}),jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:a})]}),jsx("button",{onClick:()=>n(),className:"text-sm text-muted-foreground hover:text-foreground transition-colors",children:"Try again"})]})]}):g.length===0?jsxs("div",{className:u("space-y-4",r),style:s,children:[t&&e&&jsx(ne,{baseHref:e}),jsxs("div",{className:"flex flex-col items-center justify-center gap-4 rounded-lg border border-dashed py-12",children:[jsx(KeyRound,{className:"h-10 w-10 text-muted-foreground"}),jsxs("div",{className:"text-center",children:[jsx("p",{className:"text-sm font-medium text-foreground",children:"No keys yet"}),jsx("p",{className:"text-xs text-muted-foreground",children:"Get your first node key to start earning."})]}),e&&jsx("a",{href:e,className:"rounded-lg bg-foreground px-4 py-2 text-sm font-medium text-background transition-colors hover:bg-foreground/90",children:"Get a Key"})]})]}):jsxs("div",{className:u("space-y-4",r),style:s,children:[t&&e&&jsx(ne,{baseHref:e}),jsxs("div",{className:"flex items-center justify-between",children:[jsxs("p",{className:"text-sm text-muted-foreground",children:[g.length," key",g.length!==1?"s":""," \xB7 Total balance: ",I(m)]}),e&&jsx("a",{href:e,className:"rounded-md bg-foreground px-3 py-1.5 text-xs font-medium text-background transition-colors hover:bg-foreground/90",children:"Get a Key"})]}),g.map(c=>jsx(Pe,{nodeKey:c},c.id))]})}
2
+ export{Jt as BuyKeyWidget,fe as BuyPanel,V as KeyBalanceBar,Pe as KeyCard,cr as KeyList,oe as KeyUtilsProvider,ue as MintSuccess,be as SellPanel,de as SolanaPayButton,ve as TransferPanel,pe as UsePanel,C as useKeyUtilsContext};
@@ -1 +1 @@
1
- 'use strict';var react=require('react');require('react/jsx-runtime');var L=react.createContext(null);function m(){let e=react.useContext(L);if(!e)throw new Error("useKeyUtilsContext must be used within a KeyUtilsProvider");return e}function S(){let{config:e}=m(),[c,g]=react.useState(null),[u,f]=react.useState(true),[y,d]=react.useState(null),i=react.useRef(true),l=react.useRef(e.apiBaseUrl);l.current=e.apiBaseUrl;let a=async()=>{try{i.current&&(f(!0),d(null));let s=await fetch(`${l.current}/api/keys/pricing`);if(!s.ok){let t=`Pricing unavailable (${s.status})`;try{let n=await s.json();n.error&&(t=n.error);}catch{}throw new Error(t)}let r=await s.json();i.current&&g(r);}catch(s){i.current&&d(s instanceof Error?s.message:"Failed to fetch pricing");}finally{i.current&&f(false);}};return react.useEffect(()=>{i.current=true,a();let s=setInterval(a,6e4);return ()=>{i.current=false,clearInterval(s);}},[]),{pricing:c,loading:u,error:y,refresh:a}}function j(e){return {id:e.id||"",key:e.key||e.keyPrefix||"",userId:e.userId||e.user_id||"",status:e.status||"active",tokenBalance:e.tokenBalance??e.currentTokenBalance??e.current_token_balance??0,maxTokens:e.maxTokens??e.initialTokenBalance??e.initial_token_balance??0,createdAt:String(e.createdAt??e.created_at??""),expiresAt:e.expiresAt,label:e.label||e.keyPrefix||e.key_prefix||void 0,paperWork:e.paperWork||e.paper_work||void 0,stackId:e.stackId,stackName:e.stackName}}function N(){let{config:e}=m(),[c,g]=react.useState([]),[u,f]=react.useState(true),[y,d]=react.useState(null),i=react.useRef(true),l=e.apiBaseUrl,a=react.useCallback(async()=>{try{f(!0),d(null);let r=await fetch(`${l}/api/keys`);if(!r.ok){let o=`Failed to fetch keys (${r.status})`;try{let p=await r.json();p.error&&(o=p.error);}catch{}throw new Error(o)}let t=await r.json(),n=Array.isArray(t)?t:t.keys??[];i.current&&g(n.map(j));}catch(r){i.current&&d(r instanceof Error?r.message:"Failed to fetch keys");}finally{i.current&&f(false);}},[l]);react.useEffect(()=>(i.current=true,a(),()=>{i.current=false;}),[a]);let s=c.reduce((r,t)=>r+t.tokenBalance,0);return {keys:c,totalBalance:s,loading:u,error:y,refresh:a}}function D(e){let{config:c}=m(),[g,u]=react.useState([]),[f,y]=react.useState(false),[d,i]=react.useState(null),l=react.useRef(true),a=c.apiBaseUrl,s=react.useCallback(async()=>{if(e)try{y(!0),i(null);let r=await fetch(`${a}/api/keys/${e}/ledger`);if(!r.ok){let n=`Failed to fetch ledger (${r.status})`;try{let o=await r.json();o.error&&(n=o.error);}catch{}throw new Error(n)}let t=await r.json();l.current&&u(Array.isArray(t)?t:t.entries??[]);}catch(r){l.current&&i(r instanceof Error?r.message:"Failed to fetch ledger");}finally{l.current&&y(false);}},[a,e]);return react.useEffect(()=>(l.current=true,s(),()=>{l.current=false;}),[s]),{entries:g,loading:f,error:d,refresh:s}}function F(){let{config:e,callbacks:c}=m(),[g,u]=react.useState(false),[f,y]=react.useState(null),[d,i]=react.useState(null);return {mint:react.useCallback(async(a,s,r=1)=>{try{u(!0),i(null),c.onPaymentComplete?.(a,s);let t=await fetch(`${e.apiBaseUrl}/api/keys/mint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paymentMethod:a,paymentRef:s,quantity:r})});if(!t.ok){let k="Key generation failed";try{let C=await t.json();C.error&&(k=C.error);}catch{}throw new Error(k)}let n=await t.json(),o=n.keys?.[0]||n,p={success:!0,key:{id:o.keyId||o.id||"",key:o.key||"",userId:o.userId||"",status:"active",tokenBalance:o.tokenBalance??o.currentTokenBalance??0,maxTokens:o.initialTokenBalance??o.tokenBalance??0,createdAt:String(o.createdAt||Date.now())},transactionId:s};return y(p),c.onMintSuccess?.(p),p}catch(t){let n=t instanceof Error?t:new Error("Key generation failed");return i(n.message),c.onMintError?.(n),{success:false,error:n.message}}finally{u(false);}},[e.apiBaseUrl,c]),minting:g,result:f,error:d}}function V(){let{config:e,callbacks:c}=m(),[g,u]=react.useState(false),[f,y]=react.useState(null),[d,i]=react.useState(null),l=react.useRef(true),a=react.useCallback(async(r,t)=>{try{u(!0),i(null);let n=await fetch(`${e.apiBaseUrl}/api/keys/${r}/list`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({askPriceCents:t,stackId:e.stackId,stackName:e.stackName})});if(!n.ok){let p=`Listing failed (${n.status})`;try{let k=await n.json();k.error&&(p=k.error);}catch{}throw new Error(p)}let o=await n.json();return l.current&&(y(o),c.onListingCreated?.(o)),o}catch(n){let o=n instanceof Error?n.message:"Listing failed";return l.current&&i(o),null}finally{l.current&&u(false);}},[e.apiBaseUrl,e.stackId,e.stackName,c]),s=react.useCallback(async r=>{try{u(!0),i(null);let t=await fetch(`${e.apiBaseUrl}/api/keys/${r}/list`,{method:"DELETE"});if(!t.ok){let n=`Delist failed (${t.status})`;try{let o=await t.json();o.error&&(n=o.error);}catch{}throw new Error(n)}return l.current&&y(null),!0}catch(t){let n=t instanceof Error?t.message:"Delist failed";return l.current&&i(n),false}finally{l.current&&u(false);}},[e.apiBaseUrl]);return {listKey:a,delistKey:s,listing:g,result:f,error:d}}function z(){let{config:e}=m(),[c,g]=react.useState(false),[u,f]=react.useState(null),y=react.useRef(true);return {createSession:react.useCallback(async(i,l)=>{try{g(!0),f(null);let a=await fetch(`${e.apiBaseUrl}/api/keys/stripe-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({priceCents:i,quantity:l,stackId:e.stackId,referrerUrl:window.location.href})});if(!a.ok){let r=`Checkout failed (${a.status})`;try{let t=await a.json();t.error&&(r=t.error);}catch{}throw new Error(r)}let{url:s}=await a.json();if(s){try{sessionStorage.setItem("keyutils_stripe_pending","1");}catch{}window.location.href=s;}else throw new Error("No checkout URL returned")}catch(a){if(y.current){let s=a instanceof Error?a.message:"Checkout failed";f(s),g(false);}}},[e.apiBaseUrl,e.stackId]),loading:c,error:u}}exports.useKeyLedger=D;exports.useKeys=N;exports.useListKey=V;exports.useMintKey=F;exports.usePricing=S;exports.useStripeCheckout=z;
1
+ 'use strict';var react=require('react');require('react/jsx-runtime');var L=react.createContext(null);function d(){let e=react.useContext(L);if(!e)throw new Error("useKeyUtilsContext must be used within a KeyUtilsProvider");return e}function S(){let{config:e}=d(),[c,g]=react.useState(null),[u,f]=react.useState(true),[y,m]=react.useState(null),s=react.useRef(true),a=react.useRef(e.apiBaseUrl);a.current=e.apiBaseUrl;let l=async()=>{try{s.current&&(f(!0),m(null));let i=await fetch(`${a.current}/api/keys/pricing`);if(!i.ok){let t=`Pricing unavailable (${i.status})`;try{let r=await i.json();r.error&&(t=r.error);}catch{}throw new Error(t)}let n=await i.json();s.current&&g(n);}catch(i){s.current&&m(i instanceof Error?i.message:"Failed to fetch pricing");}finally{s.current&&f(false);}};return react.useEffect(()=>{s.current=true,l();let i=setInterval(l,6e4);return ()=>{s.current=false,clearInterval(i);}},[]),{pricing:c,loading:u,error:y,refresh:l}}function M(e){return {id:e.id||"",keyIndex:e.keyIndex??e.key_index??null,key:e.key||e.keyPrefix||"",userId:e.userId||e.user_id||"",status:e.status||"active",tokenBalance:e.tokenBalance??e.currentTokenBalance??e.current_token_balance??0,maxTokens:e.maxTokens??e.initialTokenBalance??e.initial_token_balance??0,createdAt:String(e.createdAt??e.created_at??""),expiresAt:e.expiresAt,label:e.label||e.keyPrefix||e.key_prefix||void 0,paperWork:e.paperWork||e.paper_work||void 0,stackId:e.stackId,stackName:e.stackName}}function N(){let{config:e}=d(),[c,g]=react.useState([]),[u,f]=react.useState(true),[y,m]=react.useState(null),s=react.useRef(true),a=e.apiBaseUrl,l=react.useCallback(async()=>{try{f(!0),m(null);let n=await fetch(`${a}/api/keys`);if(!n.ok){let o=`Failed to fetch keys (${n.status})`;try{let p=await n.json();p.error&&(o=p.error);}catch{}throw new Error(o)}let t=await n.json(),r=Array.isArray(t)?t:t.keys??[];s.current&&g(r.map(M));}catch(n){s.current&&m(n instanceof Error?n.message:"Failed to fetch keys");}finally{s.current&&f(false);}},[a]);react.useEffect(()=>(s.current=true,l(),()=>{s.current=false;}),[l]);let i=c.reduce((n,t)=>n+t.tokenBalance,0);return {keys:c,totalBalance:i,loading:u,error:y,refresh:l}}function O(e){let{config:c}=d(),[g,u]=react.useState([]),[f,y]=react.useState(false),[m,s]=react.useState(null),a=react.useRef(true),l=c.apiBaseUrl,i=react.useCallback(async()=>{if(e)try{y(!0),s(null);let n=await fetch(`${l}/api/keys/${e}/ledger`);if(!n.ok){let r=`Failed to fetch ledger (${n.status})`;try{let o=await n.json();o.error&&(r=o.error);}catch{}throw new Error(r)}let t=await n.json();a.current&&u(Array.isArray(t)?t:t.entries??[]);}catch(n){a.current&&s(n instanceof Error?n.message:"Failed to fetch ledger");}finally{a.current&&y(false);}},[l,e]);return react.useEffect(()=>(a.current=true,i(),()=>{a.current=false;}),[i]),{entries:g,loading:f,error:m,refresh:i}}function J(){let{config:e,callbacks:c}=d(),[g,u]=react.useState(false),[f,y]=react.useState(null),[m,s]=react.useState(null);return {mint:react.useCallback(async(l,i,n=1)=>{try{u(!0),s(null),c.onPaymentComplete?.(l,i);let t=await fetch(`${e.apiBaseUrl}/api/keys/mint`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({paymentMethod:l,paymentRef:i,quantity:n})});if(!t.ok){let k="Key generation failed";try{let C=await t.json();C.error&&(k=C.error);}catch{}throw new Error(k)}let r=await t.json(),o=r.keys?.[0]||r,p={success:!0,key:{id:o.keyId||o.id||"",key:o.key||"",userId:o.userId||"",status:"active",tokenBalance:o.tokenBalance??o.currentTokenBalance??0,maxTokens:o.initialTokenBalance??o.tokenBalance??0,createdAt:String(o.createdAt||Date.now())},transactionId:i};return y(p),c.onMintSuccess?.(p),p}catch(t){let r=t instanceof Error?t:new Error("Key generation failed");return s(r.message),c.onMintError?.(r),{success:false,error:r.message}}finally{u(false);}},[e.apiBaseUrl,c]),minting:g,result:f,error:m}}function q(){let{config:e,callbacks:c}=d(),[g,u]=react.useState(false),[f,y]=react.useState(null),[m,s]=react.useState(null),a=react.useRef(true),l=react.useCallback(async(n,t)=>{try{u(!0),s(null);let r=await fetch(`${e.apiBaseUrl}/api/keys/${n}/list`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({askPriceCents:t,stackId:e.stackId,stackName:e.stackName})});if(!r.ok){let p=`Listing failed (${r.status})`;try{let k=await r.json();k.error&&(p=k.error);}catch{}throw new Error(p)}let o=await r.json();return a.current&&(y(o),c.onListingCreated?.(o)),o}catch(r){let o=r instanceof Error?r.message:"Listing failed";return a.current&&s(o),null}finally{a.current&&u(false);}},[e.apiBaseUrl,e.stackId,e.stackName,c]),i=react.useCallback(async n=>{try{u(!0),s(null);let t=await fetch(`${e.apiBaseUrl}/api/keys/${n}/list`,{method:"DELETE"});if(!t.ok){let r=`Delist failed (${t.status})`;try{let o=await t.json();o.error&&(r=o.error);}catch{}throw new Error(r)}return a.current&&y(null),!0}catch(t){let r=t instanceof Error?t.message:"Delist failed";return a.current&&s(r),false}finally{a.current&&u(false);}},[e.apiBaseUrl]);return {listKey:l,delistKey:i,listing:g,result:f,error:m}}function G(){let{config:e}=d(),[c,g]=react.useState(false),[u,f]=react.useState(null),y=react.useRef(true);return {createSession:react.useCallback(async(s,a)=>{try{g(!0),f(null);let l=await fetch(`${e.apiBaseUrl}/api/keys/stripe-session`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({priceCents:s,quantity:a,stackId:e.stackId,referrerUrl:window.location.href})});if(!l.ok){let n=`Checkout failed (${l.status})`;try{let t=await l.json();t.error&&(n=t.error);}catch{}throw new Error(n)}let{url:i}=await l.json();if(i){try{sessionStorage.setItem("keyutils_stripe_pending","1");}catch{}window.location.href=i;}else throw new Error("No checkout URL returned")}catch(l){if(y.current){let i=l instanceof Error?l.message:"Checkout failed";f(i),g(false);}}},[e.apiBaseUrl,e.stackId]),loading:c,error:u}}function X(){let{config:e,callbacks:c}=d(),[g,u]=react.useState(false),[f,y]=react.useState(null),[m,s]=react.useState(null),a=react.useRef(true);return {transferKey:react.useCallback(async(i,n)=>{try{u(!0),s(null);let t=await fetch(`${e.apiBaseUrl}/api/keys/${i}/transfer`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({recipientId:n})});if(!t.ok){let o=`Transfer failed (${t.status})`;try{let p=await t.json();p.error&&(o=p.error);}catch{}throw new Error(o)}let r=await t.json();return a.current&&(y(r),c.onTransferComplete?.(r)),r}catch(t){let r=t instanceof Error?t.message:"Transfer failed";return a.current&&s(r),null}finally{a.current&&u(false);}},[e.apiBaseUrl,c]),transferring:g,result:f,error:m}}exports.useKeyLedger=O;exports.useKeys=N;exports.useListKey=q;exports.useMintKey=J;exports.usePricing=S;exports.useStripeCheckout=G;exports.useTransferKey=X;
@@ -1,4 +1,4 @@
1
- import { PricingInfo, NodeKeyInfo, LedgerEntry, PaymentMethod, MintResult, ListingResult } from '../types/index.cjs';
1
+ import { PricingInfo, NodeKeyInfo, LedgerEntry, PaymentMethod, MintResult, ListingResult, DirectTransferResult } from '../types/index.cjs';
2
2
 
3
3
  interface UsePricingReturn {
4
4
  pricing: PricingInfo | null;
@@ -49,4 +49,12 @@ interface UseStripeCheckoutReturn {
49
49
  }
50
50
  declare function useStripeCheckout(): UseStripeCheckoutReturn;
51
51
 
52
- export { useKeyLedger, useKeys, useListKey, useMintKey, usePricing, useStripeCheckout };
52
+ interface UseTransferKeyReturn {
53
+ transferKey: (keyId: string, recipientId: string) => Promise<DirectTransferResult | null>;
54
+ transferring: boolean;
55
+ result: DirectTransferResult | null;
56
+ error: string | null;
57
+ }
58
+ declare function useTransferKey(): UseTransferKeyReturn;
59
+
60
+ export { useKeyLedger, useKeys, useListKey, useMintKey, usePricing, useStripeCheckout, useTransferKey };
@@ -1,4 +1,4 @@
1
- import { PricingInfo, NodeKeyInfo, LedgerEntry, PaymentMethod, MintResult, ListingResult } from '../types/index.js';
1
+ import { PricingInfo, NodeKeyInfo, LedgerEntry, PaymentMethod, MintResult, ListingResult, DirectTransferResult } from '../types/index.js';
2
2
 
3
3
  interface UsePricingReturn {
4
4
  pricing: PricingInfo | null;
@@ -49,4 +49,12 @@ interface UseStripeCheckoutReturn {
49
49
  }
50
50
  declare function useStripeCheckout(): UseStripeCheckoutReturn;
51
51
 
52
- export { useKeyLedger, useKeys, useListKey, useMintKey, usePricing, useStripeCheckout };
52
+ interface UseTransferKeyReturn {
53
+ transferKey: (keyId: string, recipientId: string) => Promise<DirectTransferResult | null>;
54
+ transferring: boolean;
55
+ result: DirectTransferResult | null;
56
+ error: string | null;
57
+ }
58
+ declare function useTransferKey(): UseTransferKeyReturn;
59
+
60
+ export { useKeyLedger, useKeys, useListKey, useMintKey, usePricing, useStripeCheckout, useTransferKey };