@liberfi.io/ui-predict 0.1.69 → 0.1.70

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import {createContext,useContext,useMemo,useState,useRef,useEffect,useCallback}from'react';import {useQuery,useInfiniteQuery,useMutation,useQueries}from'@tanstack/react-query';import {useTranslation}from'@liberfi.io/i18n';import {cn,Skeleton,Avatar,StyledTooltip,ChevronUpIcon,Button,ChevronRightIcon,ChevronLeftIcon,Spinner,StyledModal,ModalContent,ModalHeader,ModalBody,ModalFooter,RefreshIcon,TimerIcon,DropletIcon,ChartLineIcon,CalendarIcon,StyledBadge,FilterIcon,Linkable,PolymarketIcon,KalshiIcon,useDisclosure,toast,Tabs,Tab,StyledNumberInput,Select,SelectSection,SelectItem,useScreen,Drawer,DrawerContent,DrawerBody,StyledTable,TableHeader,TableColumn,TableBody,TableRow,TableCell,TrashIcon,Chip,StyledInput,XCloseIcon,Kbd,SearchIcon,EmptyIcon,ChevronDownIcon}from'@liberfi.io/ui';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import {List}from'react-window';import {useInfiniteLoader}from'react-window-infinite-loader';import {useResizeObserver,useCallbackRef}from'@liberfi.io/hooks';import {SOLANA_TOKENS,formatAmountUSDCompact,debounce,httpGet,httpPost}from'@liberfi.io/utils';import {useAuth,useWallets,useAuthCallback}from'@liberfi.io/wallet-connector';import Vr from'canvas-confetti';import {ChainNamespace,Chain}from'@liberfi.io/types';import {useWalletPortfoliosQuery}from'@liberfi.io/react';import {ResponsiveContainer,LineChart,CartesianGrid,XAxis,YAxis,Tooltip,Line,Customized}from'recharts';import {AsyncModal,useAsyncModal}from'@liberfi.io/ui-scaffold';import {useAtom}from'jotai';import {atomWithStorage}from'jotai/utils';typeof window<"u"&&(window.__LIBERFI_VERSION__=window.__LIBERFI_VERSION__||{},window.__LIBERFI_VERSION__["@liberfi.io/ui-predict"]="0.1.69");var ja="0.1.69";var Ct=createContext(null);function bn(){let e=useContext(Ct);if(!e)throw new Error("usePredictV2Context must be used within a PredictV2Provider");return e}function fe(){let{client:e}=bn();return e}function ei(e){return ["predict-v2","events",e??{}]}async function ti(e,t){return e.listEvents(t)}function _y(e,t={}){let r=fe();return useQuery({queryKey:ei(e),queryFn:()=>ti(r,e),...t})}var de=48,J=4,Et={ONE_MINUTE:1,ONE_HOUR:60,ONE_DAY:1440},S={ONE_DAY:"1d",ONE_WEEK:"1w",ONE_MONTH:"1m",ALL:"all"},le=S.ALL,He={[S.ONE_DAY]:Et.ONE_MINUTE,[S.ONE_WEEK]:Et.ONE_HOUR,[S.ONE_MONTH]:Et.ONE_HOUR,[S.ALL]:Et.ONE_DAY},Mt={[S.ONE_DAY]:300,[S.ONE_WEEK]:3600,[S.ONE_MONTH]:10800,[S.ALL]:1440*60},Ke={[S.ONE_DAY]:1440*60,[S.ONE_WEEK]:10080*60,[S.ONE_MONTH]:720*60*60,[S.ALL]:null},ir=1,Ay=1,Dy=1,Uy=99,qe={ONE_HOUR:"1h",SIX_HOURS:"6h",ONE_DAY:"1d",ONE_WEEK:"1w",MAX:"max"},Fy=qe.ONE_WEEK,Wy={[qe.ONE_HOUR]:60,[qe.SIX_HOURS]:60,[qe.ONE_DAY]:300,[qe.ONE_WEEK]:1800,[qe.MAX]:1800};function kn(e){if(e)return e.tagSlug??e.categorySlug??void 0}function lr(e={}){let{tagSlugSelection:t,limit:r=48,status:n="open",with_markets:s=true,source:a,sort_by:o,sort_asc:i}=e,l=kn(t);return {limit:r,status:n,with_markets:s,...a?{source:a}:{},...l?{tag_slug:l}:{},...o?{sort_by:o}:{},...i!==void 0?{sort_asc:i}:{}}}function cr(e){return ["predict-v2","events-infinite",e]}async function ur(e,t){return e.listEvents(t)}function dr(e,t){return ["predict-v2","event",e,t]}async function pr(e,t,r){return e.getEvent(t,r)}function wt(e,t={}){let r=fe();return useQuery({queryKey:dr(e.slug,e.source),queryFn:()=>pr(r,e.slug,e.source),enabled:!!e.slug,...t})}function Pn(e,t={}){let r=fe();return useInfiniteQuery({queryKey:cr(e),queryFn:({pageParam:n})=>ur(r,{...e,...n!==void 0?{cursor:n}:{}}),initialPageParam:void 0,getNextPageParam:n=>n.has_more&&n.next_cursor?n.next_cursor:void 0,...t})}function ai(e){return ["predict-v2","search",e]}function Sn(e,t){let r=fe(),n=useMemo(()=>({search:e.keyword,limit:e.limit??20,status:e.status??"open",source:e.source,with_markets:e.with_markets??false}),[e.keyword,e.limit,e.status,e.source,e.with_markets]);return useInfiniteQuery({queryKey:ai(n),queryFn:({pageParam:s})=>r.listEvents({...n,...s!==void 0?{cursor:s}:{}}),initialPageParam:void 0,getNextPageParam:s=>s.has_more&&s.next_cursor?s.next_cursor:void 0,enabled:t?.enabled??!!e.keyword})}function li(e,t){return ["predict-v2","market",e,t]}async function ci(e,t,r){return e.getMarket(t,r)}function lg(e,t={}){let r=fe();return useQuery({queryKey:li(e.slug,e.source),queryFn:()=>ci(r,e.slug,e.source),enabled:!!e.slug,...t})}var di={[S.ONE_DAY]:{daysBack:1,stepMs:300*1e3},[S.ONE_WEEK]:{daysBack:7,stepMs:1800*1e3},[S.ONE_MONTH]:{daysBack:30,stepMs:10800*1e3},[S.ALL]:{daysBack:90,stepMs:720*60*1e3}};function pi(e,t,r,n){let s=Date.now(),a=s-r*24*60*60*1e3,o=Math.floor((s-a)/n),i=e.split("").reduce((p,d)=>p+d.charCodeAt(0),0);function l(){return i=i*1664525+1013904223&4294967295,(i>>>0)/4294967295}let c=[],u=t;for(let p=o;p>=0;p--){c.unshift({timestamp:a+p*n,price:u});let d=(l()-.5)*.04;u=Math.min(.99,Math.max(.01,u-d));}return c}function Cn(e,t=S.ALL){return {series:useMemo(()=>{let{daysBack:n,stepMs:s}=di[t];return e.map(a=>{let i=a.outcomes.find(l=>l.label.toLowerCase()==="yes")?.price??a.outcomes[0]?.price??.5;return {marketSlug:a.slug,label:a.question,data:pi(a.slug,i,n,s)}})},[e,t]),isLoading:false}}var $e=createContext({});var Me=createContext(null);function En(){let e=useContext($e);if(!e)throw new Error("usePredictContext must be used within a PredictProvider");return e}function k(){let{client:e}=En();return e}function vi(e){return ["predict","events",e??{}]}async function mr(e,t){return await e.getEvents(t)}function Qg(e,t={}){let r=k();return useQuery({queryKey:vi(e),queryFn:async()=>mr(r,e),...t})}function hi(e){return ["predict","events","infinite",e??{}]}function Mn(e={},t={}){let r=k();return useInfiniteQuery({queryKey:hi(e),queryFn:async({pageParam:n})=>mr(r,{...e,...n!==void 0?{cursor:n}:{}}),initialPageParam:void 0,getNextPageParam:n=>n.cursor??void 0,...t})}function ki(e){return ["predict","event","byId",e.id,e.withNestedMarkets]}async function Pi(e,t){return await e.getEventById(t.id,t.withNestedMarkets)}function Tt(e,t={}){let r=k();return useQuery({queryKey:ki(e),queryFn:async()=>Pi(r,e),...t})}function Ci(e){return ["predict","markets",e??{}]}async function Ei(e,t){return await e.getMarkets(t)}function Gg(e,t={}){let r=k();return useQuery({queryKey:Ci(e),queryFn:async()=>Ei(r,e),...t})}function wi(e){return ["predict","market","byId",e.id]}async function Ti(e,t){return await e.getMarketById(t.id)}function Zg(e,t={}){let r=k();return useQuery({queryKey:wi(e),queryFn:async()=>Ti(r,e),...t})}function Ni(e){return ["predict","market","byMint",e]}async function Oi(e,t){return await e.getMarketByMint(t)}function rv(e,t={}){let r=k();return useQuery({queryKey:Ni(e),queryFn:async()=>Oi(r,e),...t})}function Li(e){return ["predict","markets","batch",e]}async function Vi(e,t){return await e.getMarketsBatch(t)}function av(e,t={}){let r=k();return useQuery({queryKey:Li(e),queryFn:async()=>Vi(r,e),enabled:!!(e.tickers?.length||e.mints?.length),...t})}function Bi(e){return ["predict","orderBook",e]}async function _i(e,t){return await e.getOrderbook(t)}function ze(e,t={}){let r=k();return useQuery({queryKey:Bi(e),queryFn:async()=>_i(r,e),...t})}function Qi(e){return ["predict","orderBook","byMint",e]}async function Ai(e,t){return await e.getOrderbookByMint(t)}function uv(e,t={}){let r=k();return useQuery({queryKey:Qi(e),queryFn:async()=>Ai(r,e),...t})}function Di(e){return ["predict","trades",e??{}]}async function Ui(e,t){return await e.getTrades(t)}function Rn(e,t={}){let r=k();return useQuery({queryKey:Di(e),queryFn:async()=>Ui(r,e),...t})}function Fi(e){return ["predict","trades","byMint",e]}async function Wi(e,t){return await e.getTradesByMint(t)}function fv(e,t={}){let r=k();return useQuery({queryKey:Fi(e),queryFn:async()=>Wi(r,e),...t})}function qi(e){return ["predict","onchainTrades","byWallet",e]}async function yr(e,t){return await e.getOnchainTradesByWallet(t)}function Nn(e,t={}){let r=k();return useQuery({queryKey:qi(e),queryFn:async()=>yr(r,e),...t})}function Hi(e){return ["predict","onchainTrades","byEvent",e]}async function gr(e,t){return await e.getOnchainTradesByEvent(t)}function xv(e,t={}){let r=k();return useQuery({queryKey:Hi(e),queryFn:async()=>gr(r,e),...t})}function Ki(e){return ["predict","onchainTrades","byMarket",e]}async function vr(e,t){return await e.getOnchainTradesByMarket(t)}function hv(e,t={}){let r=k();return useQuery({queryKey:Ki(e),queryFn:async()=>vr(r,e),...t})}function hr(e){return e.cursor??void 0}function $i(e){return ["predict","onchainTrades","byWallet","infinite",e]}function Cv(e,t={}){let r=k();return useInfiniteQuery({queryKey:$i(e),queryFn:async({pageParam:n})=>yr(r,{...e,...n!==void 0?{cursor:n}:{}}),initialPageParam:void 0,getNextPageParam:hr,...t})}function zi(e){return ["predict","onchainTrades","byEvent","infinite",e]}function Ev(e,t={}){let r=k();return useInfiniteQuery({queryKey:zi(e),queryFn:async({pageParam:n})=>gr(r,{...e,...n!==void 0?{cursor:n}:{}}),initialPageParam:void 0,getNextPageParam:hr,...t})}function Gi(e){return ["predict","onchainTrades","byMarket","infinite",e]}function Mv(e,t={}){let r=k();return useInfiniteQuery({queryKey:Gi(e),queryFn:async({pageParam:n})=>vr(r,{...e,...n!==void 0?{cursor:n}:{}}),initialPageParam:void 0,getNextPageParam:hr,...t})}function Yi(e){return ["predict","candlesticks","event",e]}async function ji(e,t){let{ticker:r,...n}=t;return await e.getEventCandlesticks(r,n)}function Nv(e,t={}){let r=k();return useQuery({queryKey:Yi(e),queryFn:async()=>ji(r,e),...t})}function rt(e){return ["predict","candlesticks","market",e]}async function nt(e,t){let{ticker:r,...n}=t;return await e.getMarketCandlesticks(r,n)}function kr(e,t={}){let r=k();return useQuery({queryKey:rt(e),queryFn:async()=>nt(r,e),...t})}function Xi(e){return ["predict","candlesticks","market","byMint",e]}async function Zi(e,t){let{mintAddress:r,...n}=t;return await e.getMarketCandlesticksByMint(r,n)}function Ov(e,t={}){let r=k();return useQuery({queryKey:Xi(e),queryFn:async()=>Zi(r,e),...t})}var Iv=kr;function Ji(e){return ["predict","forecast","percentileHistory",e]}async function el(e,t){return await e.getEventForecastPercentileHistory(t)}function _v(e,t={}){let r=k();return useQuery({queryKey:Ji(e),queryFn:async()=>el(r,e),...t})}function tl(e){return ["predict","forecast","percentileHistory","byMint",e]}async function rl(e,t){return await e.getEventForecastPercentileHistoryByMint(t)}function Qv(e,t={}){let r=k();return useQuery({queryKey:tl(e),queryFn:async()=>rl(r,e),...t})}function nl(e){return ["predict","liveData",e]}async function sl(e,t){return await e.getLiveData(t)}function Fv(e,t={}){let r=k();return useQuery({queryKey:nl(e),queryFn:async()=>sl(r,e),enabled:e.milestoneIds.length>0,...t})}function ol(e){return ["predict","liveData","byEvent",e]}async function al(e,t){return await e.getLiveDataByEvent(t)}function Wv(e,t={}){let r=k();return useQuery({queryKey:ol(e),queryFn:async()=>al(r,e),enabled:!!e.eventTicker,...t})}function il(e){return ["predict","liveData","byMint",e]}async function ll(e,t){return await e.getLiveDataByMint(t)}function qv(e,t={}){let r=k();return useQuery({queryKey:il(e),queryFn:async()=>ll(r,e),enabled:!!e.mintAddress,...t})}function cl(e){return ["predict","series",e??{}]}async function ul(e,t){return await e.getSeries(t)}function Ln(e,t={}){let r=k();return useQuery({queryKey:cl(e),queryFn:async()=>ul(r,e),...t})}function dl(e){return ["predict","series","byTicker",e]}async function pl(e,t){return await e.getSeriesByTicker(t)}function Vn(e,t={}){let r=k();return useQuery({queryKey:dl(e),queryFn:async()=>pl(r,e),...t})}function ml(){return ["predict","tags","byCategories"]}async function fl(e){return await e.getTagsByCategories()}function Sr(e={}){let t=k();return useQuery({queryKey:ml(),queryFn:async()=>fl(t),...e})}function yl(){return ["predict","filters","bySports"]}async function gl(e){return await e.getFiltersBySports()}function jv(e={}){let t=k();return useQuery({queryKey:yl(),queryFn:async()=>gl(t),...e})}var Xv=Sr;function xl(e){return ["predict","search",e]}async function hl(e,t){return await e.search(t)}function tx(e,t={}){let r=k();return useQuery({queryKey:xl(e),queryFn:async()=>hl(r,e),...t})}function kl(e){return ["predict","positions","byWallet",e]}async function Pl(e,t){return await e.getPositionsByWallet(t)}function _n(e,t={}){let r=k();return useQuery({queryKey:kl(e),queryFn:async()=>Pl(r,e),...t})}function lx(){let e=useContext(Me);if(!e)throw new Error("useUserPredictContext must be used within a UserPredictProvider");return e}function Qn(e){let t=useContext(Me);return useMemo(()=>t?{positions:t.positions.filter(n=>n.market?.ticker===e.ticker),isLoading:t.isLoading,isAvailable:true}:{positions:[],isLoading:false,isAvailable:false},[t,e.ticker])}function Tl(e){return ["predict","outcomeMints",e??{}]}async function Rl(e,t){return await e.getOutcomeMints(t)}function yx(e,t={}){let r=k();return useQuery({queryKey:Tl(e),queryFn:async()=>Rl(r,e),...t})}async function Nl(e,t){return await e.filterOutcomeMints(t)}function gx(e={}){let t=k();return useMutation({mutationFn:async r=>Nl(t,r),...e})}function Il(e){return ["predict","quote",e]}async function Ll(e,t){return await e.getQuote(t)}function bx(e,t={}){let r=k();return useQuery({queryKey:Il(e),queryFn:async()=>Ll(r,e),enabled:!!(e.inputMint&&e.outputMint&&e.amount>0),staleTime:1e4,gcTime:3e4,...t})}async function Vl(e,t){return await e.createSwap(t)}function Cx(e={}){let t=k();return useMutation({mutationFn:async r=>Vl(t,r),...e})}async function Bl(e,t){return await e.createSwapInstructions(t)}function Ex(e={}){let t=k();return useMutation({mutationFn:async r=>Bl(t,r),...e})}function _l(e){return ["predict","order",e]}async function Ql(e,t){return await e.getOrder(t)}function Un(e,t={}){let r=k();return useQuery({queryKey:_l(e),queryFn:async()=>Ql(r,e),enabled:!!(e.inputMint&&e.outputMint&&e.amount>0),staleTime:1e4,gcTime:3e4,...t})}function Al(e){return ["predict","order","status",e.signature]}async function Dl(e,t){return await e.getOrderStatus(t)}function Fn(e,t={}){let r=k();return useQuery({queryKey:Al(e),queryFn:async()=>Dl(r,e),enabled:!!e.signature,refetchInterval:t.refetchInterval??3e3,retry:false,...t})}function Wl(e){return ["predict","intent","quote",e]}async function ql(e,t){return await e.getIntentQuote(t)}function Ix(e,t={}){let r=k();return useQuery({queryKey:Wl(e),queryFn:async()=>ql(r,e),enabled:!!(e.inputMint&&e.outputMint&&e.amount>0),staleTime:1e4,gcTime:3e4,...t})}async function Hl(e,t){return await e.submitIntentSwap(t)}function Lx(e={}){let t=k();return useMutation({mutationFn:async r=>Hl(t,r),...e})}async function $l(e,t){return await e.initPredictionMarket(t)}function Qx(e={}){let t=k();return useMutation({mutationFn:async r=>$l(t,r),...e})}function zl(){return ["predict","tokens"]}async function Gl(e){return await e.getTokens()}function Fx(e={}){let t=k();return useQuery({queryKey:zl(),queryFn:async()=>Gl(t),staleTime:300*1e3,gcTime:1800*1e3,...e})}function Yl(){return ["predict","tokens","decimals"]}async function jl(e){return await e.getTokensWithDecimals()}function Wx(e={}){let t=k();return useQuery({queryKey:Yl(),queryFn:async()=>jl(t),staleTime:300*1e3,gcTime:1800*1e3,...e})}function Zl(){return ["predict","venues"]}async function Jl(e){return await e.getVenues()}function $x(e={}){let t=k();return useQuery({queryKey:Zl(),queryFn:async()=>Jl(t),staleTime:300*1e3,gcTime:1800*1e3,...e})}var st=class{ws=null;wsUrl;autoReconnect;reconnectIntervalBase;reconnectMaxInterval;pingInterval;status="disconnected";reconnectAttempts=0;reconnectTimeout=null;pingIntervalId=null;shouldReconnect=true;listeners={connect:[],disconnect:[],reconnecting:[],error:[],price:[],trade:[],orderbook:[],status:[],subscribed:[],unsubscribed:[]};subscriptions={prices:{all:false,tickers:new Set},trades:{all:false,tickers:new Set},orderbook:{all:false,tickers:new Set}};constructor(t){this.wsUrl=t.wsUrl,this.autoReconnect=t.autoReconnect??true,this.reconnectIntervalBase=t.reconnectIntervalBase??1e3,this.reconnectMaxInterval=t.reconnectMaxInterval??3e4,this.pingInterval=t.pingInterval??3e4,t.autoConnect!==false&&this.connect();}connect(){if(!(this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING))){this.shouldReconnect=true,this.setStatus("connecting");try{this.ws=new WebSocket(this.wsUrl),this.ws.onopen=()=>{this.reconnectAttempts=0,this.setStatus("connected"),this.emit("connect",void 0),this.restoreSubscriptions(),this.startPingInterval();},this.ws.onmessage=t=>{this.handleMessage(t.data);},this.ws.onerror=t=>{let r=new Error("WebSocket error");this.emit("error",r);},this.ws.onclose=t=>{this.stopPingInterval(),this.setStatus("disconnected"),this.emit("disconnect",{code:t.code,reason:t.reason}),this.shouldReconnect&&this.autoReconnect&&this.scheduleReconnect();};}catch(t){this.emit("error",t instanceof Error?t:new Error(String(t))),this.shouldReconnect&&this.autoReconnect&&this.scheduleReconnect();}}}disconnect(){this.shouldReconnect=false,this.stopPingInterval(),this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.ws&&(this.ws.close(),this.ws=null),this.setStatus("disconnected");}isConnected(){return this.ws!==null&&this.ws.readyState===WebSocket.OPEN}getStatus(){return this.status}subscribePrices(t,r){this.subscribeChannel("prices",t);let n=this.on("price",r);return ()=>{n(),this.unsubscribeChannel("prices",t);}}subscribeTrades(t,r){this.subscribeChannel("trades",t);let n=this.on("trade",r);return ()=>{n(),this.unsubscribeChannel("trades",t);}}subscribeOrderbook(t,r){this.subscribeChannel("orderbook",t);let n=this.on("orderbook",r);return ()=>{n(),this.unsubscribeChannel("orderbook",t);}}onStatusChange(t){return this.on("status",t)}on(t,r){return this.listeners[t].push(r),()=>{this.off(t,r);}}off(t,r){let n=this.listeners[t],s=n.indexOf(r);s!==-1&&n.splice(s,1);}removeAllListeners(t){if(t)this.listeners[t].length=0;else for(let r of Object.keys(this.listeners))this.listeners[r].length=0;}subscribeChannel(t,r){let n=this.subscriptions[t];if(r.all)n.all=true,n.tickers.clear();else if(r.tickers&&r.tickers.length>0){n.all=false;for(let s of r.tickers)n.tickers.add(s);}this.sendSubscription("subscribe",t,r);}unsubscribeChannel(t,r){let n=this.subscriptions[t];if(r.all)n.all=false,n.tickers.clear();else if(r.tickers&&r.tickers.length>0)for(let s of r.tickers)n.tickers.delete(s);this.sendSubscription("unsubscribe",t,r);}setStatus(t){this.status!==t&&(this.status=t,this.emit("status",t));}emit(t,r){let n=this.listeners[t];for(let s of n)try{s(r);}catch{}}send(t){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return false;try{return this.ws.send(JSON.stringify(t)),!0}catch{return false}}sendSubscription(t,r,n){this.send({type:t,channel:r,all:n.all,tickers:n.tickers});}handleMessage(t){try{let r=JSON.parse(t);switch(r.type){case "ticker":this.emit("price",r);break;case "trade":this.emit("trade",r);break;case "orderbook":this.emit("orderbook",r);break;case "status":break;case "subscribed":this.emit("subscribed",{channel:r.channel,all:r.all,tickers:r.tickers});break;case "unsubscribed":this.emit("unsubscribed",{channel:r.channel,all:r.all,tickers:r.tickers});break;case "pong":break;case "error":this.emit("error",new Error(r.message));break;default:if("channel"in r){let n=r;switch(n.channel){case "prices":this.emit("price",n);break;case "trades":this.emit("trade",n);break;case "orderbook":this.emit("orderbook",n);break}}}}catch{}}scheduleReconnect(){if(this.reconnectTimeout)return;let t=Math.min(this.reconnectIntervalBase*Math.pow(2,this.reconnectAttempts),this.reconnectMaxInterval);this.setStatus("reconnecting"),this.emit("reconnecting",{attempt:this.reconnectAttempts+1,delay:t}),this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.reconnectAttempts++,this.connect();},t);}restoreSubscriptions(){for(let t of ["prices","trades","orderbook"]){let r=this.subscriptions[t];r.all?this.sendSubscription("subscribe",t,{all:true}):r.tickers.size>0&&this.sendSubscription("subscribe",t,{tickers:Array.from(r.tickers)});}}startPingInterval(){this.stopPingInterval(),this.pingIntervalId=setInterval(()=>{this.send({type:"ping"});},this.pingInterval);}stopPingInterval(){this.pingIntervalId&&(clearInterval(this.pingIntervalId),this.pingIntervalId=null);}};function Rt(e){return new st(e)}function Zx({wsEndpoint:e,autoConnect:t=true,autoReconnect:r=true,enabled:n=true}){let[s,a]=useState("disconnected"),[o,i]=useState(null),l=useRef(null);useEffect(()=>{if(!n){l.current&&(l.current.disconnect(),l.current=null),a("disconnected");return}let d=Rt({wsUrl:e,autoConnect:t,autoReconnect:r});l.current=d;let y=d.on("status",v=>{a(v);}),f=d.on("error",v=>{i(v);}),g=d.on("connect",()=>{i(null);});return ()=>{y(),f(),g(),d.disconnect(),l.current=null;}},[e,t,r,n]);let c=useCallback(()=>{l.current?.connect();},[]),u=useCallback(()=>{l.current?.disconnect();},[]);return {client:l.current,status:s,isConnected:s==="connected",connect:c,disconnect:u,error:o}}function rh(){let e=useContext($e);if(!e)throw new Error("useWsClient must be used within a PredictProvider");let{wsClient:t}=e,[r,n]=useState(t?.getStatus()??"disconnected");return useEffect(()=>{if(!t){n("disconnected");return}return n(t.getStatus()),t.onStatusChange(n)},[t]),{wsClient:t,wsStatus:r,isWsConnected:r==="connected"}}function oh({client:e,all:t=false,tickers:r=[],enabled:n=true,onUpdate:s}){let[a,o]=useState(new Map),[i,l]=useState(false),c=useRef(s);return useEffect(()=>{c.current=s;},[s]),useEffect(()=>{if(!e||!n){l(false);return}if(!t&&r.length===0)return;let u=t?{all:true}:{tickers:r},p=e.subscribePrices(u,d=>{o(y=>{let f=new Map(y);return f.set(d.market_ticker,{yesBid:d.yes_bid,yesAsk:d.yes_ask,noBid:d.no_bid,noAsk:d.no_ask,updatedAt:Date.now()}),f}),c.current?.(d);});return l(true),()=>{p(),l(false);}},[e,t,r.join(","),n]),{prices:a,isSubscribed:i}}function lh({client:e,all:t=false,tickers:r=[],enabled:n=true,maxHistory:s=100,onUpdate:a}){let[o,i]=useState([]),[l,c]=useState(false),u=useRef(a);useEffect(()=>{u.current=a;},[a]),useEffect(()=>{if(!e||!n){c(false);return}if(!t&&r.length===0)return;let d=t?{all:true}:{tickers:r},y=e.subscribeTrades(d,f=>{let g={tradeId:f.trade_id,marketTicker:f.market_ticker,price:f.price,count:f.count,yesPrice:f.yes_price,noPrice:f.no_price,takerSide:f.taker_side,createdTime:f.created_time};i(v=>{let h=[g,...v];return h.length>s?h.slice(0,s):h}),u.current?.(f);});return c(true),()=>{y(),c(false);}},[e,t,r.join(","),n,s]);let p=useCallback(()=>{i([]);},[]);return {trades:o,isSubscribed:l,clearHistory:p}}function dh({client:e,all:t=false,tickers:r=[],enabled:n=true,onUpdate:s}){let[a,o]=useState(new Map),[i,l]=useState(false),c=useRef(s);useEffect(()=>{c.current=s;},[s]),useEffect(()=>{if(!e||!n){l(false);return}if(!t&&r.length===0)return;let p=t?{all:true}:{tickers:r},d=e.subscribeOrderbook(p,y=>{o(f=>{let g=new Map(f);return g.set(y.market_ticker,{yesBids:y.yes_bids,yesAsks:y.yes_asks,noBids:y.no_bids,noAsks:y.no_asks,updatedAt:Date.now()}),g}),c.current?.(y);});return l(true),()=>{d(),l(false);}},[e,t,r.join(","),n]);let u=useCallback(p=>a.get(p),[a]);return {orderbooks:a,isSubscribed:i,getOrderbook:u}}var Xn=["Politics","Sports","Culture","Crypto","Climate","Economics","Mentions","Companies","Financials","Tech & Science"];function Zn(){let{data:e,isLoading:t,isError:r,error:n}=Sr();return {data:useMemo(()=>{if(!e?.tagsByCategories)return [];let a=o=>{let i=Xn.indexOf(o);return i===-1?Xn.length:i};return Object.entries(e.tagsByCategories).map(([o,i])=>({category:o,tags:i})).sort((o,i)=>a(o.category)-a(i.category))},[e]),isLoading:t,isError:r,error:n??null}}function Ot({categories:e,selectedCategory:t,selectedTag:r,activeTags:n,onCategorySelect:s,onTagSelect:a,trailing:o,pulsingTab:i="Trending",className:l}){let{t:c}=useTranslation(),u=useCallback(()=>{s(null);},[s]),p=c("predict.categories.trending");return jsxs("div",{className:cn("sticky top-0 z-30 flex w-full flex-col justify-between gap-2 px-4 py-1 lg:px-2 lg:py-1",l),children:[jsxs("div",{className:"flex w-full items-center gap-2",children:[jsx("div",{className:"hideScrollbar min-w-0 flex-1 overflow-x-auto overflow-y-hidden",children:jsxs("div",{className:"flex min-h-8 items-stretch gap-x-2 lg:min-h-9",children:[jsx(Jn,{label:p,isSelected:t===null,onPress:u,showPulse:p===i}),jsx(fc,{}),e.map(d=>jsx(Jn,{label:d.category,isSelected:t===d.category,onPress:()=>s(d.category),badge:d.badge,showPulse:d.category===i},d.category))]})}),o&&jsx("div",{className:"flex-shrink-0",children:o})]}),t&&n.length>0&&jsx("div",{className:"hideScrollbar overflow-x-auto overflow-y-hidden flex items-center",children:jsxs("div",{className:"flex gap-x-1 pl-2 lg:w-full lg:gap-x-2",children:[jsx(es,{label:c("predict.categories.allMarkets"),isSelected:r===null,onPress:()=>a(null)}),n.map(d=>jsx(es,{label:d.label,icon:d.icon,isSelected:r===d.label,onPress:()=>a(d.label)},d.label))]})})]})}function Jn({label:e,isSelected:t,onPress:r,badge:n,showPulse:s}){return jsxs("button",{type:"button",onClick:r,className:cn("relative shrink-0 cursor-pointer whitespace-nowrap border-b p-1 text-base font-normal capitalize transition-colors",t?"border-primary/50 text-primary":"border-transparent text-neutral-500 hover:text-neutral-300"),children:[s?jsxs("span",{className:"flex items-center gap-x-1.5",children:[jsx("span",{className:"h-2 w-2 animate-pulse rounded-full bg-[rgb(240,68,56)]"}),jsx("span",{children:e})]}):e,n&&jsx("span",{className:"absolute -right-1 top-0 rounded bg-primary px-0.5 py-px text-[0.625rem] font-semibold leading-none text-neutral-950",children:n})]})}function fc(){return jsx("span",{className:"flex items-center text-neutral-600","aria-hidden":"true",children:"|"})}function es({label:e,icon:t,isSelected:r,onPress:n}){return jsxs("button",{type:"button",onClick:n,className:cn("flex shrink-0 items-center justify-center gap-x-1 min-w-14 rounded-2xl border px-2 py-1 text-sm font-medium uppercase transition-colors cursor-pointer",r?"border-transparent bg-primary text-black":"border-border/80 text-neutral-200 hover:bg-primary/10 hover:text-primary"),children:[t&&jsx("span",{className:cn("iconify size-4",t)}),e]})}function It({count:e=6}){return jsx("div",{className:"flex items-center gap-x-2",children:Array.from({length:e}).map((t,r)=>jsx(Skeleton,{className:"h-6 w-16 shrink-0 rounded"},r))})}function ss({onSelect:e,className:t}){let{data:r,isLoading:n}=Zn(),[s,a]=useState(null),[o,i]=useState(null),l=useCallback(d=>{if(a(d),i(null),!d)e?.({category:null,tags:null});else {let y=r.find(f=>f.category===d);e?.({category:d,tags:y?.tags??null});}},[r,e]),c=useCallback(d=>{if(i(d),d)e?.({category:s,tags:[d]});else {let y=r.find(f=>f.category===s);e?.({category:s,tags:y?.tags??null});}},[r,s,e]);if(n)return jsx(It,{});let p=(r.find(d=>d.category===s)?.tags??[]).map(d=>({label:d}));return jsx(Ot,{categories:r,selectedCategory:s,selectedTag:o,activeTags:p,onCategorySelect:l,onTagSelect:c,className:t})}function os(e={}){let{category:t,tags:r,...n}=e,s=!!t||!!r&&r.length>0,{data:a,isFetching:o,isError:i,error:l}=Ln({...t?{category:t}:{},...r&&r.length>0?{tags:r.join(",")}:{},isInitialized:true,status:"active"},{enabled:s}),c=useMemo(()=>{if(!s||!a?.series)return;let R=a.series.map(C=>C.ticker).slice(0,25);return R.length>0?R.join(","):void 0},[s,a]),u=useMemo(()=>({status:"active",withNestedMarkets:true,sort:"volume24h",order:"desc",limit:48,...n,...c!==void 0?{seriesTickers:c}:{}}),[n,c]),{data:p,isLoading:d,isFetching:y,isFetchingNextPage:f,isError:g,error:v,hasNextPage:h,fetchNextPage:b,refetch:x}=Mn(u),m=useMemo(()=>p?.pages.flatMap(R=>R.events)??[],[p]),P=s&&!a&&!i;return {data:m,isLoading:P||d,isFetching:o||P||y&&!f,isFetchingMore:f,isError:i||g,error:l??v,hasMore:h,fetchMore:b,refetch:x}}function vc({className:e}){return jsx(Skeleton,{className:cn("min-h-52 w-full rounded-xl border border-border/80 lg:min-h-72",e)})}function ot({count:e=12}){return jsx("div",{className:"@container w-full h-full",children:jsx("div",{className:"grid w-full grid-cols-1 gap-4 @[768px]:grid-cols-2 @[1024px]:grid-cols-3 @[1280px]:grid-cols-4",children:Array.from({length:e}).map((t,r)=>jsx(vc,{},r))})})}function gb(){return jsxs("div",{className:"flex h-full w-full flex-col gap-y-3",children:[jsx(It,{}),jsx("div",{className:"min-h-0 flex-1",children:jsx(ot,{})})]})}function as({value:e,showLabel:t=true}){let r=e/100;return jsx("div",{className:"flex-shrink-0 flex flex-col items-center",children:jsxs("div",{className:"relative w-16 h-12 lg:w-20 lg:h-14",children:[jsxs("svg",{className:"w-full h-full",viewBox:"0 0 100 70",children:[jsx("path",{d:"M 10 55 A 40 40 0 0 1 90 55",fill:"none",className:"stroke-default-200",strokeWidth:"6",strokeLinecap:"round"}),jsx("path",{d:"M 10 55 A 40 40 0 0 1 90 55",fill:"none",className:"stroke-primary",strokeWidth:"6",strokeLinecap:"round",strokeDasharray:`${r*125.6} 125.6`,style:{transition:"stroke-dasharray 0.5s ease-in-out"}})]}),t&&jsx("div",{className:"absolute inset-0 flex items-center justify-center pt-3 lg:pt-4",children:jsxs("span",{className:"text-sm font-bold text-foreground lg:text-base leading-none",children:[e.toFixed(0),"%"]})})]})})}function cs({event:e,onSelect:t,onSelectOutcome:r}){let{t:n}=useTranslation(),[s,a]=useState(null),o=e.markets||[],i=o.length>2?[...o].sort((C,V)=>Number(V.yesAsk??0)-Number(C.yesAsk??0)):o,l=i.filter(C=>C.status==="active"),c=i.length===1,u=c?i[0]:s,p=useMemo(()=>formatAmountUSDCompact((e.volume??0)/100),[e.volume]),d=C=>C.yesAsk?parseFloat(C.yesAsk)*100:null,y=C=>C.noAsk?parseFloat(C.noAsk)*100:null,f=C=>{let V=d(C),Q=y(C);return V!=null?Q==null&&V<=1?"< 1%":v(V):Q!=null?Q<=1?"> 99%":v(100-Q):"0%"},g=C=>{let V=d(C),Q=y(C);return Q!=null?V==null&&Q<=1?"< 1%":v(Q):V!=null?V<=1?"> 99%":v(100-V):"0%"},v=C=>C!=null?`${C.toFixed(0)}%`:"--",h=useMemo(()=>{let C=i.some(Q=>Q.status==="active");return i.every(Q=>Q.status==="closed"||Q.status==="determined")?{label:n("predict.event.status.closed"),color:"bg-danger-100/50 text-danger"}:C?{label:n("predict.event.status.live"),color:"bg-primary-100/50 text-primary"}:{label:n("predict.event.status.pending"),color:"bg-warning-100/50 text-warning"}},[i,n]),b=C=>{a(C);},x=()=>{a(null);},m=()=>{u&&r&&r(e,u,"yes");},P=()=>{u&&r&&r(e,u,"no");},w=()=>{t&&t(e);},O=l.slice(0,2),R=l.length>2;return jsxs("div",{className:"flex h-full w-full flex-col justify-between gap-y-1.5 rounded-xl border border-border bg-content1 p-3 transition-all duration-300 cursor-pointer hover:border-primary hover:ring-2 hover:ring-primary/20 focus-within:border-primary focus-within:bg-content2 focus-within:ring-2 focus-within:ring-primary/20 @5xl:gap-y-3 @5xl:p-4",onClick:w,children:[jsxs("div",{className:"flex w-full flex-1 flex-col gap-y-1.5 @5xl:gap-y-3",children:[jsxs("div",{className:"flex items-center gap-4",children:[jsx(Avatar,{src:e.imageUrl||void 0,name:e.title||"Event",radius:"md",className:"h-8 w-8 flex-shrink-0 transition-transform duration-300 group-hover:scale-110 @5xl:h-12 @5xl:w-12"}),jsx(StyledTooltip,{content:e.title,placement:"bottom",children:jsx("p",{className:"flex-1 min-w-0 h-10 @5xl:h-12 text-sm font-semibold @5xl:text-base line-clamp-2",children:e.title})}),c?jsx(as,{value:d(i[0])??50}):h.label!==n("predict.event.status.live")&&jsx("div",{className:`flex-shrink-0 flex items-center gap-x-2 rounded-lg px-2 py-1 text-sm @5xl:px-4 @5xl:py-2 ${h.color}`,children:jsx("span",{children:h.label})})]}),u&&!c&&jsxs("button",{type:"button",className:"flex min-h-9 w-full items-center justify-between gap-x-2 transition-opacity hover:cursor-pointer hover:opacity-80",onClick:C=>{C.stopPropagation(),x();},children:[jsx("span",{className:"text-left text-xs text-foreground @5xl:text-sm line-clamp-1",children:u.yesSubTitle}),jsxs("div",{className:"flex items-center gap-x-2",children:[jsx("span",{className:"text-sm font-semibold text-foreground @5xl:text-lg",children:f(u)}),jsx(ChevronUpIcon,{className:"w-3 h-3 text-default-500 @5xl:w-4 @5xl:h-4"})]})]}),!u&&!c&&O.length>0&&jsxs("div",{className:"flex w-full flex-col gap-y-0.5 text-xs @5xl:gap-y-1 @5xl:text-sm",children:[O.map(C=>jsxs("button",{type:"button",className:"flex min-h-8 w-full items-center justify-between gap-x-2 transition-opacity hover:cursor-pointer hover:opacity-80",onClick:V=>{V.stopPropagation(),b(C);},children:[jsx("span",{className:"text-left text-xs text-foreground @5xl:text-sm line-clamp-1",children:C.yesSubTitle}),jsxs("div",{className:"flex items-center gap-x-2",children:[jsx("span",{className:"text-xs text-foreground @5xl:text-base",children:f(C)}),jsxs("div",{className:"flex h-full items-center gap-x-3 rounded-lg p-1 @5xl:p-1.5 bg-gradient-to-r from-primary-50/20 via-primary-50/20 to-secondary-50/20",children:[jsx("span",{className:"text-primary",children:n("predict.market.yes")}),jsx("span",{className:"text-default-400",children:"/"}),jsx("span",{className:"text-secondary",children:n("predict.market.no")})]})]})]},C.ticker)),R&&jsx("span",{className:"text-xxs text-default-500 @5xl:text-xs",children:n("predict.event.moreMarkets",{count:l.length-2})})]}),u&&jsxs("div",{className:`flex items-center gap-x-2 text-sm @5xl:text-base ${c?"mt-3":""}`,children:[jsxs(Button,{color:"primary",fullWidth:true,className:"group/yes bg-primary-100 text-primary @3xl:!h-12 @3xl:!text-base",size:"sm",onPress:m,children:[jsx("span",{className:"group-hover/yes:hidden",children:n("predict.market.yes")}),jsx("span",{className:"hidden group-hover/yes:inline",children:f(u)})]}),jsxs(Button,{color:"secondary",fullWidth:true,className:"group/no bg-secondary-100 text-secondary @3xl:!h-12 @3xl:!text-base",size:"sm",onPress:P,children:[jsx("span",{className:"group-hover/no:hidden",children:n("predict.market.no")}),jsx("span",{className:"hidden group-hover/no:inline",children:g(u)})]})]})]}),!u||c?jsxs("div",{className:"flex items-center justify-between gap-x-2",children:[jsxs("button",{type:"button",className:"flex items-center gap-x-1 text-xxs text-default-600 hover:text-foreground @5xl:text-xs",onClick:C=>{C.stopPropagation(),w();},children:[jsx("span",{children:n("predict.event.showMore")}),jsx(ChevronRightIcon,{className:"h-3 w-3 @5xl:h-4 @5xl:w-4"})]}),jsxs("span",{className:"text-xxs text-default-600 @5xl:text-xs",children:[p," ",n("predict.event.volume")]})]}):jsxs("button",{type:"button",className:"flex items-center cursor-pointer gap-x-1 text-xxs text-default-600 hover:text-foreground @5xl:text-xs",onClick:C=>{C.stopPropagation(),x();},children:[jsx(ChevronLeftIcon,{className:"h-3 w-3 @5xl:h-4 @5xl:w-4"}),jsx("span",{children:n("predict.event.back")})]})]})}var Ic=640,Lc=768,ds=1024,Vc=1280,Bc=16,_c=192,Qc=228,Ac=244;function Dc(e){return e>=Vc?4:e>=ds?3:e>=Ic?2:1}function Uc(e){return e>=ds?Ac:e>=Lc?Qc:_c}function ps({events:e,hasMore:t=false,onFetchMore:r,onSelect:n,onSelectOutcome:s}){let a=useRef(null),{width:o=0,height:i=0}=useResizeObserver({ref:a}),l=Dc(o),c=Uc(o),u=Math.ceil(e.length/l)||0,p=t?u+1:u,d=useCallback(g=>g<u,[u]),y=useCallback(async()=>{r?.();},[r]),f=useInfiniteLoader({isRowLoaded:d,loadMoreRows:y,rowCount:p,threshold:3});return jsx("div",{ref:a,className:"@container w-full h-full",children:i>0&&jsx(List,{style:{height:i},onRowsRendered:f,rowComponent:Fc,rowCount:p,rowHeight:c,rowProps:{events:e,columnCount:l,dataRowCount:u,gap:Bc,onSelect:n,onSelectOutcome:s}})})}function Fc({index:e,style:t,events:r,columnCount:n,dataRowCount:s,gap:a,onSelect:o,onSelectOutcome:i}){if(e>=s)return jsx("div",{style:t,className:"flex justify-center items-start pt-4",children:jsx(Spinner,{size:"sm"})});let l=e*n,c=r.slice(l,l+n),u=n-c.length,p={display:"flex",gap:a,height:`calc(100% - ${a}px)`};return jsx("div",{style:t,children:jsxs("div",{style:p,children:[c.map(d=>jsx("div",{style:{flex:1,minWidth:0},children:jsx(cs,{event:d,onSelect:o,onSelectOutcome:i})},d.ticker)),u>0&&Array.from({length:u}).map((d,y)=>jsx("div",{style:{flex:1,minWidth:0}},`spacer-${y}`))]})})}function fs({onSelect:e,onSelectOutcome:t,...r}){let{data:n,hasMore:s,fetchMore:a,isFetching:o}=os({limit:48,...r});return o?jsx(ot,{count:48}):jsx(ps,{events:n,hasMore:s,onFetchMore:a,onSelect:e,onSelectOutcome:t})}function Kb({onSelect:e,onSelectOutcome:t}){let[r,n]=useState({category:null,tags:null}),s=useCallback(a=>{n(a);},[]);return jsxs("div",{className:"flex h-full w-full flex-col gap-y-3",children:[jsx(ss,{onSelect:s}),jsx("div",{className:"min-h-0 flex-1",children:jsx(fs,{category:r.category,tags:r.tags,onSelect:e,onSelectOutcome:t})})]})}var $c={Weather:["Daily temperature","Snow and rain","Climate change","Natural disasters","Hurricanes"],Companies:["IPOs","Product launches","KPIs","Elon Musk","CEOs","Layoffs"],Crypto:["BTC","15 min","Hourly","ETH","SOL","DOGE","Pre-Market","XRP","BNB","HYPE"],Economics:["Growth","Fed","Inflation","Oil and energy","Employment","Housing","Jobs & Economy","Bankruptcy & Defaults","GDP","Global Central Banks"],Elections:["Primaries","International elections"],Entertainment:["Music","Movies","Music charts","Television","Awards","Video games","Oscars","Rotten Tomatoes"],Financials:["S&P","Nasdaq","Daily","Metals","Treasuries","Oil","EUR/USD","USD/JPY","WTI"],Mentions:["Politicians","Earnings","Entertainment"],Politics:["Trump","Congress","International","SCOTUS & courts","Local","Recurring","Iran","House"],Science:["AI","Energy","Space"],Social:null,Sports:["Soccer","Basketball","Baseball","Football","Hockey","Golf","Tennis","Motorsport","Esports","Boxing","MMA","Rugby","Lacrosse","Mentions","Chess","Cricket","Aussie Rules","Darts"],World:null},ys=["Politics","Sports","Crypto","Economics","Financials","Elections","Entertainment","Companies","Science and Technology","Climate and Weather","Mentions","Social","World"],wr=(()=>{let e=t=>{let r=ys.indexOf(t);return r===-1?ys.length:r};return Object.entries($c).map(([t,r])=>({slug:t,label:t,tags:(r??[]).map(n=>({slug:n,label:n}))})).sort((t,r)=>e(t.slug)-e(r.slug))})();function zc(e){return e.map(t=>({category:t.label,tags:t.tags.map(r=>r.label)}))}function Gc(e){return e?e.tags.map(t=>({label:t.label,icon:t.icon})):[]}function xs({onSelect:e,trailing:t,className:r}){let[n,s]=useState(null),[a,o]=useState(null),i=useCallback(d=>{s(d),o(null),e?.({categorySlug:d,tagSlug:null});},[e]),l=useCallback(d=>{o(d),e?.({categorySlug:n,tagSlug:d});},[n,e]),c=zc(wr),u=wr.find(d=>d.slug===n),p=Gc(u);return jsx(Ot,{categories:c,selectedCategory:n,selectedTag:a,activeTags:p,onCategorySelect:i,onTagSelect:l,trailing:t,className:r})}var Tr={sortPreset:"volume",sortAsc:false,source:"dflow",timeRemaining:void 0,minVolume:void 0,minLiquidity:void 0};function Rr(e){let t=0;return e.source&&t++,e.timeRemaining&&t++,e.minVolume&&t++,e.minLiquidity&&t++,t}function bs({isOpen:e,onClose:t,value:r,onChange:n}){let{t:s}=useTranslation(),[a,o]=useState(r),i=useCallback(v=>{v?o(r):t();},[r,t]),l=useCallback(()=>{o(Tr);},[]),c=useCallback(()=>{n(a),t();},[a,n,t]),u=useCallback((v,h)=>{o(b=>({...b,[v]:h}));},[]),p=useMemo(()=>Rr(a),[a]),d=useMemo(()=>[{value:void 0,label:s("predict.filter.all")},{value:"polymarket",label:s("predict.platform.polymarket")},{value:"dflow",label:s("predict.platform.dflow")}],[s]),y=useMemo(()=>[{value:void 0,label:s("predict.filter.all")},{value:"1d",label:s("predict.filter.lessThanDay")},{value:"7d",label:s("predict.filter.lessThanWeek")},{value:"30d",label:s("predict.filter.lessThanMonth")}],[s]),f=useMemo(()=>[{value:void 0,label:s("predict.filter.all")},{value:"1000",label:">$1K"},{value:"10000",label:">$10K"},{value:"100000",label:">$100K"},{value:"1000000",label:">$1M"}],[s]),g=useMemo(()=>[{value:void 0,label:s("predict.filter.all")},{value:"1000",label:">$1K"},{value:"10000",label:">$10K"},{value:"100000",label:">$100K"},{value:"1000000",label:">$1M"}],[s]);return jsx(StyledModal,{isOpen:e,onOpenChange:i,size:"md",scrollBehavior:"inside",children:jsxs(ModalContent,{children:[jsx(ModalHeader,{className:"px-4 py-2",children:jsx("span",{className:"text-base font-semibold",children:s("predict.filter.title")})}),jsxs(ModalBody,{className:"flex flex-col gap-5",children:[jsx(Bt,{label:s("predict.filter.platform"),children:jsx(_t,{options:d,selected:a.source,onSelect:v=>u("source",v)})}),jsx(Bt,{label:s("predict.filter.timeRemaining"),children:jsx(_t,{options:y,selected:a.timeRemaining,onSelect:v=>u("timeRemaining",v)})}),jsx(Bt,{label:s("predict.filter.minVolume"),children:jsx(_t,{options:f,selected:a.minVolume,onSelect:v=>u("minVolume",v)})}),jsx(Bt,{label:s("predict.filter.minLiquidity"),children:jsx(_t,{options:g,selected:a.minLiquidity,onSelect:v=>u("minLiquidity",v)})})]}),jsx(ModalFooter,{className:"px-4",children:jsxs("div",{className:"w-full flex justify-between items-center",children:[jsx(Button,{variant:"light",color:"default",size:"sm",radius:"full",startContent:jsx(RefreshIcon,{width:16,height:16}),onPress:l,children:s("predict.filter.reset")}),jsxs(Button,{color:"primary",size:"sm",radius:"full",onPress:c,children:[s("predict.filter.showResults"),p>0&&jsxs("span",{className:"ml-1 text-xs opacity-80",children:["(",p,")"]})]})]})})]})})}function Bt({label:e,children:t}){return jsxs("div",{className:"flex flex-col gap-2.5",children:[jsx("span",{className:"text-sm font-semibold text-foreground",children:e}),t]})}function _t({options:e,selected:t,onSelect:r,allowDeselect:n=true}){return jsx("div",{className:"flex flex-wrap gap-2",children:e.map(s=>{let a=t===s.value;return jsx("button",{type:"button",onClick:()=>{r(a&&n?void 0:s.value);},className:cn("shrink-0 rounded-lg px-3 py-1.5 text-xs font-medium transition-colors duration-150 cursor-pointer border",a?"bg-primary/15 text-primary border-primary/40":"bg-content2 text-foreground/60 border-default-100 hover:bg-default-100 hover:text-foreground"),children:s.label},s.value??"__all")})})}var Cs={start_time:{sort_by:"created_at"},volume:{sort_by:"volume"},liquidity:{sort_by:"liquidity"},ending_soon:{sort_by:"end_at"}},Ps={start_time:"predict.sort.startTime",volume:"predict.sort.volume",liquidity:"predict.sort.liquidity",ending_soon:"predict.sort.endingSoon"},yu=["start_time","volume","liquidity","ending_soon"];function Es({sortPreset:e,onSortChange:t,sortAsc:r,onSortAscChange:n,onFilterPress:s,filterCount:a=0,className:o}){let{t:i}=useTranslation(),[l,c]=useState(false),u=useRef(null);useEffect(()=>{if(!l)return;let d=f=>{u.current&&!u.current.contains(f.target)&&c(false);},y=f=>{f.key==="Escape"&&c(false);};return document.addEventListener("mousedown",d),document.addEventListener("keydown",y),()=>{document.removeEventListener("mousedown",d),document.removeEventListener("keydown",y);}},[l]);let p=Ss[e];return jsxs("div",{className:cn("flex items-center gap-2",o),children:[jsxs("div",{ref:u,className:"relative flex shrink-0 items-center rounded-full border border-border",children:[jsxs("button",{type:"button",onClick:()=>c(d=>!d),className:"flex shrink-0 items-center gap-2 px-3 py-1.5 text-xs font-medium text-neutral transition-colors hover:text-primary/80 cursor-pointer",children:[jsx(p,{className:"size-[18px] shrink-0"}),jsx("span",{className:"whitespace-nowrap",children:i(Ps[e])})]}),jsx("div",{className:"h-6 w-px bg-border"}),jsx("button",{type:"button",onClick:()=>n(!r),className:"px-2.5 py-1.5 text-xs text-neutral transition-colors hover:text-primary/80 cursor-pointer",children:r?"\u2191":"\u2193"}),l&&jsx("div",{className:"absolute left-0 top-full z-20 mt-1 flex min-w-max flex-col gap-0.5 rounded-lg border border-border bg-content1 p-1 shadow-lg",children:yu.map(d=>{let y=Ss[d];return jsxs("button",{type:"button",onClick:()=>{t(d),c(false);},className:cn("flex w-full items-center gap-2 rounded px-2.5 py-1.5 text-xs font-medium transition-colors cursor-pointer",d===e?"bg-primary/10 text-primary":"text-neutral hover:bg-content2 hover:text-foreground"),children:[jsx(y,{className:"size-4 shrink-0"}),jsx("span",{children:i(Ps[d])})]},d)})})]}),jsx(StyledBadge,{content:a>0?a:void 0,color:"primary",size:"sm",isInvisible:a===0,children:jsxs("button",{type:"button",onClick:s,className:"flex shrink-0 items-center gap-2 rounded-full border border-border px-3 py-1.5 text-xs font-medium text-neutral transition-colors hover:text-primary/80 cursor-pointer",children:[jsx(FilterIcon,{className:"size-[18px]"}),jsx("span",{className:"whitespace-nowrap",children:i("predict.filter.title")})]})})]})}var Ss={start_time:CalendarIcon,volume:ChartLineIcon,liquidity:DropletIcon,ending_soon:TimerIcon};function Ts(e={}){let t=useMemo(()=>lr(e),[e.tagSlugSelection,e.limit,e.status,e.sort_by,e.sort_asc,e.source,e.with_markets]),{data:r,isLoading:n,isFetching:s,isFetchingNextPage:a,isError:o,error:i,hasNextPage:l,fetchNextPage:c,refetch:u}=Pn(t),p=useMemo(()=>r?.pages.flatMap(f=>f.items).filter(f=>f!=null)??[],[r]),d=useCallback(()=>{c();},[c]),y=useCallback(()=>{u();},[u]);return {data:p,isLoading:n,isFetching:s&&!a,isFetchingMore:a,isError:o,error:i??null,hasMore:l??false,fetchMore:d,refetch:y}}var Rs=3,Or={bg:"hsl(var(--heroui-primary) / 0.14)",text:"hsl(var(--heroui-primary))",shadow:"hsl(var(--heroui-primary) / 0.18)"},Bs={bg:"hsl(var(--heroui-secondary) / 0.14)",text:"hsl(var(--heroui-secondary))",shadow:"hsl(var(--heroui-secondary) / 0.18)"},Pu={bg:"rgba(239, 68, 68, 0.14)",text:"rgb(239, 68, 68)",shadow:"rgba(239, 68, 68, 0.18)"},lt=[{bg:"rgba(139,92,246,0.14)",text:"rgb(139,92,246)",shadow:"rgba(139,92,246,0.18)"},{bg:"rgba(34,197,94,0.14)",text:"rgb(34,197,94)",shadow:"rgba(34,197,94,0.18)"},{bg:"rgba(0,166,212,0.14)",text:"rgb(0,166,212)",shadow:"rgba(0,166,212,0.18)"},{bg:"rgba(194,120,32,0.14)",text:"rgb(194,120,32)",shadow:"rgba(194,120,32,0.18)"},{bg:"rgba(202,138,4,0.14)",text:"rgb(202,138,4)",shadow:"rgba(202,138,4,0.18)"},{bg:"rgba(236,72,153,0.14)",text:"rgb(236,72,153)",shadow:"rgba(236,72,153,0.18)"},{bg:"rgba(99,102,241,0.14)",text:"rgb(99,102,241)",shadow:"rgba(99,102,241,0.18)"},{bg:"rgba(244,114,82,0.14)",text:"rgb(244,114,82)",shadow:"rgba(244,114,82,0.18)"}];function Ns(e){let t=0;for(let r=0;r<e.length;r++)t=(t<<5)-t+e.charCodeAt(r)|0;return Math.abs(t)}function Su(e){let t=e.outcomes?.map(o=>o.label?.toLowerCase().trim()??"")??[];if(t.some(o=>o==="up")&&t.some(o=>o==="down"))return [Or,Pu];if(t.some(o=>o==="yes")&&t.some(o=>o==="no"))return [Or,Bs];let r=t[0]??"",n=t[1]??"",s=Ns(r)%lt.length,a=Ns(n)%lt.length;return a===s&&(a=(a+1)%lt.length),[lt[s],lt[a]]}function Cu(e){let t=e.outcomes?.[0];return t?t.best_ask??t.price??null:null}function _s(e){let t=Cu(e);return t!=null?Math.round(t*100):0}function Qs(e){return e<=1&&e>0?"< 1%":e>=99&&e<100?"> 99%":`${e}%`}function Os(e){let t=e.outcomes?.[0];return ((t?.best_ask??t?.price??0)*100).toFixed(1)}function Is(e){let t=e.outcomes?.[1];if(t){let s=t.best_ask??t.price??0;return Math.round(s*100).toString()}let r=e.outcomes?.[0],n=r?.best_ask??r?.price??0;return Math.round((1-n)*100).toString()}function Eu(e){let t=new Date(e).getTime()-Date.now();if(t<=0)return null;let r=Math.floor(t/864e5),n=Math.floor(t%864e5/36e5),s=Math.floor(t%36e5/6e4),a=[];return r>0&&a.push(`${r}d`),n>0&&a.push(`${n}h`),a.push(`${s}m`),a.join(" ")}var Mu=`
1
+ import {createContext,useContext,useMemo,useState,useRef,useEffect,useCallback}from'react';import {useQuery,useInfiniteQuery,useMutation,useQueries}from'@tanstack/react-query';import {useTranslation}from'@liberfi.io/i18n';import {cn,Skeleton,Avatar,StyledTooltip,ChevronUpIcon,Button,ChevronRightIcon,ChevronLeftIcon,Spinner,StyledModal,ModalContent,ModalHeader,ModalBody,ModalFooter,RefreshIcon,TimerIcon,DropletIcon,ChartLineIcon,CalendarIcon,StyledBadge,FilterIcon,Linkable,PolymarketIcon,KalshiIcon,useDisclosure,toast,Tabs,Tab,StyledNumberInput,Select,SelectSection,SelectItem,useScreen,Drawer,DrawerContent,DrawerBody,StyledTable,TableHeader,TableColumn,TableBody,TableRow,TableCell,TrashIcon,Chip,StyledInput,XCloseIcon,Kbd,SearchIcon,EmptyIcon,ChevronDownIcon}from'@liberfi.io/ui';import {jsxs,jsx,Fragment}from'react/jsx-runtime';import {List}from'react-window';import {useInfiniteLoader}from'react-window-infinite-loader';import {useResizeObserver,useCallbackRef}from'@liberfi.io/hooks';import {SOLANA_TOKENS,formatAmountUSDCompact,debounce,httpGet,httpPost}from'@liberfi.io/utils';import {useAuth,useWallets,useAuthCallback}from'@liberfi.io/wallet-connector';import Vr from'canvas-confetti';import {ChainNamespace,Chain}from'@liberfi.io/types';import {useWalletPortfoliosQuery}from'@liberfi.io/react';import {ResponsiveContainer,LineChart,CartesianGrid,XAxis,YAxis,Tooltip,Line,Customized}from'recharts';import {AsyncModal,useAsyncModal}from'@liberfi.io/ui-scaffold';import {useAtom}from'jotai';import {atomWithStorage}from'jotai/utils';typeof window<"u"&&(window.__LIBERFI_VERSION__=window.__LIBERFI_VERSION__||{},window.__LIBERFI_VERSION__["@liberfi.io/ui-predict"]="0.1.70");var ja="0.1.70";var Ct=createContext(null);function bn(){let e=useContext(Ct);if(!e)throw new Error("usePredictV2Context must be used within a PredictV2Provider");return e}function fe(){let{client:e}=bn();return e}function ei(e){return ["predict-v2","events",e??{}]}async function ti(e,t){return e.listEvents(t)}function _y(e,t={}){let r=fe();return useQuery({queryKey:ei(e),queryFn:()=>ti(r,e),...t})}var de=48,J=4,Et={ONE_MINUTE:1,ONE_HOUR:60,ONE_DAY:1440},S={ONE_DAY:"1d",ONE_WEEK:"1w",ONE_MONTH:"1m",ALL:"all"},le=S.ALL,He={[S.ONE_DAY]:Et.ONE_MINUTE,[S.ONE_WEEK]:Et.ONE_HOUR,[S.ONE_MONTH]:Et.ONE_HOUR,[S.ALL]:Et.ONE_DAY},Mt={[S.ONE_DAY]:300,[S.ONE_WEEK]:3600,[S.ONE_MONTH]:10800,[S.ALL]:1440*60},Ke={[S.ONE_DAY]:1440*60,[S.ONE_WEEK]:10080*60,[S.ONE_MONTH]:720*60*60,[S.ALL]:null},ar=1,Ay=1,Dy=1,Uy=99,qe={ONE_HOUR:"1h",SIX_HOURS:"6h",ONE_DAY:"1d",ONE_WEEK:"1w",MAX:"max"},Fy=qe.ONE_WEEK,Wy={[qe.ONE_HOUR]:60,[qe.SIX_HOURS]:60,[qe.ONE_DAY]:300,[qe.ONE_WEEK]:1800,[qe.MAX]:1800};function kn(e){if(e)return e.tagSlug??e.categorySlug??void 0}function ir(e={}){let{tagSlugSelection:t,limit:r=48,status:n="open",with_markets:s=true,source:a,sort_by:o,sort_asc:i}=e,l=kn(t);return {limit:r,status:n,with_markets:s,...a?{source:a}:{},...l?{tag_slug:l}:{},...o?{sort_by:o}:{},...i!==void 0?{sort_asc:i}:{}}}function lr(e){return ["predict-v2","events-infinite",e]}async function cr(e,t){return e.listEvents(t)}function ur(e,t){return ["predict-v2","event",e,t]}async function dr(e,t,r){return e.getEvent(t,r)}function wt(e,t={}){let r=fe();return useQuery({queryKey:ur(e.slug,e.source),queryFn:()=>dr(r,e.slug,e.source),enabled:!!e.slug,...t})}function Pn(e,t={}){let r=fe();return useInfiniteQuery({queryKey:lr(e),queryFn:({pageParam:n})=>cr(r,{...e,...n!==void 0?{cursor:n}:{}}),initialPageParam:void 0,getNextPageParam:n=>n.has_more&&n.next_cursor?n.next_cursor:void 0,...t})}function ai(e){return ["predict-v2","search",e]}function Sn(e,t){let r=fe(),n=useMemo(()=>({search:e.keyword,limit:e.limit??20,status:e.status??"open",source:e.source,with_markets:e.with_markets??false}),[e.keyword,e.limit,e.status,e.source,e.with_markets]);return useInfiniteQuery({queryKey:ai(n),queryFn:({pageParam:s})=>r.listEvents({...n,...s!==void 0?{cursor:s}:{}}),initialPageParam:void 0,getNextPageParam:s=>s.has_more&&s.next_cursor?s.next_cursor:void 0,enabled:t?.enabled??!!e.keyword})}function li(e,t){return ["predict-v2","market",e,t]}async function ci(e,t,r){return e.getMarket(t,r)}function lg(e,t={}){let r=fe();return useQuery({queryKey:li(e.slug,e.source),queryFn:()=>ci(r,e.slug,e.source),enabled:!!e.slug,...t})}var di={[S.ONE_DAY]:{daysBack:1,stepMs:300*1e3},[S.ONE_WEEK]:{daysBack:7,stepMs:1800*1e3},[S.ONE_MONTH]:{daysBack:30,stepMs:10800*1e3},[S.ALL]:{daysBack:90,stepMs:720*60*1e3}};function pi(e,t,r,n){let s=Date.now(),a=s-r*24*60*60*1e3,o=Math.floor((s-a)/n),i=e.split("").reduce((p,d)=>p+d.charCodeAt(0),0);function l(){return i=i*1664525+1013904223&4294967295,(i>>>0)/4294967295}let c=[],u=t;for(let p=o;p>=0;p--){c.unshift({timestamp:a+p*n,price:u});let d=(l()-.5)*.04;u=Math.min(.99,Math.max(.01,u-d));}return c}function Cn(e,t=S.ALL){return {series:useMemo(()=>{let{daysBack:n,stepMs:s}=di[t];return e.map(a=>{let i=a.outcomes.find(l=>l.label.toLowerCase()==="yes")?.price??a.outcomes[0]?.price??.5;return {marketSlug:a.slug,label:a.question,data:pi(a.slug,i,n,s)}})},[e,t]),isLoading:false}}var $e=createContext({});var Me=createContext(null);function En(){let e=useContext($e);if(!e)throw new Error("usePredictContext must be used within a PredictProvider");return e}function k(){let{client:e}=En();return e}function vi(e){return ["predict","events",e??{}]}async function pr(e,t){return await e.getEvents(t)}function Qg(e,t={}){let r=k();return useQuery({queryKey:vi(e),queryFn:async()=>pr(r,e),...t})}function hi(e){return ["predict","events","infinite",e??{}]}function Mn(e={},t={}){let r=k();return useInfiniteQuery({queryKey:hi(e),queryFn:async({pageParam:n})=>pr(r,{...e,...n!==void 0?{cursor:n}:{}}),initialPageParam:void 0,getNextPageParam:n=>n.cursor??void 0,...t})}function ki(e){return ["predict","event","byId",e.id,e.withNestedMarkets]}async function Pi(e,t){return await e.getEventById(t.id,t.withNestedMarkets)}function Tt(e,t={}){let r=k();return useQuery({queryKey:ki(e),queryFn:async()=>Pi(r,e),...t})}function Ci(e){return ["predict","markets",e??{}]}async function Ei(e,t){return await e.getMarkets(t)}function Gg(e,t={}){let r=k();return useQuery({queryKey:Ci(e),queryFn:async()=>Ei(r,e),...t})}function wi(e){return ["predict","market","byId",e.id]}async function Ti(e,t){return await e.getMarketById(t.id)}function Zg(e,t={}){let r=k();return useQuery({queryKey:wi(e),queryFn:async()=>Ti(r,e),...t})}function Ni(e){return ["predict","market","byMint",e]}async function Oi(e,t){return await e.getMarketByMint(t)}function rv(e,t={}){let r=k();return useQuery({queryKey:Ni(e),queryFn:async()=>Oi(r,e),...t})}function Li(e){return ["predict","markets","batch",e]}async function Vi(e,t){return await e.getMarketsBatch(t)}function av(e,t={}){let r=k();return useQuery({queryKey:Li(e),queryFn:async()=>Vi(r,e),enabled:!!(e.tickers?.length||e.mints?.length),...t})}function Bi(e){return ["predict","orderBook",e]}async function _i(e,t){return await e.getOrderbook(t)}function ze(e,t={}){let r=k();return useQuery({queryKey:Bi(e),queryFn:async()=>_i(r,e),...t})}function Qi(e){return ["predict","orderBook","byMint",e]}async function Ai(e,t){return await e.getOrderbookByMint(t)}function uv(e,t={}){let r=k();return useQuery({queryKey:Qi(e),queryFn:async()=>Ai(r,e),...t})}function Di(e){return ["predict","trades",e??{}]}async function Ui(e,t){return await e.getTrades(t)}function Rn(e,t={}){let r=k();return useQuery({queryKey:Di(e),queryFn:async()=>Ui(r,e),...t})}function Fi(e){return ["predict","trades","byMint",e]}async function Wi(e,t){return await e.getTradesByMint(t)}function fv(e,t={}){let r=k();return useQuery({queryKey:Fi(e),queryFn:async()=>Wi(r,e),...t})}function qi(e){return ["predict","onchainTrades","byWallet",e]}async function fr(e,t){return await e.getOnchainTradesByWallet(t)}function Nn(e,t={}){let r=k();return useQuery({queryKey:qi(e),queryFn:async()=>fr(r,e),...t})}function Hi(e){return ["predict","onchainTrades","byEvent",e]}async function yr(e,t){return await e.getOnchainTradesByEvent(t)}function xv(e,t={}){let r=k();return useQuery({queryKey:Hi(e),queryFn:async()=>yr(r,e),...t})}function Ki(e){return ["predict","onchainTrades","byMarket",e]}async function gr(e,t){return await e.getOnchainTradesByMarket(t)}function hv(e,t={}){let r=k();return useQuery({queryKey:Ki(e),queryFn:async()=>gr(r,e),...t})}function xr(e){return e.cursor??void 0}function $i(e){return ["predict","onchainTrades","byWallet","infinite",e]}function Cv(e,t={}){let r=k();return useInfiniteQuery({queryKey:$i(e),queryFn:async({pageParam:n})=>fr(r,{...e,...n!==void 0?{cursor:n}:{}}),initialPageParam:void 0,getNextPageParam:xr,...t})}function zi(e){return ["predict","onchainTrades","byEvent","infinite",e]}function Ev(e,t={}){let r=k();return useInfiniteQuery({queryKey:zi(e),queryFn:async({pageParam:n})=>yr(r,{...e,...n!==void 0?{cursor:n}:{}}),initialPageParam:void 0,getNextPageParam:xr,...t})}function Gi(e){return ["predict","onchainTrades","byMarket","infinite",e]}function Mv(e,t={}){let r=k();return useInfiniteQuery({queryKey:Gi(e),queryFn:async({pageParam:n})=>gr(r,{...e,...n!==void 0?{cursor:n}:{}}),initialPageParam:void 0,getNextPageParam:xr,...t})}function Yi(e){return ["predict","candlesticks","event",e]}async function ji(e,t){let{ticker:r,...n}=t;return await e.getEventCandlesticks(r,n)}function Nv(e,t={}){let r=k();return useQuery({queryKey:Yi(e),queryFn:async()=>ji(r,e),...t})}function rt(e){return ["predict","candlesticks","market",e]}async function nt(e,t){let{ticker:r,...n}=t;return await e.getMarketCandlesticks(r,n)}function br(e,t={}){let r=k();return useQuery({queryKey:rt(e),queryFn:async()=>nt(r,e),...t})}function Xi(e){return ["predict","candlesticks","market","byMint",e]}async function Zi(e,t){let{mintAddress:r,...n}=t;return await e.getMarketCandlesticksByMint(r,n)}function Ov(e,t={}){let r=k();return useQuery({queryKey:Xi(e),queryFn:async()=>Zi(r,e),...t})}var Iv=br;function Ji(e){return ["predict","forecast","percentileHistory",e]}async function el(e,t){return await e.getEventForecastPercentileHistory(t)}function _v(e,t={}){let r=k();return useQuery({queryKey:Ji(e),queryFn:async()=>el(r,e),...t})}function tl(e){return ["predict","forecast","percentileHistory","byMint",e]}async function rl(e,t){return await e.getEventForecastPercentileHistoryByMint(t)}function Qv(e,t={}){let r=k();return useQuery({queryKey:tl(e),queryFn:async()=>rl(r,e),...t})}function nl(e){return ["predict","liveData",e]}async function sl(e,t){return await e.getLiveData(t)}function Fv(e,t={}){let r=k();return useQuery({queryKey:nl(e),queryFn:async()=>sl(r,e),enabled:e.milestoneIds.length>0,...t})}function ol(e){return ["predict","liveData","byEvent",e]}async function al(e,t){return await e.getLiveDataByEvent(t)}function Wv(e,t={}){let r=k();return useQuery({queryKey:ol(e),queryFn:async()=>al(r,e),enabled:!!e.eventTicker,...t})}function il(e){return ["predict","liveData","byMint",e]}async function ll(e,t){return await e.getLiveDataByMint(t)}function qv(e,t={}){let r=k();return useQuery({queryKey:il(e),queryFn:async()=>ll(r,e),enabled:!!e.mintAddress,...t})}function cl(e){return ["predict","series",e??{}]}async function ul(e,t){return await e.getSeries(t)}function Ln(e,t={}){let r=k();return useQuery({queryKey:cl(e),queryFn:async()=>ul(r,e),...t})}function dl(e){return ["predict","series","byTicker",e]}async function pl(e,t){return await e.getSeriesByTicker(t)}function Vn(e,t={}){let r=k();return useQuery({queryKey:dl(e),queryFn:async()=>pl(r,e),...t})}function ml(){return ["predict","tags","byCategories"]}async function fl(e){return await e.getTagsByCategories()}function Pr(e={}){let t=k();return useQuery({queryKey:ml(),queryFn:async()=>fl(t),...e})}function yl(){return ["predict","filters","bySports"]}async function gl(e){return await e.getFiltersBySports()}function jv(e={}){let t=k();return useQuery({queryKey:yl(),queryFn:async()=>gl(t),...e})}var Xv=Pr;function xl(e){return ["predict","search",e]}async function hl(e,t){return await e.search(t)}function tx(e,t={}){let r=k();return useQuery({queryKey:xl(e),queryFn:async()=>hl(r,e),...t})}function kl(e){return ["predict","positions","byWallet",e]}async function Pl(e,t){return await e.getPositionsByWallet(t)}function _n(e,t={}){let r=k();return useQuery({queryKey:kl(e),queryFn:async()=>Pl(r,e),...t})}function lx(){let e=useContext(Me);if(!e)throw new Error("useUserPredictContext must be used within a UserPredictProvider");return e}function Qn(e){let t=useContext(Me);return useMemo(()=>t?{positions:t.positions.filter(n=>n.market?.ticker===e.ticker),isLoading:t.isLoading,isAvailable:true}:{positions:[],isLoading:false,isAvailable:false},[t,e.ticker])}function Tl(e){return ["predict","outcomeMints",e??{}]}async function Rl(e,t){return await e.getOutcomeMints(t)}function yx(e,t={}){let r=k();return useQuery({queryKey:Tl(e),queryFn:async()=>Rl(r,e),...t})}async function Nl(e,t){return await e.filterOutcomeMints(t)}function gx(e={}){let t=k();return useMutation({mutationFn:async r=>Nl(t,r),...e})}function Il(e){return ["predict","quote",e]}async function Ll(e,t){return await e.getQuote(t)}function bx(e,t={}){let r=k();return useQuery({queryKey:Il(e),queryFn:async()=>Ll(r,e),enabled:!!(e.inputMint&&e.outputMint&&e.amount>0),staleTime:1e4,gcTime:3e4,...t})}async function Vl(e,t){return await e.createSwap(t)}function Cx(e={}){let t=k();return useMutation({mutationFn:async r=>Vl(t,r),...e})}async function Bl(e,t){return await e.createSwapInstructions(t)}function Ex(e={}){let t=k();return useMutation({mutationFn:async r=>Bl(t,r),...e})}function _l(e){return ["predict","order",e]}async function Ql(e,t){return await e.getOrder(t)}function Un(e,t={}){let r=k();return useQuery({queryKey:_l(e),queryFn:async()=>Ql(r,e),enabled:!!(e.inputMint&&e.outputMint&&e.amount>0),staleTime:1e4,gcTime:3e4,...t})}function Al(e){return ["predict","order","status",e.signature]}async function Dl(e,t){return await e.getOrderStatus(t)}function Fn(e,t={}){let r=k();return useQuery({queryKey:Al(e),queryFn:async()=>Dl(r,e),enabled:!!e.signature,refetchInterval:t.refetchInterval??3e3,retry:false,...t})}function Wl(e){return ["predict","intent","quote",e]}async function ql(e,t){return await e.getIntentQuote(t)}function Ix(e,t={}){let r=k();return useQuery({queryKey:Wl(e),queryFn:async()=>ql(r,e),enabled:!!(e.inputMint&&e.outputMint&&e.amount>0),staleTime:1e4,gcTime:3e4,...t})}async function Hl(e,t){return await e.submitIntentSwap(t)}function Lx(e={}){let t=k();return useMutation({mutationFn:async r=>Hl(t,r),...e})}async function $l(e,t){return await e.initPredictionMarket(t)}function Qx(e={}){let t=k();return useMutation({mutationFn:async r=>$l(t,r),...e})}function zl(){return ["predict","tokens"]}async function Gl(e){return await e.getTokens()}function Fx(e={}){let t=k();return useQuery({queryKey:zl(),queryFn:async()=>Gl(t),staleTime:300*1e3,gcTime:1800*1e3,...e})}function Yl(){return ["predict","tokens","decimals"]}async function jl(e){return await e.getTokensWithDecimals()}function Wx(e={}){let t=k();return useQuery({queryKey:Yl(),queryFn:async()=>jl(t),staleTime:300*1e3,gcTime:1800*1e3,...e})}function Zl(){return ["predict","venues"]}async function Jl(e){return await e.getVenues()}function $x(e={}){let t=k();return useQuery({queryKey:Zl(),queryFn:async()=>Jl(t),staleTime:300*1e3,gcTime:1800*1e3,...e})}var st=class{ws=null;wsUrl;autoReconnect;reconnectIntervalBase;reconnectMaxInterval;pingInterval;status="disconnected";reconnectAttempts=0;reconnectTimeout=null;pingIntervalId=null;shouldReconnect=true;listeners={connect:[],disconnect:[],reconnecting:[],error:[],price:[],trade:[],orderbook:[],status:[],subscribed:[],unsubscribed:[]};subscriptions={prices:{all:false,tickers:new Set},trades:{all:false,tickers:new Set},orderbook:{all:false,tickers:new Set}};constructor(t){this.wsUrl=t.wsUrl,this.autoReconnect=t.autoReconnect??true,this.reconnectIntervalBase=t.reconnectIntervalBase??1e3,this.reconnectMaxInterval=t.reconnectMaxInterval??3e4,this.pingInterval=t.pingInterval??3e4,t.autoConnect!==false&&this.connect();}connect(){if(!(this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING))){this.shouldReconnect=true,this.setStatus("connecting");try{this.ws=new WebSocket(this.wsUrl),this.ws.onopen=()=>{this.reconnectAttempts=0,this.setStatus("connected"),this.emit("connect",void 0),this.restoreSubscriptions(),this.startPingInterval();},this.ws.onmessage=t=>{this.handleMessage(t.data);},this.ws.onerror=t=>{let r=new Error("WebSocket error");this.emit("error",r);},this.ws.onclose=t=>{this.stopPingInterval(),this.setStatus("disconnected"),this.emit("disconnect",{code:t.code,reason:t.reason}),this.shouldReconnect&&this.autoReconnect&&this.scheduleReconnect();};}catch(t){this.emit("error",t instanceof Error?t:new Error(String(t))),this.shouldReconnect&&this.autoReconnect&&this.scheduleReconnect();}}}disconnect(){this.shouldReconnect=false,this.stopPingInterval(),this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.ws&&(this.ws.close(),this.ws=null),this.setStatus("disconnected");}isConnected(){return this.ws!==null&&this.ws.readyState===WebSocket.OPEN}getStatus(){return this.status}subscribePrices(t,r){this.subscribeChannel("prices",t);let n=this.on("price",r);return ()=>{n(),this.unsubscribeChannel("prices",t);}}subscribeTrades(t,r){this.subscribeChannel("trades",t);let n=this.on("trade",r);return ()=>{n(),this.unsubscribeChannel("trades",t);}}subscribeOrderbook(t,r){this.subscribeChannel("orderbook",t);let n=this.on("orderbook",r);return ()=>{n(),this.unsubscribeChannel("orderbook",t);}}onStatusChange(t){return this.on("status",t)}on(t,r){return this.listeners[t].push(r),()=>{this.off(t,r);}}off(t,r){let n=this.listeners[t],s=n.indexOf(r);s!==-1&&n.splice(s,1);}removeAllListeners(t){if(t)this.listeners[t].length=0;else for(let r of Object.keys(this.listeners))this.listeners[r].length=0;}subscribeChannel(t,r){let n=this.subscriptions[t];if(r.all)n.all=true,n.tickers.clear();else if(r.tickers&&r.tickers.length>0){n.all=false;for(let s of r.tickers)n.tickers.add(s);}this.sendSubscription("subscribe",t,r);}unsubscribeChannel(t,r){let n=this.subscriptions[t];if(r.all)n.all=false,n.tickers.clear();else if(r.tickers&&r.tickers.length>0)for(let s of r.tickers)n.tickers.delete(s);this.sendSubscription("unsubscribe",t,r);}setStatus(t){this.status!==t&&(this.status=t,this.emit("status",t));}emit(t,r){let n=this.listeners[t];for(let s of n)try{s(r);}catch{}}send(t){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)return false;try{return this.ws.send(JSON.stringify(t)),!0}catch{return false}}sendSubscription(t,r,n){this.send({type:t,channel:r,all:n.all,tickers:n.tickers});}handleMessage(t){try{let r=JSON.parse(t);switch(r.type){case "ticker":this.emit("price",r);break;case "trade":this.emit("trade",r);break;case "orderbook":this.emit("orderbook",r);break;case "status":break;case "subscribed":this.emit("subscribed",{channel:r.channel,all:r.all,tickers:r.tickers});break;case "unsubscribed":this.emit("unsubscribed",{channel:r.channel,all:r.all,tickers:r.tickers});break;case "pong":break;case "error":this.emit("error",new Error(r.message));break;default:if("channel"in r){let n=r;switch(n.channel){case "prices":this.emit("price",n);break;case "trades":this.emit("trade",n);break;case "orderbook":this.emit("orderbook",n);break}}}}catch{}}scheduleReconnect(){if(this.reconnectTimeout)return;let t=Math.min(this.reconnectIntervalBase*Math.pow(2,this.reconnectAttempts),this.reconnectMaxInterval);this.setStatus("reconnecting"),this.emit("reconnecting",{attempt:this.reconnectAttempts+1,delay:t}),this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.reconnectAttempts++,this.connect();},t);}restoreSubscriptions(){for(let t of ["prices","trades","orderbook"]){let r=this.subscriptions[t];r.all?this.sendSubscription("subscribe",t,{all:true}):r.tickers.size>0&&this.sendSubscription("subscribe",t,{tickers:Array.from(r.tickers)});}}startPingInterval(){this.stopPingInterval(),this.pingIntervalId=setInterval(()=>{this.send({type:"ping"});},this.pingInterval);}stopPingInterval(){this.pingIntervalId&&(clearInterval(this.pingIntervalId),this.pingIntervalId=null);}};function Rt(e){return new st(e)}function Zx({wsEndpoint:e,autoConnect:t=true,autoReconnect:r=true,enabled:n=true}){let[s,a]=useState("disconnected"),[o,i]=useState(null),l=useRef(null);useEffect(()=>{if(!n){l.current&&(l.current.disconnect(),l.current=null),a("disconnected");return}let d=Rt({wsUrl:e,autoConnect:t,autoReconnect:r});l.current=d;let y=d.on("status",v=>{a(v);}),f=d.on("error",v=>{i(v);}),g=d.on("connect",()=>{i(null);});return ()=>{y(),f(),g(),d.disconnect(),l.current=null;}},[e,t,r,n]);let c=useCallback(()=>{l.current?.connect();},[]),u=useCallback(()=>{l.current?.disconnect();},[]);return {client:l.current,status:s,isConnected:s==="connected",connect:c,disconnect:u,error:o}}function rh(){let e=useContext($e);if(!e)throw new Error("useWsClient must be used within a PredictProvider");let{wsClient:t}=e,[r,n]=useState(t?.getStatus()??"disconnected");return useEffect(()=>{if(!t){n("disconnected");return}return n(t.getStatus()),t.onStatusChange(n)},[t]),{wsClient:t,wsStatus:r,isWsConnected:r==="connected"}}function oh({client:e,all:t=false,tickers:r=[],enabled:n=true,onUpdate:s}){let[a,o]=useState(new Map),[i,l]=useState(false),c=useRef(s);return useEffect(()=>{c.current=s;},[s]),useEffect(()=>{if(!e||!n){l(false);return}if(!t&&r.length===0)return;let u=t?{all:true}:{tickers:r},p=e.subscribePrices(u,d=>{o(y=>{let f=new Map(y);return f.set(d.market_ticker,{yesBid:d.yes_bid,yesAsk:d.yes_ask,noBid:d.no_bid,noAsk:d.no_ask,updatedAt:Date.now()}),f}),c.current?.(d);});return l(true),()=>{p(),l(false);}},[e,t,r.join(","),n]),{prices:a,isSubscribed:i}}function lh({client:e,all:t=false,tickers:r=[],enabled:n=true,maxHistory:s=100,onUpdate:a}){let[o,i]=useState([]),[l,c]=useState(false),u=useRef(a);useEffect(()=>{u.current=a;},[a]),useEffect(()=>{if(!e||!n){c(false);return}if(!t&&r.length===0)return;let d=t?{all:true}:{tickers:r},y=e.subscribeTrades(d,f=>{let g={tradeId:f.trade_id,marketTicker:f.market_ticker,price:f.price,count:f.count,yesPrice:f.yes_price,noPrice:f.no_price,takerSide:f.taker_side,createdTime:f.created_time};i(v=>{let h=[g,...v];return h.length>s?h.slice(0,s):h}),u.current?.(f);});return c(true),()=>{y(),c(false);}},[e,t,r.join(","),n,s]);let p=useCallback(()=>{i([]);},[]);return {trades:o,isSubscribed:l,clearHistory:p}}function dh({client:e,all:t=false,tickers:r=[],enabled:n=true,onUpdate:s}){let[a,o]=useState(new Map),[i,l]=useState(false),c=useRef(s);useEffect(()=>{c.current=s;},[s]),useEffect(()=>{if(!e||!n){l(false);return}if(!t&&r.length===0)return;let p=t?{all:true}:{tickers:r},d=e.subscribeOrderbook(p,y=>{o(f=>{let g=new Map(f);return g.set(y.market_ticker,{yesBids:y.yes_bids,yesAsks:y.yes_asks,noBids:y.no_bids,noAsks:y.no_asks,updatedAt:Date.now()}),g}),c.current?.(y);});return l(true),()=>{d(),l(false);}},[e,t,r.join(","),n]);let u=useCallback(p=>a.get(p),[a]);return {orderbooks:a,isSubscribed:i,getOrderbook:u}}var Xn=["Politics","Sports","Culture","Crypto","Climate","Economics","Mentions","Companies","Financials","Tech & Science"];function Zn(){let{data:e,isLoading:t,isError:r,error:n}=Pr();return {data:useMemo(()=>{if(!e?.tagsByCategories)return [];let a=o=>{let i=Xn.indexOf(o);return i===-1?Xn.length:i};return Object.entries(e.tagsByCategories).map(([o,i])=>({category:o,tags:i})).sort((o,i)=>a(o.category)-a(i.category))},[e]),isLoading:t,isError:r,error:n??null}}function Ot({categories:e,selectedCategory:t,selectedTag:r,activeTags:n,onCategorySelect:s,onTagSelect:a,trailing:o,pulsingTab:i="Trending",className:l}){let{t:c}=useTranslation(),u=useCallback(()=>{s(null);},[s]),p=c("predict.categories.trending");return jsxs("div",{className:cn("sticky top-0 z-30 flex w-full flex-col justify-between gap-2 px-4 py-1 lg:px-2 lg:py-1",l),children:[jsxs("div",{className:"flex w-full items-center gap-2",children:[jsx("div",{className:"hideScrollbar min-w-0 flex-1 overflow-x-auto overflow-y-hidden",children:jsxs("div",{className:"flex min-h-8 items-stretch gap-x-2 lg:min-h-9",children:[jsx(Jn,{label:p,isSelected:t===null,onPress:u,showPulse:p===i}),jsx(fc,{}),e.map(d=>jsx(Jn,{label:d.category,isSelected:t===d.category,onPress:()=>s(d.category),badge:d.badge,showPulse:d.category===i},d.category))]})}),o&&jsx("div",{className:"flex-shrink-0",children:o})]}),t&&n.length>0&&jsx("div",{className:"hideScrollbar overflow-x-auto overflow-y-hidden flex items-center",children:jsxs("div",{className:"flex gap-x-1 pl-2 lg:w-full lg:gap-x-2",children:[jsx(es,{label:c("predict.categories.allMarkets"),isSelected:r===null,onPress:()=>a(null)}),n.map(d=>jsx(es,{label:d.label,icon:d.icon,isSelected:r===d.label,onPress:()=>a(d.label)},d.label))]})})]})}function Jn({label:e,isSelected:t,onPress:r,badge:n,showPulse:s}){return jsxs("button",{type:"button",onClick:r,className:cn("relative shrink-0 cursor-pointer whitespace-nowrap border-b p-1 text-base font-normal capitalize transition-colors",t?"border-primary/50 text-primary":"border-transparent text-neutral-500 hover:text-neutral-300"),children:[s?jsxs("span",{className:"flex items-center gap-x-1.5",children:[jsx("span",{className:"h-2 w-2 animate-pulse rounded-full bg-[rgb(240,68,56)]"}),jsx("span",{children:e})]}):e,n&&jsx("span",{className:"absolute -right-1 top-0 rounded bg-primary px-0.5 py-px text-[0.625rem] font-semibold leading-none text-neutral-950",children:n})]})}function fc(){return jsx("span",{className:"flex items-center text-neutral-600","aria-hidden":"true",children:"|"})}function es({label:e,icon:t,isSelected:r,onPress:n}){return jsxs("button",{type:"button",onClick:n,className:cn("flex shrink-0 items-center justify-center gap-x-1 min-w-14 rounded-2xl border px-2 py-1 text-sm font-medium uppercase transition-colors cursor-pointer",r?"border-transparent bg-primary text-black":"border-border/80 text-neutral-200 hover:bg-primary/10 hover:text-primary"),children:[t&&jsx("span",{className:cn("iconify size-4",t)}),e]})}function It({count:e=6}){return jsx("div",{className:"flex items-center gap-x-2",children:Array.from({length:e}).map((t,r)=>jsx(Skeleton,{className:"h-6 w-16 shrink-0 rounded"},r))})}function ss({onSelect:e,className:t}){let{data:r,isLoading:n}=Zn(),[s,a]=useState(null),[o,i]=useState(null),l=useCallback(d=>{if(a(d),i(null),!d)e?.({category:null,tags:null});else {let y=r.find(f=>f.category===d);e?.({category:d,tags:y?.tags??null});}},[r,e]),c=useCallback(d=>{if(i(d),d)e?.({category:s,tags:[d]});else {let y=r.find(f=>f.category===s);e?.({category:s,tags:y?.tags??null});}},[r,s,e]);if(n)return jsx(It,{});let p=(r.find(d=>d.category===s)?.tags??[]).map(d=>({label:d}));return jsx(Ot,{categories:r,selectedCategory:s,selectedTag:o,activeTags:p,onCategorySelect:l,onTagSelect:c,className:t})}function os(e={}){let{category:t,tags:r,...n}=e,s=!!t||!!r&&r.length>0,{data:a,isFetching:o,isError:i,error:l}=Ln({...t?{category:t}:{},...r&&r.length>0?{tags:r.join(",")}:{},isInitialized:true,status:"active"},{enabled:s}),c=useMemo(()=>{if(!s||!a?.series)return;let R=a.series.map(C=>C.ticker).slice(0,25);return R.length>0?R.join(","):void 0},[s,a]),u=useMemo(()=>({status:"active",withNestedMarkets:true,sort:"volume24h",order:"desc",limit:48,...n,...c!==void 0?{seriesTickers:c}:{}}),[n,c]),{data:p,isLoading:d,isFetching:y,isFetchingNextPage:f,isError:g,error:v,hasNextPage:h,fetchNextPage:b,refetch:x}=Mn(u),m=useMemo(()=>p?.pages.flatMap(R=>R.events)??[],[p]),P=s&&!a&&!i;return {data:m,isLoading:P||d,isFetching:o||P||y&&!f,isFetchingMore:f,isError:i||g,error:l??v,hasMore:h,fetchMore:b,refetch:x}}function vc({className:e}){return jsx(Skeleton,{className:cn("min-h-52 w-full rounded-xl border border-border/80 lg:min-h-72",e)})}function ot({count:e=12}){return jsx("div",{className:"@container w-full h-full",children:jsx("div",{className:"grid w-full grid-cols-1 gap-4 @[768px]:grid-cols-2 @[1024px]:grid-cols-3 @[1280px]:grid-cols-4",children:Array.from({length:e}).map((t,r)=>jsx(vc,{},r))})})}function gb(){return jsxs("div",{className:"flex h-full w-full flex-col gap-y-3",children:[jsx(It,{}),jsx("div",{className:"min-h-0 flex-1",children:jsx(ot,{})})]})}function as({value:e,showLabel:t=true}){let r=e/100;return jsx("div",{className:"flex-shrink-0 flex flex-col items-center",children:jsxs("div",{className:"relative w-16 h-12 lg:w-20 lg:h-14",children:[jsxs("svg",{className:"w-full h-full",viewBox:"0 0 100 70",children:[jsx("path",{d:"M 10 55 A 40 40 0 0 1 90 55",fill:"none",className:"stroke-default-200",strokeWidth:"6",strokeLinecap:"round"}),jsx("path",{d:"M 10 55 A 40 40 0 0 1 90 55",fill:"none",className:"stroke-primary",strokeWidth:"6",strokeLinecap:"round",strokeDasharray:`${r*125.6} 125.6`,style:{transition:"stroke-dasharray 0.5s ease-in-out"}})]}),t&&jsx("div",{className:"absolute inset-0 flex items-center justify-center pt-3 lg:pt-4",children:jsxs("span",{className:"text-sm font-bold text-foreground lg:text-base leading-none",children:[e.toFixed(0),"%"]})})]})})}function cs({event:e,onSelect:t,onSelectOutcome:r}){let{t:n}=useTranslation(),[s,a]=useState(null),o=e.markets||[],i=o.length>2?[...o].sort((C,V)=>Number(V.yesAsk??0)-Number(C.yesAsk??0)):o,l=i.filter(C=>C.status==="active"),c=i.length===1,u=c?i[0]:s,p=useMemo(()=>formatAmountUSDCompact((e.volume??0)/100),[e.volume]),d=C=>C.yesAsk?parseFloat(C.yesAsk)*100:null,y=C=>C.noAsk?parseFloat(C.noAsk)*100:null,f=C=>{let V=d(C),Q=y(C);return V!=null?Q==null&&V<=1?"< 1%":v(V):Q!=null?Q<=1?"> 99%":v(100-Q):"0%"},g=C=>{let V=d(C),Q=y(C);return Q!=null?V==null&&Q<=1?"< 1%":v(Q):V!=null?V<=1?"> 99%":v(100-V):"0%"},v=C=>C!=null?`${C.toFixed(0)}%`:"--",h=useMemo(()=>{let C=i.some(Q=>Q.status==="active");return i.every(Q=>Q.status==="closed"||Q.status==="determined")?{label:n("predict.event.status.closed"),color:"bg-danger-100/50 text-danger"}:C?{label:n("predict.event.status.live"),color:"bg-primary-100/50 text-primary"}:{label:n("predict.event.status.pending"),color:"bg-warning-100/50 text-warning"}},[i,n]),b=C=>{a(C);},x=()=>{a(null);},m=()=>{u&&r&&r(e,u,"yes");},P=()=>{u&&r&&r(e,u,"no");},w=()=>{t&&t(e);},O=l.slice(0,2),R=l.length>2;return jsxs("div",{className:"flex h-full w-full flex-col justify-between gap-y-1.5 rounded-xl border border-border bg-content1 p-3 transition-all duration-300 cursor-pointer hover:border-primary hover:ring-2 hover:ring-primary/20 focus-within:border-primary focus-within:bg-content2 focus-within:ring-2 focus-within:ring-primary/20 @5xl:gap-y-3 @5xl:p-4",onClick:w,children:[jsxs("div",{className:"flex w-full flex-1 flex-col gap-y-1.5 @5xl:gap-y-3",children:[jsxs("div",{className:"flex items-center gap-4",children:[jsx(Avatar,{src:e.imageUrl||void 0,name:e.title||"Event",radius:"md",className:"h-8 w-8 flex-shrink-0 transition-transform duration-300 group-hover:scale-110 @5xl:h-12 @5xl:w-12"}),jsx(StyledTooltip,{content:e.title,placement:"bottom",children:jsx("p",{className:"flex-1 min-w-0 h-10 @5xl:h-12 text-sm font-semibold @5xl:text-base line-clamp-2",children:e.title})}),c?jsx(as,{value:d(i[0])??50}):h.label!==n("predict.event.status.live")&&jsx("div",{className:`flex-shrink-0 flex items-center gap-x-2 rounded-lg px-2 py-1 text-sm @5xl:px-4 @5xl:py-2 ${h.color}`,children:jsx("span",{children:h.label})})]}),u&&!c&&jsxs("button",{type:"button",className:"flex min-h-9 w-full items-center justify-between gap-x-2 transition-opacity hover:cursor-pointer hover:opacity-80",onClick:C=>{C.stopPropagation(),x();},children:[jsx("span",{className:"text-left text-xs text-foreground @5xl:text-sm line-clamp-1",children:u.yesSubTitle}),jsxs("div",{className:"flex items-center gap-x-2",children:[jsx("span",{className:"text-sm font-semibold text-foreground @5xl:text-lg",children:f(u)}),jsx(ChevronUpIcon,{className:"w-3 h-3 text-default-500 @5xl:w-4 @5xl:h-4"})]})]}),!u&&!c&&O.length>0&&jsxs("div",{className:"flex w-full flex-col gap-y-0.5 text-xs @5xl:gap-y-1 @5xl:text-sm",children:[O.map(C=>jsxs("button",{type:"button",className:"flex min-h-8 w-full items-center justify-between gap-x-2 transition-opacity hover:cursor-pointer hover:opacity-80",onClick:V=>{V.stopPropagation(),b(C);},children:[jsx("span",{className:"text-left text-xs text-foreground @5xl:text-sm line-clamp-1",children:C.yesSubTitle}),jsxs("div",{className:"flex items-center gap-x-2",children:[jsx("span",{className:"text-xs text-foreground @5xl:text-base",children:f(C)}),jsxs("div",{className:"flex h-full items-center gap-x-3 rounded-lg p-1 @5xl:p-1.5 bg-gradient-to-r from-primary-50/20 via-primary-50/20 to-secondary-50/20",children:[jsx("span",{className:"text-primary",children:n("predict.market.yes")}),jsx("span",{className:"text-default-400",children:"/"}),jsx("span",{className:"text-secondary",children:n("predict.market.no")})]})]})]},C.ticker)),R&&jsx("span",{className:"text-xxs text-default-500 @5xl:text-xs",children:n("predict.event.moreMarkets",{count:l.length-2})})]}),u&&jsxs("div",{className:`flex items-center gap-x-2 text-sm @5xl:text-base ${c?"mt-3":""}`,children:[jsxs(Button,{color:"primary",fullWidth:true,className:"group/yes bg-primary-100 text-primary @3xl:!h-12 @3xl:!text-base",size:"sm",onPress:m,children:[jsx("span",{className:"group-hover/yes:hidden",children:n("predict.market.yes")}),jsx("span",{className:"hidden group-hover/yes:inline",children:f(u)})]}),jsxs(Button,{color:"secondary",fullWidth:true,className:"group/no bg-secondary-100 text-secondary @3xl:!h-12 @3xl:!text-base",size:"sm",onPress:P,children:[jsx("span",{className:"group-hover/no:hidden",children:n("predict.market.no")}),jsx("span",{className:"hidden group-hover/no:inline",children:g(u)})]})]})]}),!u||c?jsxs("div",{className:"flex items-center justify-between gap-x-2",children:[jsxs("button",{type:"button",className:"flex items-center gap-x-1 text-xxs text-default-600 hover:text-foreground @5xl:text-xs",onClick:C=>{C.stopPropagation(),w();},children:[jsx("span",{children:n("predict.event.showMore")}),jsx(ChevronRightIcon,{className:"h-3 w-3 @5xl:h-4 @5xl:w-4"})]}),jsxs("span",{className:"text-xxs text-default-600 @5xl:text-xs",children:[p," ",n("predict.event.volume")]})]}):jsxs("button",{type:"button",className:"flex items-center cursor-pointer gap-x-1 text-xxs text-default-600 hover:text-foreground @5xl:text-xs",onClick:C=>{C.stopPropagation(),x();},children:[jsx(ChevronLeftIcon,{className:"h-3 w-3 @5xl:h-4 @5xl:w-4"}),jsx("span",{children:n("predict.event.back")})]})]})}var Ic=640,Lc=768,ds=1024,Vc=1280,Bc=16,_c=192,Qc=228,Ac=244;function Dc(e){return e>=Vc?4:e>=ds?3:e>=Ic?2:1}function Uc(e){return e>=ds?Ac:e>=Lc?Qc:_c}function ps({events:e,hasMore:t=false,onFetchMore:r,onSelect:n,onSelectOutcome:s}){let a=useRef(null),{width:o=0,height:i=0}=useResizeObserver({ref:a}),l=Dc(o),c=Uc(o),u=Math.ceil(e.length/l)||0,p=t?u+1:u,d=useCallback(g=>g<u,[u]),y=useCallback(async()=>{r?.();},[r]),f=useInfiniteLoader({isRowLoaded:d,loadMoreRows:y,rowCount:p,threshold:3});return jsx("div",{ref:a,className:"@container w-full h-full",children:i>0&&jsx(List,{style:{height:i},onRowsRendered:f,rowComponent:Fc,rowCount:p,rowHeight:c,rowProps:{events:e,columnCount:l,dataRowCount:u,gap:Bc,onSelect:n,onSelectOutcome:s}})})}function Fc({index:e,style:t,events:r,columnCount:n,dataRowCount:s,gap:a,onSelect:o,onSelectOutcome:i}){if(e>=s)return jsx("div",{style:t,className:"flex justify-center items-start pt-4",children:jsx(Spinner,{size:"sm"})});let l=e*n,c=r.slice(l,l+n),u=n-c.length,p={display:"flex",gap:a,height:`calc(100% - ${a}px)`};return jsx("div",{style:t,children:jsxs("div",{style:p,children:[c.map(d=>jsx("div",{style:{flex:1,minWidth:0},children:jsx(cs,{event:d,onSelect:o,onSelectOutcome:i})},d.ticker)),u>0&&Array.from({length:u}).map((d,y)=>jsx("div",{style:{flex:1,minWidth:0}},`spacer-${y}`))]})})}function fs({onSelect:e,onSelectOutcome:t,...r}){let{data:n,hasMore:s,fetchMore:a,isFetching:o}=os({limit:48,...r});return o?jsx(ot,{count:48}):jsx(ps,{events:n,hasMore:s,onFetchMore:a,onSelect:e,onSelectOutcome:t})}function Kb({onSelect:e,onSelectOutcome:t}){let[r,n]=useState({category:null,tags:null}),s=useCallback(a=>{n(a);},[]);return jsxs("div",{className:"flex h-full w-full flex-col gap-y-3",children:[jsx(ss,{onSelect:s}),jsx("div",{className:"min-h-0 flex-1",children:jsx(fs,{category:r.category,tags:r.tags,onSelect:e,onSelectOutcome:t})})]})}var $c={Weather:["Daily temperature","Snow and rain","Climate change","Natural disasters","Hurricanes"],Companies:["IPOs","Product launches","KPIs","Elon Musk","CEOs","Layoffs"],Crypto:["BTC","15 min","Hourly","ETH","SOL","DOGE","Pre-Market","XRP","BNB","HYPE"],Economics:["Growth","Fed","Inflation","Oil and energy","Employment","Housing","Jobs & Economy","Bankruptcy & Defaults","GDP","Global Central Banks"],Elections:["Primaries","International elections"],Entertainment:["Music","Movies","Music charts","Television","Awards","Video games","Oscars","Rotten Tomatoes"],Financials:["S&P","Nasdaq","Daily","Metals","Treasuries","Oil","EUR/USD","USD/JPY","WTI"],Mentions:["Politicians","Earnings","Entertainment"],Politics:["Trump","Congress","International","SCOTUS & courts","Local","Recurring","Iran","House"],Science:["AI","Energy","Space"],Social:null,Sports:["Soccer","Basketball","Baseball","Football","Hockey","Golf","Tennis","Motorsport","Esports","Boxing","MMA","Rugby","Lacrosse","Mentions","Chess","Cricket","Aussie Rules","Darts"],World:null},ys=["Politics","Sports","Crypto","Economics","Financials","Elections","Entertainment","Companies","Science and Technology","Climate and Weather","Mentions","Social","World"],Mr=(()=>{let e=t=>{let r=ys.indexOf(t);return r===-1?ys.length:r};return Object.entries($c).map(([t,r])=>({slug:t,label:t,tags:(r??[]).map(n=>({slug:n,label:n}))})).sort((t,r)=>e(t.slug)-e(r.slug))})();function zc(e){return e.map(t=>({category:t.label,tags:t.tags.map(r=>r.label)}))}function Gc(e){return e?e.tags.map(t=>({label:t.label,icon:t.icon})):[]}function xs({onSelect:e,trailing:t,className:r}){let[n,s]=useState(null),[a,o]=useState(null),i=useCallback(d=>{s(d),o(null),e?.({categorySlug:d,tagSlug:null});},[e]),l=useCallback(d=>{o(d),e?.({categorySlug:n,tagSlug:d});},[n,e]),c=zc(Mr),u=Mr.find(d=>d.slug===n),p=Gc(u);return jsx(Ot,{categories:c,selectedCategory:n,selectedTag:a,activeTags:p,onCategorySelect:i,onTagSelect:l,trailing:t,className:r})}var wr={sortPreset:"volume",sortAsc:false,source:"dflow",timeRemaining:void 0,minVolume:void 0,minLiquidity:void 0};function Tr(e){let t=0;return e.source&&t++,e.timeRemaining&&t++,e.minVolume&&t++,e.minLiquidity&&t++,t}function bs({isOpen:e,onClose:t,value:r,onChange:n}){let{t:s}=useTranslation(),[a,o]=useState(r),i=useCallback(v=>{v?o(r):t();},[r,t]),l=useCallback(()=>{o(wr);},[]),c=useCallback(()=>{n(a),t();},[a,n,t]),u=useCallback((v,h)=>{o(b=>({...b,[v]:h}));},[]),p=useMemo(()=>Tr(a),[a]),d=useMemo(()=>[{value:void 0,label:s("predict.filter.all")},{value:"polymarket",label:s("predict.platform.polymarket")},{value:"dflow",label:s("predict.platform.dflow")}],[s]),y=useMemo(()=>[{value:void 0,label:s("predict.filter.all")},{value:"1d",label:s("predict.filter.lessThanDay")},{value:"7d",label:s("predict.filter.lessThanWeek")},{value:"30d",label:s("predict.filter.lessThanMonth")}],[s]),f=useMemo(()=>[{value:void 0,label:s("predict.filter.all")},{value:"1000",label:">$1K"},{value:"10000",label:">$10K"},{value:"100000",label:">$100K"},{value:"1000000",label:">$1M"}],[s]),g=useMemo(()=>[{value:void 0,label:s("predict.filter.all")},{value:"1000",label:">$1K"},{value:"10000",label:">$10K"},{value:"100000",label:">$100K"},{value:"1000000",label:">$1M"}],[s]);return jsx(StyledModal,{isOpen:e,onOpenChange:i,size:"md",scrollBehavior:"inside",children:jsxs(ModalContent,{children:[jsx(ModalHeader,{className:"px-4 py-2",children:jsx("span",{className:"text-base font-semibold",children:s("predict.filter.title")})}),jsxs(ModalBody,{className:"flex flex-col gap-5",children:[jsx(Bt,{label:s("predict.filter.platform"),children:jsx(_t,{options:d,selected:a.source,onSelect:v=>u("source",v)})}),jsx(Bt,{label:s("predict.filter.timeRemaining"),children:jsx(_t,{options:y,selected:a.timeRemaining,onSelect:v=>u("timeRemaining",v)})}),jsx(Bt,{label:s("predict.filter.minVolume"),children:jsx(_t,{options:f,selected:a.minVolume,onSelect:v=>u("minVolume",v)})}),jsx(Bt,{label:s("predict.filter.minLiquidity"),children:jsx(_t,{options:g,selected:a.minLiquidity,onSelect:v=>u("minLiquidity",v)})})]}),jsx(ModalFooter,{className:"px-4",children:jsxs("div",{className:"w-full flex justify-between items-center",children:[jsx(Button,{variant:"light",color:"default",size:"sm",radius:"full",startContent:jsx(RefreshIcon,{width:16,height:16}),onPress:l,children:s("predict.filter.reset")}),jsxs(Button,{color:"primary",size:"sm",radius:"full",onPress:c,children:[s("predict.filter.showResults"),p>0&&jsxs("span",{className:"ml-1 text-xs opacity-80",children:["(",p,")"]})]})]})})]})})}function Bt({label:e,children:t}){return jsxs("div",{className:"flex flex-col gap-2.5",children:[jsx("span",{className:"text-sm font-semibold text-foreground",children:e}),t]})}function _t({options:e,selected:t,onSelect:r,allowDeselect:n=true}){return jsx("div",{className:"flex flex-wrap gap-2",children:e.map(s=>{let a=t===s.value;return jsx("button",{type:"button",onClick:()=>{r(a&&n?void 0:s.value);},className:cn("shrink-0 rounded-lg px-3 py-1.5 text-xs font-medium transition-colors duration-150 cursor-pointer border",a?"bg-primary/15 text-primary border-primary/40":"bg-content2 text-foreground/60 border-default-100 hover:bg-default-100 hover:text-foreground"),children:s.label},s.value??"__all")})})}var Cs={start_time:{sort_by:"created_at"},volume:{sort_by:"volume"},liquidity:{sort_by:"liquidity"},ending_soon:{sort_by:"end_at"}},Ps={start_time:"predict.sort.startTime",volume:"predict.sort.volume",liquidity:"predict.sort.liquidity",ending_soon:"predict.sort.endingSoon"},yu=["start_time","volume","liquidity","ending_soon"];function Es({sortPreset:e,onSortChange:t,sortAsc:r,onSortAscChange:n,onFilterPress:s,filterCount:a=0,className:o}){let{t:i}=useTranslation(),[l,c]=useState(false),u=useRef(null);useEffect(()=>{if(!l)return;let d=f=>{u.current&&!u.current.contains(f.target)&&c(false);},y=f=>{f.key==="Escape"&&c(false);};return document.addEventListener("mousedown",d),document.addEventListener("keydown",y),()=>{document.removeEventListener("mousedown",d),document.removeEventListener("keydown",y);}},[l]);let p=Ss[e];return jsxs("div",{className:cn("flex items-center gap-2",o),children:[jsxs("div",{ref:u,className:"relative flex shrink-0 items-center rounded-full border border-border",children:[jsxs("button",{type:"button",onClick:()=>c(d=>!d),className:"flex shrink-0 items-center gap-2 px-3 py-1.5 text-xs font-medium text-neutral transition-colors hover:text-primary/80 cursor-pointer",children:[jsx(p,{className:"size-[18px] shrink-0"}),jsx("span",{className:"whitespace-nowrap",children:i(Ps[e])})]}),jsx("div",{className:"h-6 w-px bg-border"}),jsx("button",{type:"button",onClick:()=>n(!r),className:"px-2.5 py-1.5 text-xs text-neutral transition-colors hover:text-primary/80 cursor-pointer",children:r?"\u2191":"\u2193"}),l&&jsx("div",{className:"absolute left-0 top-full z-20 mt-1 flex min-w-max flex-col gap-0.5 rounded-lg border border-border bg-content1 p-1 shadow-lg",children:yu.map(d=>{let y=Ss[d];return jsxs("button",{type:"button",onClick:()=>{t(d),c(false);},className:cn("flex w-full items-center gap-2 rounded px-2.5 py-1.5 text-xs font-medium transition-colors cursor-pointer",d===e?"bg-primary/10 text-primary":"text-neutral hover:bg-content2 hover:text-foreground"),children:[jsx(y,{className:"size-4 shrink-0"}),jsx("span",{children:i(Ps[d])})]},d)})})]}),jsx(StyledBadge,{content:a>0?a:void 0,color:"primary",size:"sm",isInvisible:a===0,children:jsxs("button",{type:"button",onClick:s,className:"flex shrink-0 items-center gap-2 rounded-full border border-border px-3 py-1.5 text-xs font-medium text-neutral transition-colors hover:text-primary/80 cursor-pointer",children:[jsx(FilterIcon,{className:"size-[18px]"}),jsx("span",{className:"whitespace-nowrap",children:i("predict.filter.title")})]})})]})}var Ss={start_time:CalendarIcon,volume:ChartLineIcon,liquidity:DropletIcon,ending_soon:TimerIcon};function Ts(e={}){let t=useMemo(()=>ir(e),[e.tagSlugSelection,e.limit,e.status,e.sort_by,e.sort_asc,e.source,e.with_markets]),{data:r,isLoading:n,isFetching:s,isFetchingNextPage:a,isError:o,error:i,hasNextPage:l,fetchNextPage:c,refetch:u}=Pn(t),p=useMemo(()=>r?.pages.flatMap(f=>f.items).filter(f=>f!=null)??[],[r]),d=useCallback(()=>{c();},[c]),y=useCallback(()=>{u();},[u]);return {data:p,isLoading:n,isFetching:s&&!a,isFetchingMore:a,isError:o,error:i??null,hasMore:l??false,fetchMore:d,refetch:y}}var Rs=3,Nr={bg:"hsl(var(--heroui-primary) / 0.14)",text:"hsl(var(--heroui-primary))",shadow:"hsl(var(--heroui-primary) / 0.18)"},Bs={bg:"hsl(var(--heroui-secondary) / 0.14)",text:"hsl(var(--heroui-secondary))",shadow:"hsl(var(--heroui-secondary) / 0.18)"},Pu={bg:"rgba(239, 68, 68, 0.14)",text:"rgb(239, 68, 68)",shadow:"rgba(239, 68, 68, 0.18)"},lt=[{bg:"rgba(139,92,246,0.14)",text:"rgb(139,92,246)",shadow:"rgba(139,92,246,0.18)"},{bg:"rgba(34,197,94,0.14)",text:"rgb(34,197,94)",shadow:"rgba(34,197,94,0.18)"},{bg:"rgba(0,166,212,0.14)",text:"rgb(0,166,212)",shadow:"rgba(0,166,212,0.18)"},{bg:"rgba(194,120,32,0.14)",text:"rgb(194,120,32)",shadow:"rgba(194,120,32,0.18)"},{bg:"rgba(202,138,4,0.14)",text:"rgb(202,138,4)",shadow:"rgba(202,138,4,0.18)"},{bg:"rgba(236,72,153,0.14)",text:"rgb(236,72,153)",shadow:"rgba(236,72,153,0.18)"},{bg:"rgba(99,102,241,0.14)",text:"rgb(99,102,241)",shadow:"rgba(99,102,241,0.18)"},{bg:"rgba(244,114,82,0.14)",text:"rgb(244,114,82)",shadow:"rgba(244,114,82,0.18)"}];function Ns(e){let t=0;for(let r=0;r<e.length;r++)t=(t<<5)-t+e.charCodeAt(r)|0;return Math.abs(t)}function Su(e){let t=e.outcomes?.map(o=>o.label?.toLowerCase().trim()??"")??[];if(t.some(o=>o==="up")&&t.some(o=>o==="down"))return [Nr,Pu];if(t.some(o=>o==="yes")&&t.some(o=>o==="no"))return [Nr,Bs];let r=t[0]??"",n=t[1]??"",s=Ns(r)%lt.length,a=Ns(n)%lt.length;return a===s&&(a=(a+1)%lt.length),[lt[s],lt[a]]}function Cu(e){let t=e.outcomes?.[0];return t?t.best_ask??t.price??null:null}function _s(e){let t=Cu(e);return t!=null?Math.round(t*100):0}function Qs(e){return e<=1&&e>0?"< 1%":e>=99&&e<100?"> 99%":`${e}%`}function Os(e){let t=e.outcomes?.[0];return ((t?.best_ask??t?.price??0)*100).toFixed(1)}function Is(e){let t=e.outcomes?.[1];if(t){let s=t.best_ask??t.price??0;return Math.round(s*100).toString()}let r=e.outcomes?.[0],n=r?.best_ask??r?.price??0;return Math.round((1-n)*100).toString()}function Eu(e){let t=new Date(e).getTime()-Date.now();if(t<=0)return null;let r=Math.floor(t/864e5),n=Math.floor(t%864e5/36e5),s=Math.floor(t%36e5/6e4),a=[];return r>0&&a.push(`${r}d`),n>0&&a.push(`${n}h`),a.push(`${s}m`),a.join(" ")}var Mu=`
2
2
  .badge-shine { position: relative; overflow: hidden; }
3
3
  .badge-shine::after {
4
4
  content: "";
@@ -16,6 +16,6 @@ import {createContext,useContext,useMemo,useState,useRef,useEffect,useCallback}f
16
16
  60% { transform: translate(200%); }
17
17
  100% { transform: translate(200%); }
18
18
  }
19
- `;function As({event:e,href:t,LinkComponent:r,onSelect:n,onSelectOutcome:s,onHover:a}){let[o,i]=useState(null),l=e.markets??[],u=useMemo(()=>l.length>2?[...l].sort((m,P)=>(P.outcomes?.[0]?.price??0)-(m.outcomes?.[0]?.price??0)):l,[l]).filter(m=>m.status==="open"),p=u.length===1,d=u.slice(0,Rs),y=u.length-Rs,f=useMemo(()=>`$${Math.round(e.volume??0).toLocaleString("en-US")}`,[e.volume]),g=o?u.find(m=>m.slug===o)??null:null,v=!!g||p,h=()=>{v||n?.(e);},b=m=>{m.stopPropagation(),g&&(m.preventDefault(),i(null));},x=m=>{m.stopPropagation(),t||(m.preventDefault(),n?.(e));};return jsxs("div",{className:cn("group flex h-full w-full flex-col rounded-xl","min-h-52 border border-border/90 bg-background p-3","lg:min-h-72 lg:max-w-md lg:p-4","gap-y-1.5 lg:gap-y-4","transition duration-300","hover:border-primary/40 hover:shadow-card-glow","focus-within:border-primary/40 focus-within:shadow-card-glow",!v&&"cursor-pointer"),onMouseEnter:()=>a?.(e),onClick:h,children:[jsx("style",{children:Mu}),jsx(wu,{event:e,href:v?void 0:t,LinkComponent:r,onClick:b,isExpanded:v}),jsx("div",{className:"flex flex-1 flex-col",children:p?jsx(Bu,{market:u[0],event:e,formattedVolume:f,href:t,LinkComponent:r,onSelect:n,onSelectOutcome:s}):g?jsx(_u,{market:g,event:e,onCollapse:()=>i(null),onSelectOutcome:s}):jsx(Lu,{displayedMarkets:d,moreCount:y,formattedVolume:f,source:e.source,href:t,LinkComponent:r,onMarketClick:m=>i(m.slug),onShowMore:x})})]})}function wu({event:e,href:t,LinkComponent:r,onClick:n,isExpanded:s}){let a=e.start_at?Eu(e.start_at):null,o=jsxs(Fragment,{children:[jsx(Avatar,{src:e.image_url||void 0,name:e.title||"Event",radius:"lg",className:"h-8 w-8 flex-shrink-0 transition-transform duration-300 group-hover/header:scale-110 lg:h-12 lg:w-12",classNames:{base:"bg-transparent"}}),jsxs("div",{className:"flex min-w-0 flex-1 flex-col justify-center gap-y-0.5",children:[jsx("p",{className:cn("min-w-0 text-sm font-semibold leading-snug text-slate-200 line-clamp-2 lg:text-base",s&&"group-hover/header:text-neutral-400"),children:e.title}),a&&jsxs("span",{className:"text-[10px] leading-4 text-neutral-500",children:["Live in ",a]})]}),jsx(Ru,{event:e})]}),i="group/header flex items-center gap-x-2 lg:gap-x-4 w-full text-left cursor-pointer";return t?jsx(Linkable,{href:t,LinkComponent:r,className:i,onClick:n,children:o}):jsx("button",{type:"button",className:i,onClick:n,children:o})}function Tu(e){let t=[];if(e.status==="closed")return t.push({kind:"closed"}),t.slice(0,2);let r=e.tags?.some(s=>s.label?.toLowerCase()==="crypto"),n=e.tags?.some(s=>s.label?.toLowerCase()==="live");if(r&&e.end_at){let s=new Date(e.end_at).getTime()-Date.now(),a=300*1e3,o=900*1e3;if(s>0&&s<=o){let i=s<=a?"#ef4444":"#f59e0b";t.push({kind:"crypto-short",label:s<=a?"5m":"15m",color:i});}}return n&&t.push({kind:"live"}),t.slice(0,2)}function Ru({event:e}){let t=useMemo(()=>Tu(e),[e]);return t.length===0?null:jsx("div",{className:"flex flex-shrink-0 flex-col items-end gap-1",children:t.map((r,n)=>{switch(r.kind){case "live":return jsx(Nu,{},n);case "crypto-short":return jsx(Ou,{label:r.label,color:r.color},n);case "closed":return jsx(Iu,{},n)}})})}function Nu(){let{t:e}=useTranslation();return jsxs("span",{className:"badge-shine relative inline-flex items-center gap-1 overflow-hidden rounded-md bg-[rgb(240,68,56)]/10 px-1.5 py-0.5 text-xs font-semibold text-[rgb(240,68,56)]",children:[jsx("span",{className:"h-2 w-2 animate-pulse rounded-full bg-current"}),e("predict.event.status.live")]})}function Ou({label:e,color:t}){return jsxs("span",{className:"badge-shine relative inline-flex items-center gap-1 overflow-hidden rounded-md px-1.5 py-0.5 text-xs font-semibold",style:{backgroundColor:`${t}26`,color:t},children:[jsx(TimerIcon,{className:"size-3 shrink-0"}),e]})}function Iu(){let{t:e}=useTranslation();return jsx("span",{className:"inline-flex items-center rounded-md bg-neutral-800/80 px-1.5 py-0.5 text-xs font-semibold text-neutral-400",children:e("predict.event.status.closed")})}function Lu({displayedMarkets:e,moreCount:t,formattedVolume:r,source:n,href:s,LinkComponent:a,onMarketClick:o,onShowMore:i}){let{t:l}=useTranslation();return jsxs(Fragment,{children:[e.length>0&&jsx("div",{className:"flex w-full flex-1 flex-col gap-y-0.5 lg:gap-y-2",children:e.map(c=>{let u=_s(c);return jsxs("button",{type:"button",className:"flex h-9 w-full items-center justify-between gap-x-2 transition-opacity hover:cursor-pointer hover:opacity-80",onClick:p=>{p.stopPropagation(),o(c);},children:[jsx("span",{className:"min-w-0 flex-1 text-left text-xs text-slate-200 line-clamp-1 lg:text-sm",children:c.outcomes?.[0]?.label??c.question}),jsxs("div",{className:"flex items-center gap-x-2",children:[jsx("span",{className:"text-sm font-semibold text-slate-200 lg:text-lg",children:Qs(u)}),jsx(Vu,{})]})]},c.slug)})}),jsxs("div",{className:"mt-auto flex items-center justify-between pt-3",children:[t>0?jsxs(Linkable,{href:s,LinkComponent:a,as:"button",className:"flex items-center gap-1 text-[10px] font-normal text-neutral-500 transition-colors hover:text-slate-200 cursor-pointer lg:text-xs",onClick:i,children:[l("predict.event.showMore"),jsx(Us,{className:"h-3 w-3"})]}):jsx("div",{}),jsxs("span",{className:"inline-flex items-center gap-x-1.5 text-[10px] font-normal text-neutral-500 lg:text-xs",children:[r," ",l("predict.event.volume"),jsx(Fs,{source:n})]})]})]})}function Ls({bgColor:e,textColor:t,shadowColor:r,onClick:n,children:s}){return jsx("button",{type:"button",className:"flex h-12 flex-1 w-full items-center justify-center gap-x-1 overflow-hidden rounded-lg p-3 text-base font-normal hover:cursor-pointer will-change-transform [-webkit-tap-highlight-color:transparent]",style:{backgroundColor:e,color:t,"--shadow-color":r,"--shadow-offset":"4px",boxShadow:"inset 0 -1px 0 rgba(255,255,255,0.08), 0 var(--shadow-offset, 4px) 0 var(--shadow-color, rgba(0,0,0,0.22))",transition:"transform .12s, box-shadow .12s, opacity .14s"},onMouseEnter:i=>{let l=i.currentTarget;l.style.setProperty("--shadow-offset","2px"),l.style.transform="translateY(2px)";},onMouseLeave:i=>{let l=i.currentTarget;l.style.setProperty("--shadow-offset","4px"),l.style.transform="translateY(0px)";},onClick:n,children:s})}function Ds({market:e,event:t,onSelectOutcome:r,dynamicColors:n=false,labelFormat:s="action"}){let{t:a}=useTranslation(),[o,i]=n?Su(e):[Or,Bs],l=s==="label"?`${e.outcomes?.[0]?.label??"Yes"} ${Os(e)}\xA2`:a("predict.market.action.yes",{price:Os(e)}),c=s==="label"?`${e.outcomes?.[1]?.label??"No"} ${Is(e)}\xA2`:a("predict.market.action.no",{price:Is(e)});return jsxs("div",{className:"flex gap-2",children:[jsx(Ls,{bgColor:o.bg,textColor:o.text,shadowColor:o.shadow,onClick:u=>{u.stopPropagation(),r?.(t,e,"yes");},children:l}),jsx(Ls,{bgColor:i.bg,textColor:i.text,shadowColor:i.shadow,onClick:u=>{u.stopPropagation(),r?.(t,e,"no");},children:c})]})}function Vu(){let{t:e}=useTranslation();return jsxs("span",{className:"inline-flex h-7 w-[85px] items-center justify-center gap-x-3 rounded-lg p-1.5 text-xs font-semibold flex-shrink-0 bg-gradient-to-r from-primary/15 to-secondary/15 lg:h-9 lg:w-24 lg:gap-x-4 lg:p-2 lg:text-sm",children:[jsx("span",{className:"text-primary",children:e("predict.market.yes")}),jsx("span",{className:"text-neutral-400",children:"/"}),jsx("span",{className:"text-secondary",children:e("predict.market.no")})]})}function Bu({market:e,event:t,formattedVolume:r,href:n,LinkComponent:s,onSelect:a,onSelectOutcome:o}){let{t:i}=useTranslation();return jsxs(Fragment,{children:[jsx("div",{className:"flex-1",children:jsx(Ds,{market:e,event:t,onSelectOutcome:o,dynamicColors:true,labelFormat:"label"})}),jsxs("div",{className:"mt-auto flex items-center justify-between pt-3",children:[jsxs(Linkable,{href:n,LinkComponent:s,as:"button",className:"flex items-center gap-1 text-[10px] font-normal text-neutral-500 transition-colors hover:text-slate-200 cursor-pointer lg:text-xs",onClick:c=>{c.stopPropagation(),n||(c.preventDefault(),a?.(t));},children:[i("predict.event.viewEvent"),jsx(Us,{className:"h-3 w-3"})]}),jsxs("span",{className:"inline-flex items-center gap-x-1.5 text-[10px] font-normal text-neutral-500 lg:text-xs",children:[r," ",i("predict.event.volume"),jsx(Fs,{source:t.source})]})]})]})}function _u({market:e,event:t,onCollapse:r,onSelectOutcome:n}){let{t:s}=useTranslation(),a=_s(e);return jsxs(Fragment,{children:[jsxs("div",{className:"flex-1",children:[jsxs("button",{type:"button",className:"flex h-9 w-full items-center justify-between cursor-pointer",onClick:o=>{o.stopPropagation(),r();},children:[jsx("span",{className:"min-w-0 flex-1 text-left text-xs text-slate-200 lg:text-sm",children:e.outcomes?.[0]?.label??e.question}),jsxs("div",{className:"flex items-center gap-x-1 flex-shrink-0",children:[jsx("span",{className:"text-sm font-semibold text-slate-200 lg:text-lg",children:Qs(a)}),jsx(ChevronUpIcon,{className:"h-4 w-4 text-neutral-400"})]})]}),jsx("div",{className:"mt-3",children:jsx(Ds,{market:e,event:t,onSelectOutcome:n,labelFormat:"action"})})]}),jsxs("button",{type:"button",className:"mt-auto flex items-center gap-x-1 pt-4 text-[10px] font-normal text-neutral-500 transition-colors hover:text-slate-200 cursor-pointer lg:text-xs",onClick:o=>{o.stopPropagation(),r();},children:[jsx(Qu,{className:"h-3 w-3"}),s("predict.event.back")]})]})}function Us({className:e}){return jsx("svg",{viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:e,children:jsx("path",{d:"M4.5 2.5L8 6l-3.5 3.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}function Qu({className:e}){return jsx("svg",{viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:e,children:jsx("path",{d:"M7.5 2.5L4 6l3.5 3.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}function Fs({source:e}){return jsxs("span",{className:"inline-flex items-center gap-x-1 text-neutral-400",title:e==="polymarket"?"Polymarket":"Kalshi",children:[jsx("span",{className:"text-neutral-600",children:"\xB7"}),e==="polymarket"?jsx(PolymarketIcon,{className:"h-5 w-auto shrink-0"}):jsx(KalshiIcon,{className:"h-3 w-auto shrink-0"})]})}var qu=768,qs=1024,Hu=1280,Ku=8,$u=224,zu=304,Gu=114;function Yu(e){return e>=Hu?4:e>=qs?3:e>=qu?2:1}function ju(e){return e>=qs?zu:$u}function Hs({events:e,hasMore:t=false,onFetchMore:r,onSelect:n,onSelectOutcome:s,getEventHref:a,LinkComponent:o,onHover:i}){let l=useRef(null),c=useRef(null),{width:u=0,height:p=0}=useResizeObserver({ref:l}),d=Yu(u),y=ju(u),f=Math.ceil(e.length/d)||0,g=!t&&e.length>0,v=f+(t?1:0)+(g?1:0),h=useCallback(P=>P<f,[f]),b=useCallback(async()=>{r?.();},[r]),x=useInfiniteLoader({isRowLoaded:h,loadMoreRows:b,rowCount:v,threshold:3}),m=useCallback(()=>{c.current?.scrollToRow({index:0,behavior:"smooth"});},[]);return jsx("div",{ref:l,className:"@container w-full h-full",children:p>0&&jsx(List,{listRef:c,className:"no-scrollbar",style:{height:p},onRowsRendered:x,rowComponent:Xu,rowCount:v,rowHeight:P=>g&&P===v-1?Gu:(y),rowProps:{events:e,columnCount:d,dataRowCount:f,showEndOfList:g,totalRowCount:v,onSelect:n,onSelectOutcome:s,getEventHref:a,LinkComponent:o,onHover:i,onScrollToTop:m}})})}function Xu({index:e,style:t,events:r,columnCount:n,dataRowCount:s,showEndOfList:a,totalRowCount:o,onSelect:i,onSelectOutcome:l,getEventHref:c,LinkComponent:u,onHover:p,onScrollToTop:d}){if(a&&e===o-1)return jsx("div",{style:t,children:jsx(Zu,{onScrollToTop:d})});if(e>=s)return jsx("div",{style:t,className:"flex justify-center items-start pt-4",children:jsx(Spinner,{size:"sm"})});let y=e*n,f=r.slice(y,y+n),g=n-f.length;return jsx("div",{style:t,children:jsxs("div",{className:"flex w-full h-full",children:[f.map(v=>v==null?null:jsx("div",{className:"flex-1 min-w-0 flex",style:{padding:Ku},children:jsx(As,{event:v,href:c?.(v),LinkComponent:u,onSelect:i,onSelectOutcome:l,onHover:p})},v.slug)),g>0&&Array.from({length:g}).map((v,h)=>jsx("div",{style:{flex:1,minWidth:0}},`spacer-${h}`))]})})}function Zu({onScrollToTop:e}){let{t}=useTranslation();return jsxs("div",{className:"flex w-full flex-col items-center justify-center gap-y-4 py-6",children:[jsxs("div",{className:"flex w-full items-center justify-center gap-x-4",children:[jsx("div",{className:"h-px w-16 bg-neutral-700"}),jsx("span",{className:"text-xs font-medium text-neutral-500",children:t("predict.event.endOfList")}),jsx("div",{className:"h-px w-16 bg-neutral-700"})]}),jsxs("button",{type:"button",className:"flex cursor-pointer items-center gap-x-1 text-xs font-medium text-neutral-400",onClick:e,children:[jsx("span",{className:"iconify size-4 ph--arrow-up-bold"}),jsx("span",{children:t("predict.event.backToTop")})]})]})}function $s({tagSlugSelection:e,limit:t=48,status:r,sort_by:n,sort_asc:s,source:a,with_markets:o,onSelect:i,onSelectOutcome:l,getEventHref:c,LinkComponent:u,onHover:p}){let{data:d,hasMore:y,fetchMore:f,isFetching:g}=Ts({tagSlugSelection:e,limit:t,status:r,sort_by:n,sort_asc:s,source:a,with_markets:o});return g?jsx(ot,{count:48}):jsx(Hs,{events:d,hasMore:y,onFetchMore:f,onSelect:i,onSelectOutcome:l,getEventHref:c,LinkComponent:u,onHover:p})}function D0({onSelect:e,onSelectOutcome:t,getEventHref:r,LinkComponent:n,onHover:s}){let[a,o]=useState({categorySlug:null,tagSlug:null}),[i,l]=useState(Tr),{isOpen:c,onOpen:u,onClose:p}=useDisclosure(),d=useCallback(x=>{o(x);},[]),y=useCallback(x=>{l(m=>({...m,sortPreset:x}));},[]),f=useCallback(x=>{l(m=>({...m,sortAsc:x}));},[]),g=useCallback(x=>{l(x);},[]),v=useMemo(()=>Cs[i.sortPreset].sort_by,[i.sortPreset]),h=useMemo(()=>Rr(i),[i]),b=jsx(Es,{sortPreset:i.sortPreset,onSortChange:y,sortAsc:i.sortAsc,onSortAscChange:f,onFilterPress:u,filterCount:h});return jsxs("div",{className:"flex h-full w-full max-w-[1680px] mx-auto flex-col gap-y-3",children:[jsx(xs,{onSelect:d,trailing:b}),jsx(bs,{isOpen:c,onClose:p,value:i,onChange:g}),jsx("div",{className:"min-h-0 flex-1",children:jsx($s,{tagSlugSelection:a,sort_by:v,sort_asc:i.sortAsc,source:i.source,onSelect:e,onSelectOutcome:t,getEventHref:r,LinkComponent:n,onHover:s})})]})}function _r(e,t,r){let n=e[t];return n?r==="yes"?n.yesMint:n.noMint:null}var ut=SOLANA_TOKENS.stablecoins.USDC.address;function id(){let e={startVelocity:30,spread:360,ticks:60,zIndex:9999};Vr({...e,particleCount:80,origin:{x:.5,y:.4}}),setTimeout(()=>{Vr({...e,particleCount:40,origin:{x:.3,y:.6}});},150),setTimeout(()=>{Vr({...e,particleCount:40,origin:{x:.7,y:.6}});},300);}function js({market:e,chain:t="solana",initialOutcome:r="yes",initialSide:n="buy"}){let{t:s}=useTranslation(),a=useContext(Me),{status:o}=useAuth(),l=useWallets().find(N=>N.chainNamespace===ChainNamespace.SOLANA&&N.isConnected),c=o==="authenticated",u=l?.address,[p,d]=useState(r),[y,f]=useState(n),[g,v]=useState(NaN),h=useMemo(()=>_r(e.accounts,ut,p),[e.accounts,p]),{inputMint:b,outputMint:x}=useMemo(()=>y==="buy"?{inputMint:ut,outputMint:h}:{inputMint:h,outputMint:ut},[y,h]),m=!!b&&!!x&&g>0,P=useMemo(()=>Number(p==="yes"?e.yesAsk??.5:e.noAsk??.5),[p,e.yesAsk,e.noAsk]),w=useMemo(()=>isNaN(g)||g<=0?0:y==="buy"?P>0?g/P:0:g,[y,g,P]),O=useMemo(()=>isNaN(g)||g<=0?0:Math.round(g*1e6),[g]),{data:R,isLoading:C,error:V,refetch:Q}=Un({userPublicKey:u??void 0,inputMint:b??"",outputMint:x??"",amount:O,slippageBps:100},{enabled:m}),Le=a?.usdcBalance??null,Ee=a?.isLoading??false,vn=a?.refetch,be=a?.positions,ht=useMemo(()=>{if(!be||!h)return null;let N=be.find(me=>me.mint===h);return N?N.balance:0},[be,h]),nr=useMemo(()=>_r(e.accounts,ut,"yes"),[e.accounts]),sr=useMemo(()=>_r(e.accounts,ut,"no"),[e.accounts]),Aa=useMemo(()=>{if(!be||!nr)return null;let N=be.find(me=>me.mint===nr);return N?N.balance:0},[be,nr]),Da=useMemo(()=>{if(!be||!sr)return null;let N=be.find(me=>me.mint===sr);return N?N.balance:0},[be,sr]),{data:Fe}=ze(e.ticker,{refetchInterval:5e3}),Ua=useMemo(()=>(p==="yes"?Fe?.yesBids:Fe?.noBids)?.[0]?.price??null,[Fe,p]),Fa=useMemo(()=>(p==="yes"?Fe?.yesAsks:Fe?.noAsks)?.[0]?.price??null,[Fe,p]),Wa=useMemo(()=>R?.priceImpactPct?parseFloat(R.priceImpactPct):null,[R]),bt=useMemo(()=>{if(isNaN(g)||g<=0)return 0;if(R)return parseInt(R.inAmount)/1e6;if(y==="buy")return g;let N=Number(p==="yes"?e.yesBid??0:e.noBid??0);return g*N},[R,y,p,g,e.yesBid,e.noBid]),xn=useMemo(()=>isNaN(g)||g<=0?0:y==="buy"?w*1:bt,[y,w,bt,g]),qa=xn-bt,Ha=useCallback(N=>{f(N),v(NaN);},[]),Ka=useCallback(N=>{if(isNaN(N)){v(NaN);return}let me=Math.max(0,N),St=y==="buy"?Math.round(me*100)/100:Math.round(me);v(St);},[y]);useEffect(()=>{m&&Q();},[g,p,y,m,Q]);let or=useMemo(()=>{let N=[];return (isNaN(g)||g<ir)&&N.push(`Minimum quantity is ${ir}`),e.status!=="active"&&N.push("Market is not active"),y==="buy"&&Le!=null&&!isNaN(g)&&g>0&&g>Le&&N.push("Insufficient USDC balance"),y==="sell"&&ht!=null&&!isNaN(g)&&g>0&&g>ht&&N.push("Insufficient shares"),{isValid:N.length===0,errors:N}},[g,e.status,y,Le,ht]),[$a,ar]=useState(null),[za,We]=useState(false),[kt,tt]=useState(null),{data:Pt}=Fn({signature:kt??""},{enabled:!!kt});useEffect(()=>{if(!Pt||!kt)return;let{status:N}=Pt;N==="closed"?(We(false),tt(null),toast.success(s("predict.trade.submitSuccess")),id(),v(NaN),vn?.()):(N==="failed"||N==="expired")&&(We(false),tt(null),toast.error(s("predict.trade.submitError")));},[Pt,kt,vn,s]);let Ga=useCallback(async()=>{if(!(!or.isValid||!c||!u||!l||Ee)){ar(null),tt(null),We(true);try{let N=R;if(N?.transaction||(N=(await Q()).data),!N?.transaction){We(!1);return}let me=Uint8Array.from(atob(N.transaction),hn=>hn.charCodeAt(0)),St=await l.sendTransaction(me);ar(St),tt(St);}catch{toast.error(s("predict.trade.submitError")),We(false);}}},[or.isValid,c,u,l,R,Ee,Q,s]),Ya=useCallback(()=>{d(r),f(n),v(NaN),ar(null),tt(null),We(false);},[r,n]);return {outcome:p,side:y,quantity:g,shares:w,estimatedCost:bt,potentialPayout:xn,potentialProfit:qa,isAuthenticated:c,bestBid:Ua,bestAsk:Fa,order:R??null,priceImpact:Wa,usdcBalance:Le,outcomeTokenBalance:ht,yesTokenBalance:Aa,noTokenBalance:Da,isBalanceLoading:Ee,isQuoteLoading:C,isSubmitting:za,quoteError:V??null,txHash:$a,orderStatus:Pt??null,validation:or,setOutcome:d,setSide:Ha,setQuantity:Ka,submit:Ga,reset:Ya}}var md=`https://s1.chainstream.io/chains/sol/tokens/${SOLANA_TOKENS.stablecoins.USDC.address}/image.png`;function eo({event:e,market:t,outcome:r,side:n,quantity:s,potentialProfit:a,estimatedCost:o,usdcBalance:i,yesTokenBalance:l,noTokenBalance:c,isBalanceLoading:u,isSubmitting:p,isValid:d,onOutcomeChange:y,onSideChange:f,onQuantityChange:g,onSubmit:v}){let{t:h}=useTranslation(),b=useMemo(()=>{if(p)return h("predict.trade.submitting");let m=h(n==="buy"?"predict.trade.buy":"predict.trade.sell"),P=h(r==="yes"?"predict.trade.yes":"predict.trade.no");return `${m} ${P}`},[p,n,r,h]),x=useMemo(()=>r==="yes"?"primary":"secondary",[r]);return jsxs("div",{className:"flex w-full flex-col gap-y-4 rounded-xl border border-default-200 bg-content1 p-4",children:[e&&jsxs("div",{className:"flex items-center gap-x-3",children:[e.imageUrl&&jsx("img",{src:e.imageUrl,alt:e.title,className:"h-10 w-10 shrink-0 rounded-lg object-cover"}),jsxs("div",{className:"flex min-w-0 flex-col gap-y-0.5",children:[jsx("span",{className:"text-sm text-neutral-500 leading-tight line-clamp-1",children:e.title}),jsxs("span",{className:"text-base font-semibold leading-tight line-clamp-1",children:[jsxs("span",{className:r==="yes"?"text-bullish":"text-bearish",children:[h(n==="buy"?"predict.trade.buy":"predict.trade.sell")," ",h(r==="yes"?"predict.trade.yes":"predict.trade.no")]}),jsxs("span",{className:"text-foreground",children:[" \xB7 ",r==="yes"?t.yesSubTitle:t.noSubTitle]})]})]})]}),jsxs(Tabs,{variant:"underlined",selectedKey:n,onSelectionChange:m=>f(m),classNames:{tabList:"gap-x-4",tab:"px-0"},children:[jsx(Tab,{title:h("predict.trade.buy")},"buy"),jsx(Tab,{title:h("predict.trade.sell")},"sell")]}),jsx("div",{className:"flex gap-x-2",children:["yes","no"].map(m=>{let P=m==="yes"?l:c;return jsxs("div",{className:"flex flex-1 flex-col gap-y-1",children:[jsxs("button",{type:"button",onClick:()=>y(m),className:`w-full rounded-lg border py-2 text-sm font-medium transition-colors cursor-pointer ${r===m?m==="yes"?"border-primary bg-primary-50 text-primary":"border-secondary bg-secondary-50 text-secondary":"border-default-400 text-foreground hover:border-default-500"}`,children:[jsx("span",{children:h(m==="yes"?"predict.trade.yes":"predict.trade.no")}),(()=>{let w=n==="buy"?m==="yes"?t.yesAsk:t.noAsk:m==="yes"?t.yesBid:t.noBid;return w!=null?jsxs("span",{className:"ml-1 opacity-70",children:[Math.round(Number(w)*100),"\xA2"]}):null})()]}),n==="sell"&&r===m&&jsx("span",{className:"text-center text-xs text-foreground",children:u?"\u2013":`${P??0} shares`})]},m)})}),n==="buy"&&jsxs("div",{className:"flex items-center justify-end gap-x-1 text-xs text-default-500",children:[jsx("img",{src:md,alt:"USDC",className:"h-4 w-4 rounded-full object-cover"}),jsxs("span",{children:[h("predict.trade.balance"),":"]}),jsx("span",{className:"font-medium text-foreground",children:i!=null?`$${i.toFixed(2)}`:"\u2013"})]}),jsxs("div",{className:"flex flex-col gap-y-1.5",children:[jsx("span",{className:"text-sm font-medium text-foreground",children:h(n==="buy"?"predict.trade.amount":"predict.trade.contracts")}),jsx(StyledNumberInput,{fullWidth:true,placeholder:"0",radius:"lg",size:"lg",value:isNaN(s)?void 0:s,onValueChange:m=>{g(m);},minValue:0,step:n==="buy"?.01:1,formatOptions:n==="buy"?{maximumFractionDigits:2}:{maximumFractionDigits:0},startContent:n==="buy"?jsx("span",{className:"text-default-600 text-xl",children:"$"}):void 0,classNames:{inputWrapper:"bg-content2 data-[hover=true]:bg-content2 group-data-[focus=true]:bg-content2 h-14 min-h-14",input:"text-lg"}},n),jsx("div",{className:"flex gap-x-2 justify-end",children:n==="buy"?jsxs(Fragment,{children:[[1,5,10,100].map(m=>jsxs("button",{type:"button",onClick:()=>g(Math.round(((isNaN(s)?0:s)+m)*100)/100),className:"rounded-md bg-content2 px-2.5 py-1 text-xs font-medium text-default-600 transition-colors hover:bg-content3 cursor-pointer",children:["+",m,"$"]},m)),jsx("button",{type:"button",onClick:()=>{},className:"rounded-md bg-content2 px-2.5 py-1 text-xs font-medium text-default-600 transition-colors hover:bg-content3 cursor-pointer",children:h("common.all")})]}):jsxs(Fragment,{children:[[25,50].map(m=>jsxs("button",{type:"button",onClick:()=>{},className:"rounded-md bg-content2 px-2.5 py-1 text-xs font-medium text-default-600 transition-colors hover:bg-content3 cursor-pointer",children:[m,"%"]},m)),jsx("button",{type:"button",onClick:()=>{},className:"rounded-md bg-content2 px-2.5 py-1 text-xs font-medium text-default-600 transition-colors hover:bg-content3 cursor-pointer",children:h("common.all")})]})})]}),!isNaN(s)&&s>0&&jsxs("div",{className:"flex flex-col items-end gap-y-0.5",children:[jsx("span",{className:"text-sm text-foreground",children:h(n==="buy"?"predict.trade.potentialWin":"predict.trade.estimatedReceive")}),jsxs("span",{className:"text-xl font-semibold text-bullish",children:["$",(n==="buy"?a:o).toFixed(2)]})]}),jsx(Button,{color:x,fullWidth:true,radius:"lg",size:"lg",isDisabled:!d||p,isLoading:p,onPress:v,children:b})]})}function je({event:e,market:t,initialSide:r,initialOutcome:n,chain:s}){let{outcome:a,side:o,quantity:i,estimatedCost:l,potentialPayout:c,potentialProfit:u,usdcBalance:p,yesTokenBalance:d,noTokenBalance:y,isBalanceLoading:f,isSubmitting:g,validation:v,setOutcome:h,setSide:b,setQuantity:x,submit:m}=js({market:t,initialSide:r,initialOutcome:n,chain:s}),P=useAuthCallback(m);return jsx(eo,{event:e,market:t,outcome:a,side:o,quantity:i,estimatedCost:l,potentialPayout:c,potentialProfit:u,usdcBalance:p,yesTokenBalance:d,noTokenBalance:y,isBalanceLoading:f,isSubmitting:g,isValid:v.isValid,validationErrors:v.errors,onOutcomeChange:h,onSideChange:b,onQuantityChange:x,onSubmit:P})}function gd(){return jsxs("div",{className:"flex items-center gap-x-3 px-2 py-3 lg:gap-x-4",children:[jsx(Skeleton,{className:"h-4 flex-1 rounded-md"}),jsx(Skeleton,{className:"h-5 w-10 shrink-0 rounded-md"}),jsxs("div",{className:"flex gap-x-2",children:[jsx(Skeleton,{className:"h-8 w-16 rounded-lg"}),jsx(Skeleton,{className:"h-8 w-16 rounded-lg"})]})]})}function ge({marketCount:e=4}){return jsxs("div",{className:"w-full flex flex-col gap-4 lg:gap-y-6 px-1 lg:px-4 lg:max-w-3xl animate-pulse",children:[jsxs("div",{className:"flex items-center gap-x-3 lg:gap-x-4",children:[jsx(Skeleton,{className:"h-14 w-14 shrink-0 rounded-lg lg:h-18 lg:w-18"}),jsxs("div",{className:"flex flex-col gap-y-1.5 min-w-0 flex-1",children:[jsx(Skeleton,{className:"h-3 w-24 rounded-md lg:w-32"}),jsx(Skeleton,{className:"h-5 w-48 rounded-md lg:h-6 lg:w-72"})]})]}),jsx(Skeleton,{className:"h-[200px] w-full rounded-xl lg:h-[280px]"}),jsxs("div",{className:"flex items-center justify-between",children:[jsx(Skeleton,{className:"h-3 w-32 rounded-md"}),jsx("div",{className:"flex gap-x-1",children:Array.from({length:4}).map((t,r)=>jsx(Skeleton,{className:"h-7 w-10 rounded-md"},r))})]}),jsx("div",{className:"flex flex-col divide-y divide-default-200",children:Array.from({length:e}).map((t,r)=>jsx(gd,{},r))})]})}function Ft(){return jsxs("div",{className:"flex w-full flex-col gap-y-4 rounded-xl border border-default-200 bg-content1 p-4 animate-pulse",children:[jsxs("div",{className:"flex items-center gap-x-3",children:[jsx(Skeleton,{className:"h-10 w-10 shrink-0 rounded-lg"}),jsxs("div",{className:"flex flex-col gap-y-1 flex-1",children:[jsx(Skeleton,{className:"h-3 w-28 rounded-md"}),jsx(Skeleton,{className:"h-4 w-40 rounded-md"})]})]}),jsxs("div",{className:"flex gap-x-4",children:[jsx(Skeleton,{className:"h-4 w-12 rounded-md"}),jsx(Skeleton,{className:"h-4 w-12 rounded-md"})]}),jsxs("div",{className:"flex gap-x-2",children:[jsx(Skeleton,{className:"h-10 flex-1 rounded-lg"}),jsx(Skeleton,{className:"h-10 flex-1 rounded-lg"})]}),jsx(Skeleton,{className:"h-14 w-full rounded-lg"}),jsx(Skeleton,{className:"h-12 w-full rounded-lg"})]})}var to=e=>{let{candlestickMarketTickers:t,chartRange:r=le}=e,n=He[r],s=Ke[r],a=useMemo(()=>Math.floor(Date.now()/1e3),[r]),o=k(),{data:i,isLoading:l,error:c}=Tt({id:e.eventId,withNestedMarkets:true}),u=useMemo(()=>{if(s!=null)return a-s;let x=i?.markets;return x?.length?Math.min(...x.map(m=>m.openTime)):a},[a,s,i?.markets]),{data:p,isLoading:d,error:y}=Vn(i?.seriesTicker??"",{enabled:!!i?.seriesTicker}),f=useMemo(()=>i?.markets?(t&&t.length>0?t.slice(0,4).map(m=>i.markets.find(P=>P.ticker===m)).filter(m=>m!==void 0):[...i.markets].sort((m,P)=>Number(P.yesAsk??0)-Number(m.yesAsk??0)).slice(0,4)).map(m=>m.ticker):[],[t,i?.markets]),g=useQueries({queries:f.map(x=>({queryKey:rt({ticker:x,startTs:u,endTs:a,periodInterval:n}),queryFn:()=>nt(o,{ticker:x,startTs:u,endTs:a,periodInterval:n}),enabled:f.length>0}))}),v=g.some(x=>x.isLoading),h=useMemo(()=>{let x=new Map;return f.forEach((m,P)=>{let w=g[P]?.error;w&&x.set(m,w);}),x},[f,g]),b=useMemo(()=>{let x=new Map;return f.forEach((m,P)=>{let w=g[P]?.data;w&&x.set(m,w);}),x},[f,g]);return {event:i,isEventLoading:l,eventError:c,series:p,isSeriesLoading:d,seriesError:y,periodInterval:n,candlesticks:b,isCandlesticksLoading:v,candlestickErrors:h}};var Ed=SOLANA_TOKENS.stablecoins.USDC.address;function ro(e){let{status:t}=useAuth(),n=useWallets().find(c=>c.chainNamespace===ChainNamespace.SOLANA&&c.isConnected),s=t==="authenticated",a=n?.address,{data:o,isLoading:i}=useWalletPortfoliosQuery({chain:Chain.SOLANA,address:a??""},{enabled:s&&!!a,refetchInterval:1e4});return {holdings:useMemo(()=>{let c=new Map;if(!o?.portfolios||e.length===0)return c;let u=new Map;for(let p of o.portfolios)u.set(p.address,parseFloat(p.amount));for(let p of e){let d=p.accounts[Ed];if(!d)continue;let y=u.get(d.yesMint)??0,f=u.get(d.noMint)??0;(y>0||f>0)&&c.set(p.ticker,{yesShares:y,noShares:f});}return c},[o,e]),isLoading:i}}function Bd(e){let{cx:t,cy:r,index:n,dataLength:s,stroke:a}=e;return n!==s-1||t==null||r==null?null:jsxs("g",{children:[jsxs("circle",{cx:t,cy:r,r:6,fill:a,opacity:.3,children:[jsx("animate",{attributeName:"r",values:"4;8;4",dur:"2s",repeatCount:"indefinite"}),jsx("animate",{attributeName:"opacity",values:"0.4;0.1;0.4",dur:"2s",repeatCount:"indefinite"})]}),jsx("circle",{cx:t,cy:r,r:3,fill:a})]})}var Wt=[{stroke:"hsl(var(--heroui-primary))",id:"colorMarket0"},{stroke:"hsl(var(--heroui-secondary))",id:"colorMarket1"},{stroke:"hsl(var(--heroui-success))",id:"colorMarket2"},{stroke:"hsl(var(--heroui-warning))",id:"colorMarket3"}];function no(e,t){let r=new Date(e*1e3);switch(t){case S.ONE_DAY:return r.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:false});case S.ONE_WEEK:case S.ONE_MONTH:return r.toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:false});case S.ALL:default:return r.toLocaleDateString("en-US",{month:"short",day:"numeric"})}}function _d(e,t,r){let n=Mt[r],s=new Map;e.forEach((l,c)=>{let u=new Map;(l.candlesticks??[]).forEach(d=>{let y=d.end_period_ts-d.end_period_ts%n;u.set(y,d.yes_ask.close);}),s.set(c,u);});let a=new Set;for(let l of s.values())for(let c of l.keys())a.add(c);let o=Array.from(a).sort((l,c)=>l-c),i=new Map;return o.map(l=>{let u={date:new Date(l*1e3).toLocaleDateString("en-US",{month:"short",day:"numeric"}),timestamp:l};return t.forEach(p=>{let d=s.get(p)?.get(l);if(d!==void 0)u[p]=Math.round(d*100)/100,i.set(p,u[p]);else {let y=i.get(p);y!==void 0&&(u[p]=y);}}),u})}function qt({candlesticks:e,markets:t=[],isLoading:r,chartRange:n=S.ALL,onDataChange:s}){let[a,o]=useState(null),i=useRef(s);useEffect(()=>{i.current=s;});let l=useMemo(()=>e?Array.from(e.keys()).slice(0,4):[],[e]),c=useMemo(()=>!e||e.size===0?[]:_d(e,l,n),[e,l,n]),u=useMemo(()=>{if(c.length===0||l.length===0)return [0,100];let f=1/0,g=-1/0;if(c.forEach(m=>{l.forEach(P=>{let w=m[P];w!==void 0&&(f=Math.min(f,w),g=Math.max(g,w));});}),f===1/0||g===-1/0)return [0,100];let v=g-f,h=Math.max(v*.2,5),b=Math.max(0,Math.floor(f-h)),x=Math.min(100,Math.ceil(g+h));return [b,x]},[c,l]),p=useCallback(f=>{if(c.length===0)return null;let g=f!==null?c[f]:c[c.length-1];return g?{timestamp:g.timestamp,date:g.date,markets:l.map((v,h)=>{let b=t.find(x=>x.ticker===v);return {id:v,label:b?.yesSubTitle||`Market ${h+1}`,value:g[v]??0,color:Wt[h%Wt.length].stroke}})}:null},[c,l,t]);useEffect(()=>{i.current&&c.length>0&&i.current(p(null));},[c,p]),useEffect(()=>{i.current&&i.current(p(a));},[a,p]);let d=useCallback(f=>{typeof f?.activeTooltipIndex=="number"&&o(f.activeTooltipIndex);},[]),y=useCallback(()=>{o(null);},[]);return r?jsx("div",{className:"h-[200px] w-full lg:h-[300px] flex items-center justify-center",children:jsx("div",{className:"text-default-400 text-sm",children:"Loading chart..."})}):c.length===0?jsx("div",{className:"h-[200px] w-full lg:h-[300px] flex items-center justify-center",children:jsx("div",{className:"text-default-400 text-sm",children:"No price history data"})}):jsx("div",{className:"h-[200px] w-full lg:h-[300px]",children:jsx(ResponsiveContainer,{width:"100%",height:"100%",children:jsxs(LineChart,{data:c,margin:{top:10,right:16,left:16,bottom:0},onMouseMove:d,onMouseLeave:y,children:[jsx(XAxis,{dataKey:"timestamp",tick:f=>{let{x:g,y:v,payload:h,index:b}=f,x=c.length,P=Math.max(1,Math.ceil(x/6)),w=b===0,O=b===x-1,R=b%P===0;return !w&&!O&&!R?null:jsx("text",{x:g,y:v+10,textAnchor:"middle",fill:"hsl(var(--heroui-default-500))",fontSize:10,children:no(h.value,n)})},tickLine:false,axisLine:false,interval:0}),jsx(CartesianGrid,{horizontal:true,vertical:false,strokeDasharray:"3 3",stroke:"hsl(var(--heroui-default-200))"}),jsx(YAxis,{domain:u,tickLine:false,axisLine:false,tick:{fontSize:10,fill:"hsl(var(--heroui-default-500))"},tickFormatter:f=>`${f}%`,width:40}),jsx(Tooltip,{contentStyle:{backgroundColor:"hsl(var(--heroui-content1))",border:"1px solid hsl(var(--heroui-default-200))",borderRadius:"8px",fontSize:"12px"},labelFormatter:f=>no(f,n),formatter:(f,g)=>{let h=t.find(b=>b.ticker===g)?.yesSubTitle||g;return [`${f.toFixed(2)}%`,h]}}),l.map((f,g)=>jsx(Line,{type:"monotone",dataKey:f,stroke:Wt[g%Wt.length].stroke,strokeWidth:2,isAnimationActive:false,dot:v=>jsx(Bd,{...v,dataLength:c.length},`dot-${f}-${v.index}`),activeDot:false},f))]})})})}function Ht(){return {timestamp:Date.now()/1e3,date:new Date().toLocaleDateString("en-US",{month:"short",day:"numeric"}),markets:[]}}function oo({marketTicker:e,openTime:t,chartRange:r=le}){let n=He[r],s=Ke[r],a=useMemo(()=>Math.floor(Date.now()/1e3),[r]),o=useMemo(()=>s!=null?a-s:t??a,[a,s,t]),{data:i,isLoading:l,isFetching:c,error:u}=kr({ticker:e,startTs:o,endTs:a,periodInterval:n},{enabled:!!e});return {candlesticks:i,isLoading:l,isFetching:c,error:u,periodInterval:n}}var Hd="hsl(var(--heroui-primary))",Kd=[{value:S.ONE_DAY,label:"1D"},{value:S.ONE_WEEK,label:"1W"},{value:S.ONE_MONTH,label:"1M"},{value:S.ALL,label:"ALL"}];function $d(e){let{cx:t,cy:r,index:n,dataLength:s,stroke:a}=e;return n!==s-1||t==null||r==null?null:jsxs("g",{children:[jsxs("circle",{cx:t,cy:r,r:6,fill:a,opacity:.3,children:[jsx("animate",{attributeName:"r",values:"4;8;4",dur:"2s",repeatCount:"indefinite"}),jsx("animate",{attributeName:"opacity",values:"0.4;0.1;0.4",dur:"2s",repeatCount:"indefinite"})]}),jsx("circle",{cx:t,cy:r,r:3,fill:a})]})}function io(e,t){let r=new Date(e*1e3);switch(t){case S.ONE_DAY:return r.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:false});case S.ONE_WEEK:case S.ONE_MONTH:return r.toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:false});case S.ALL:default:return r.toLocaleDateString("en-US",{month:"short",day:"numeric"})}}function zd(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:e.toFixed(0)}function Gd(e,t){let r=Mt[t],n=e.candlesticks??[],s=new Map;for(let o of n){let i=o.end_period_ts-o.end_period_ts%r,l=s.get(i);s.set(i,{close:o.yes_ask.close,volume:(l?.volume??0)+(o.volume??0)});}return Array.from(s.entries()).sort((o,i)=>o[0]-i[0]).map(([o,{close:i,volume:l}])=>({timestamp:o,date:new Date(o*1e3).toLocaleDateString("en-US",{month:"short",day:"numeric"}),value:Math.round(i*100)/100,volume:l}))}function lo({candlesticks:e,isLoading:t,chartRange:r,onRangeChange:n}){let s=useMemo(()=>e?Gd(e,r):[],[e,r]),a=useMemo(()=>{if(s.length===0)return [0,100];let o=1/0,i=-1/0;for(let d of s)d.value<o&&(o=d.value),d.value>i&&(i=d.value);if(o===1/0||i===-1/0)return [0,100];let l=i-o,c=Math.max(l*.2,5),u=Math.max(0,Math.floor(o-c)),p=Math.min(100,Math.ceil(i+c));return [u,p]},[s]);return t?jsxs("div",{className:"flex flex-col gap-y-2",children:[jsx("div",{className:"h-[200px] w-full flex items-center justify-center",children:jsx("div",{className:"text-neutral text-sm",children:"Loading chart..."})}),jsx(Fr,{chartRange:r,onRangeChange:n})]}):s.length===0?jsxs("div",{className:"flex flex-col gap-y-2",children:[jsx("div",{className:"h-[200px] w-full flex items-center justify-center",children:jsx("div",{className:"text-neutral text-sm",children:"No price history data"})}),jsx(Fr,{chartRange:r,onRangeChange:n})]}):jsxs("div",{className:"flex flex-col gap-y-2",children:[jsx("div",{className:"h-[200px] w-full",children:jsx(ResponsiveContainer,{width:"100%",height:"100%",children:jsxs(LineChart,{data:s,margin:{top:10,right:16,left:16,bottom:0},children:[jsx(XAxis,{dataKey:"timestamp",tick:o=>{let{x:i,y:l,payload:c,index:u}=o,p=s.length,y=Math.max(1,Math.ceil(p/6)),f=u===0,g=u===p-1,v=u%y===0;return !f&&!g&&!v?null:jsx("text",{x:i,y:l+10,textAnchor:"middle",fill:"hsl(var(--heroui-default-500))",fontSize:10,children:io(c.value,r)})},tickLine:false,axisLine:false,interval:0}),jsx(CartesianGrid,{horizontal:true,vertical:false,strokeDasharray:"3 3",stroke:"hsl(var(--heroui-default-200))"}),jsx(YAxis,{domain:a,tickLine:false,axisLine:false,tick:{fontSize:10,fill:"hsl(var(--heroui-default-500))"},tickFormatter:o=>`${o}%`,width:40}),jsx(Tooltip,{cursor:{stroke:"hsl(var(--heroui-default-300))"},content:({active:o,payload:i})=>{if(!o||!i?.length)return null;let l=i[0].payload,c=Math.round(l.value);return jsxs("div",{className:"rounded-lg border border-default-200 bg-content1 px-3 py-2 shadow-md",children:[jsxs("div",{className:"text-lg font-semibold text-primary",children:["Yes ",c,"\xA2"]}),jsxs("div",{className:"text-sm text-neutral",children:["Vol ",zd(l.volume)," \xB7"," ",io(l.timestamp,r)]})]})}}),jsx(Line,{type:"monotone",dataKey:"value",stroke:Hd,strokeWidth:2,isAnimationActive:false,dot:o=>jsx($d,{...o,dataLength:s.length},`dot-${o.index}`),activeDot:false})]})})}),jsx(Fr,{chartRange:r,onRangeChange:n})]})}function Fr({chartRange:e,onRangeChange:t}){return jsx("div",{className:"flex items-center justify-end gap-x-1",children:Kd.map(r=>{let n=e===r.value;return jsx("button",{type:"button",className:`px-3 py-1 text-xs rounded-md transition-colors cursor-pointer ${n?"bg-primary text-primary-foreground":"bg-default-100 text-default-600 hover:bg-default-200"}`,onClick:()=>t?.(r.value),children:r.label},r.value)})})}function co({marketTicker:e}){let{data:t,isLoading:r,error:n}=ze(e,{enabled:!!e});return {orderbook:useMemo(()=>{if(!t)return null;let{yesBids:a,yesAsks:o,noBids:i,noAsks:l}=t;return {yesBids:a,yesAsks:o,noBids:i,noAsks:l,bestYesBid:a.length>0?a[0].price:null,bestYesAsk:o.length>0?o[0].price:null,bestNoBid:i.length>0?i[0].price:null,bestNoAsk:l.length>0?l[0].price:null,sequence:t.sequence??null}},[t]),isOrderbookLoading:r,orderbookError:n}}function uo(e,t){let r=e.slice(0,t),n=0;return r.map(s=>(n+=s.quantity,{...s,cumulative:n,depth:0,total:s.price*s.quantity}))}function po(e,t){for(let r of e)r.depth=t>0?r.cumulative/t:0;}function go(e){return `${Math.round(e*100)}\xA2`}function Xd(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:e.toLocaleString()}function Zd(e){return e>=1e6?`$${(e/1e6).toFixed(2)}M`:e>=1e3?`$${(e/1e3).toFixed(2)}K`:e>=1?`$${e.toFixed(2)}`:`$${e.toFixed(4)}`}function mo({row:e,side:t,showType:r=false,onClick:n}){let{t:s}=useTranslation(),a=t==="ask",o=a?"bg-bullish/10":"bg-bearish/10",i=a?"text-bullish":"text-bearish";return jsxs("button",{type:"button",className:"relative grid w-full grid-cols-4 px-2 py-2.5 text-xs cursor-pointer hover:bg-default-100 transition-colors",onClick:()=>n?.(e.price,t),children:[jsx("div",{className:`absolute inset-y-0 left-0 ${o} transition-[width] duration-200`,style:{width:`${e.depth*100}%`}}),jsx("span",{className:`relative z-10 font-mono font-medium ${i} text-left`,children:r?s(a?"predict.trade.bestAsk":"predict.trade.bestBid"):""}),jsx("span",{className:"relative z-10 font-mono text-foreground text-right",children:go(e.price)}),jsx("span",{className:"relative z-10 font-mono text-foreground text-right",children:Xd(e.quantity)}),jsx("span",{className:"relative z-10 font-mono text-foreground text-right",children:Zd(e.total)})]})}function fo({index:e}){let t=["60%","45%","75%","55%","65%","50%","70%","40%"];return jsxs("div",{className:"grid grid-cols-4 gap-x-2 px-2 py-2.5",children:[jsx("div",{className:"h-4 animate-pulse rounded bg-default-100",style:{width:t[e%t.length]}}),jsx("div",{className:"h-4 animate-pulse rounded bg-default-100 ml-auto w-3/4"}),jsx("div",{className:"h-4 animate-pulse rounded bg-default-100 ml-auto w-3/4"}),jsx("div",{className:"h-4 animate-pulse rounded bg-default-100 ml-auto w-3/4"})]})}function Jd(){return jsxs("div",{className:"flex flex-col",children:[jsxs("div",{className:"grid grid-cols-4 gap-x-2 px-2 py-2.5",children:[jsx("div",{}),jsx("div",{className:"h-4 animate-pulse rounded bg-default-100 ml-auto w-1/2"}),jsx("div",{className:"h-4 animate-pulse rounded bg-default-100 ml-auto w-1/2"}),jsx("div",{className:"h-4 animate-pulse rounded bg-default-100 ml-auto w-1/2"})]}),Array.from({length:Wr}).map((e,t)=>jsx(fo,{index:t},`ask-${t}`)),jsx("div",{className:"flex justify-center border-y border-default-200 px-2 py-2.5",children:jsx("div",{className:"h-4 w-24 animate-pulse rounded bg-default-100"})}),Array.from({length:Wr}).map((e,t)=>jsx(fo,{index:t+3},`bid-${t}`))]})}var Wr=8;function qr({bids:e,asks:t,isLoading:r=false,maxLevels:n=Wr,onPriceClick:s}){let{t:a}=useTranslation(),{bidRows:o,askRows:i,spread:l,spreadPercent:c}=useMemo(()=>{let p=uo(e,n),d=uo(t,n),y=Math.max(p[p.length-1]?.cumulative??0,d[d.length-1]?.cumulative??0);po(p,y),po(d,y);let f=p[0]?.price??null,g=d[0]?.price??null,v=null,h=null;if(f!=null&&g!=null){v=g-f;let b=(f+g)/2;b>0&&(h=Math.round(v/b*1e4)/100);}return {bidRows:p,askRows:d,spread:v,spreadPercent:h}},[e,t,n]);return r?jsx(Jd,{}):o.length===0&&i.length===0?jsx("div",{className:"flex items-center justify-center py-6 text-sm text-neutral",children:a("predict.orderBook.empty")}):jsxs("div",{className:"flex flex-col",children:[jsxs("div",{className:"grid grid-cols-4 px-2 py-2.5 text-xs text-neutral",children:[jsx("span",{}),jsx("span",{className:"text-right",children:a("predict.orderBook.price")}),jsx("span",{className:"text-right",children:a("predict.orderBook.contracts")}),jsx("span",{className:"text-right",children:a("predict.orderBook.total")})]}),jsx("div",{className:"flex flex-col-reverse",children:i.map((p,d)=>jsx(mo,{row:p,side:"ask",showType:d===0,onClick:s},p.price))}),l!=null&&jsxs("div",{className:"flex items-center justify-center gap-x-2 border-y border-default-200 px-2 py-2.5 text-xs text-default-500",children:[jsxs("span",{children:[a("predict.orderBook.spread"),": ",go(l)]}),c!=null&&jsxs("span",{className:"text-default-400",children:["(",c,"%)"]})]}),jsx("div",{className:"flex flex-col",children:o.map((p,d)=>jsx(mo,{row:p,side:"bid",showType:d===0,onClick:s},p.price))})]})}function rp(e){return e>=1e6?`${(e/1e6).toFixed(2)}M`:e>=1e3?`${(e/1e3).toFixed(2)}K`:e.toLocaleString(void 0,{maximumFractionDigits:2})}function np(e){let t=Math.abs(e),r=e>=0?"+":"-";return t>=1e3?`${r}$${(t/1e3).toFixed(1)}K`:t>=1?`${r}$${t.toFixed(2)}`:`${r}$${t.toFixed(4)}`}function vo({positions:e,isLoading:t=false}){let{t:r}=useTranslation();return t?jsx("div",{className:"flex items-center justify-center py-8",children:jsx(Spinner,{size:"sm"})}):e.length===0?jsx("div",{className:"flex items-center justify-center py-6 text-sm text-neutral",children:r("predict.positions.empty")}):jsxs("div",{className:"flex flex-col",children:[jsxs("div",{className:"grid grid-cols-5 px-2 py-2.5 text-xs text-neutral",children:[jsx("span",{children:r("predict.positions.outcome")}),jsx("span",{className:"text-right",children:r("predict.positions.qty")}),jsx("span",{className:"text-right",children:r("predict.positions.avgCost")}),jsx("span",{className:"text-right",children:r("predict.positions.currentPrice")}),jsx("span",{className:"text-right",children:r("predict.positions.pnl")})]}),e.map(n=>{let s=n.position==="YES",a=s?"text-bullish":"text-bearish",o=r(s?"predict.market.yes":"predict.market.no"),i=n.avgCost!=null?`${Math.round(n.avgCost*100)}\xA2`:"\u2014",l=n.currentPrice!=null?`${Math.round(n.currentPrice*100)}\xA2`:"\u2014",c=n.pnl!=null&&n.pnlPercent!=null,u=c&&n.pnl>0?"text-bullish":c&&n.pnl<0?"text-bearish":"text-foreground";return jsxs("div",{className:"grid grid-cols-5 px-2 py-2.5 text-xs hover:bg-default-100 transition-colors",children:[jsx("span",{className:`font-medium ${a}`,children:o}),jsx("span",{className:"text-right font-mono text-foreground",children:rp(n.balance)}),jsx("span",{className:"text-right font-mono text-foreground",children:i}),jsx("span",{className:"text-right font-mono text-foreground",children:l}),jsx("span",{className:`text-right font-mono ${u}`,children:c?jsxs("span",{className:"flex flex-col items-end",children:[jsx("span",{children:np(n.pnl)}),jsxs("span",{className:"text-[10px] opacity-70",children:[n.pnlPercent>=0?"+":"",n.pnlPercent.toFixed(1),"%"]})]}):"\u2014"})]},n.mint)})]})}function op(e){let t=e/1e6;return t>=1e6?`${(t/1e6).toFixed(2)}M`:t>=1e3?`${(t/1e3).toFixed(2)}K`:t.toLocaleString(void 0,{maximumFractionDigits:2})}function ap(e){return e==null?"\u2014":`${Math.round(e*100)}\xA2`}function ip(e){let t=new Date(e*1e3),r=t.toLocaleString("default",{month:"short"}),n=t.getDate(),s=t.getHours().toString().padStart(2,"0"),a=t.getMinutes().toString().padStart(2,"0");return `${r} ${n} ${s}:${a}`}function lp({index:e}){let t=["60%","45%","75%","55%","65%"];return jsxs("div",{className:"grid grid-cols-4 gap-x-2 px-2 py-2.5",children:[jsx("div",{className:"h-4 animate-pulse rounded bg-default-100",style:{width:t[e%t.length]}}),jsx("div",{className:"h-4 animate-pulse rounded bg-default-100 ml-auto w-3/4"}),jsx("div",{className:"h-4 animate-pulse rounded bg-default-100 ml-auto w-3/4"}),jsx("div",{className:"h-4 animate-pulse rounded bg-default-100 ml-auto w-3/4"})]})}function xo({trades:e,isLoading:t=false}){let{t:r}=useTranslation();return t?jsx("div",{className:"flex flex-col",children:Array.from({length:6}).map((n,s)=>jsx(lp,{index:s},s))}):e.length===0?jsx("div",{className:"flex items-center justify-center py-6 text-sm text-neutral",children:r("predict.tradeHistory.empty")}):jsxs("div",{className:"flex flex-col",children:[jsxs("div",{className:"grid grid-cols-4 px-2 py-2.5 text-xs text-neutral",children:[jsx("span",{children:r("predict.tradeHistory.side")}),jsx("span",{className:"text-right",children:r("predict.tradeHistory.price")}),jsx("span",{className:"text-right",children:r("predict.tradeHistory.qty")}),jsx("span",{className:"text-right",children:r("predict.tradeHistory.time")})]}),e.map(n=>{let s=n.side==="yes",a=s?"text-bullish":"text-bearish",o=n.side?r(s?"predict.trade.yes":"predict.trade.no"):"\u2014";return jsxs("div",{className:"grid grid-cols-4 px-2 py-2.5 text-xs hover:bg-default-100 transition-colors",children:[jsx("span",{className:`font-medium ${a}`,children:o}),jsx("span",{className:"text-right font-mono text-foreground",children:ap(n.usdPricePerContract)}),jsx("span",{className:"text-right font-mono text-foreground",children:op(n.outputAmount)}),jsx("span",{className:"text-right text-default-500",children:ip(n.createdAt)})]},n.id)})]})}function $t({market:e,onTradeAction:t}){let{t:r}=useTranslation(),[n,s]=useState("trade-yes"),[a,o]=useState(le),{orderbook:i,isOrderbookLoading:l}=co({marketTicker:e.ticker}),{candlesticks:c,isFetching:u}=oo({marketTicker:e.ticker,openTime:e.openTime,chartRange:a}),{positions:p,isLoading:d}=Qn(e),{status:y}=useAuth(),v=useWallets().find(O=>O.chainNamespace===ChainNamespace.SOLANA&&O.isConnected)?.address,{data:h,isLoading:b}=Nn({walletAddress:v??""},{enabled:(n==="trade-history"||n==="positions")&&y==="authenticated"&&!!v}),x=(h?.trades??[]).filter(O=>O.marketTicker===e.ticker),m=useMemo(()=>p.map(O=>{let R=x.filter(Ee=>Ee.outputMint===O.mint&&Ee.usdPricePerContract!=null&&Ee.contracts!=null&&Ee.contracts>0),C=yp(R),V=O.position==="YES"?ko(O.market?.yesAsk):ko(O.market?.noAsk),Q=null,Le=null;return C!=null&&V!=null&&(Q=(V-C)*O.balance,Le=C>0?(V-C)/C*100:null),{...O,avgCost:C,currentPrice:V,pnl:Q,pnlPercent:Le}}),[p,x]),P=useCallback((O,R)=>{t?.(e,"yes",R==="ask"?"buy":"sell");},[e,t]),w=useCallback((O,R)=>{t?.(e,"no",R==="ask"?"buy":"sell");},[e,t]);return jsxs("div",{className:"flex flex-col gap-y-3",children:[jsxs(Tabs,{variant:"underlined",selectedKey:n,onSelectionChange:O=>s(O),classNames:{tabList:"gap-x-4",tab:"px-0"},children:[jsx(Tab,{title:r("predict.market.tradeYes")},"trade-yes"),jsx(Tab,{title:r("predict.market.tradeNo")},"trade-no"),jsx(Tab,{title:r("predict.market.graph")},"graph"),jsx(Tab,{title:r("predict.positions.title")},"positions"),jsx(Tab,{title:r("predict.tradeHistory.title")},"trade-history")]}),jsxs("div",{className:"min-h-[120px]",children:[n==="trade-yes"&&jsx(qr,{bids:i?.yesBids??[],asks:i?.yesAsks??[],isLoading:l,onPriceClick:P}),n==="trade-no"&&jsx(qr,{bids:i?.noBids??[],asks:i?.noAsks??[],isLoading:l,onPriceClick:w}),n==="graph"&&jsx(lo,{candlesticks:c,isLoading:u,chartRange:a,onRangeChange:o}),n==="positions"&&jsx(vo,{positions:m,isLoading:d}),n==="trade-history"&&jsx(xo,{trades:x,isLoading:b})]})]})}function yp(e){if(e.length===0)return null;let t=0,r=0;for(let n of e)t+=n.contracts,r+=n.usdPricePerContract*n.contracts;return t>0?r/t:null}function ko(e){if(e==null)return null;let t=Number(e);return Number.isFinite(t)?t:null}var Kr=4;function vp(e){let t=e.yesAsk?Math.round(parseFloat(e.yesAsk)*100):null,r=e.noAsk?Math.round(parseFloat(e.noAsk)*100):null;return {yesCents:t,noCents:r}}function To({markets:e,renderMarketDetail:t,onTradeAction:r,marketHoldings:n}){let{t:s}=useTranslation(),[a,o]=useState(false),[i,l]=useState(null);if(e.length===0)return null;let c=e.length>Kr,u=a?e:e.slice(0,Kr),p=d=>{l(y=>y===d?null:d);};return jsxs("div",{className:"flex flex-col divide-y divide-default-200",children:[u.map(d=>{let{yesCents:y,noCents:f}=vp(d),g=i===d.ticker;return jsxs("div",{className:"flex flex-col",children:[jsxs("div",{className:"flex items-center gap-x-3 px-2 py-3 transition-colors hover:bg-content2 lg:gap-x-4 cursor-pointer",onClick:()=>p(d.ticker),role:"button",tabIndex:0,onKeyDown:v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),p(d.ticker));},children:[jsxs("div",{className:"flex flex-col gap-y-1 min-w-0 flex-1",children:[jsx("span",{className:"text-sm font-medium truncate lg:text-base",children:d.yesSubTitle}),(()=>{let v=n?.get(d.ticker);if(!v)return null;let{yesShares:h,noShares:b}=v;return h<=0&&b<=0?null:jsxs("div",{className:"flex items-center gap-x-1.5",children:[h>0&&jsx(Chip,{size:"sm",variant:"flat",color:"primary",classNames:{base:"h-5",content:"text-[10px] font-medium px-1"},children:s("predict.market.sharesYes",{shares:h%1===0?h:h.toFixed(2)})}),b>0&&jsx(Chip,{size:"sm",variant:"flat",color:"secondary",classNames:{base:"h-5",content:"text-[10px] font-medium px-1"},children:s("predict.market.sharesNo",{shares:b%1===0?b:b.toFixed(2)})})]})})()]}),(()=>{let v=y!=null,h=f!=null;return v&&!h&&y<=1?jsx("span",{className:"text-lg font-bold shrink-0 text-center text-default-400 lg:text-xl",children:"< 1%"}):h&&!v&&f<=1?jsx("span",{className:"text-lg font-bold shrink-0 text-center text-default-400 lg:text-xl",children:"> 99%"}):!v&&!h?jsx("span",{className:"text-lg font-bold shrink-0 text-center text-default-400 lg:text-xl",children:"0%"}):jsx("span",{className:"text-lg font-bold shrink-0 text-center lg:text-xl",children:`${y}%`})})(),jsxs("div",{className:"flex items-center gap-x-2 flex-1 justify-end",children:[jsx(Button,{size:"sm",color:"primary",className:"w-20 bg-primary-100 text-primary",onPress:()=>r?.(d,"yes","buy"),children:y!=null?s("predict.market.action.yes",{price:y}):s("predict.market.yes")}),jsx(Button,{size:"sm",color:"secondary",className:"w-20 bg-secondary-100 text-secondary",onPress:()=>r?.(d,"no","buy"),children:f!=null?s("predict.market.action.no",{price:f}):s("predict.market.no")})]}),g?jsx(ChevronUpIcon,{className:"h-4 w-4 shrink-0 text-default-400"}):jsx(ChevronDownIcon,{className:"h-4 w-4 shrink-0 text-default-400"})]}),g&&t&&jsx("div",{className:"max-h-100 overflow-y-auto px-2 pb-3",children:t(d)})]},d.ticker)}),c&&jsx("button",{type:"button",onClick:()=>o(d=>!d),className:"flex items-center justify-center gap-x-1.5 px-2 py-2.5 text-sm text-default-500 transition-colors cursor-pointer hover:text-primary",children:a?jsxs(Fragment,{children:[jsx("span",{children:s("predict.event.rules.collapse")}),jsx(ChevronUpIcon,{className:"h-4 w-4"})]}):jsxs(Fragment,{children:[jsx("span",{children:s("predict.event.moreMarkets",{count:e.length-Kr})}),jsx(ChevronDownIcon,{className:"h-4 w-4"})]})})]})}var Pp=new Set(["closed","determined","finalized"]);function zt(e){let t=new Date(e*1e3),r=t.toLocaleString("default",{month:"short"}),n=t.getDate(),s=t.getFullYear(),a=t.getHours().toString().padStart(2,"0"),o=t.getMinutes().toString().padStart(2,"0");return `${r} ${n}, ${s} ${a}:${o}`}function Sp({market:e}){let t=Pp.has(e.status),r=useMemo(()=>{let s={label:"Market Open",value:zt(e.openTime),isActive:true},a={label:"Market Closes",value:t?zt(e.closeTime):"After the outcome occurs",isActive:t},o={label:"Projected Payout",value:"30 minutes after closing",isActive:e.status==="finalized"};return [s,a,o]},[e.openTime,e.closeTime,e.status,t]),n=useMemo(()=>t?null:e.canCloseEarly&&e.earlyCloseCondition?`${e.earlyCloseCondition} Otherwise, it closes by ${zt(e.expirationTime)}.`:`This market closes by ${zt(e.expirationTime)}.`,[t,e.canCloseEarly,e.earlyCloseCondition,e.expirationTime]);return jsxs("div",{className:"flex flex-col",children:[r.map((s,a)=>jsxs("div",{className:"flex items-stretch gap-x-3",children:[jsxs("div",{className:"flex flex-col items-center w-3",children:[jsx("div",{className:`h-3 w-3 shrink-0 rounded-full border-2 mt-0.5 ${s.isActive?"border-primary bg-primary":"border-default-300 bg-transparent"}`}),a<r.length-1&&jsx("div",{className:"w-px flex-1 bg-default-200"})]}),jsxs("div",{className:`flex flex-col ${a<r.length-1?"pb-4":""}`,children:[jsx("span",{className:"text-xs font-medium text-foreground lg:text-sm",children:s.label}),jsx("span",{className:"text-xs text-default-500 lg:text-sm",children:s.value})]})]},s.label)),n&&jsx("p",{className:"text-xs text-default-500 mt-3 lg:text-sm",children:n})]})}function No({markets:e,event:t,series:r}){let{t:n}=useTranslation(),[s,a]=useState(null),o=e.filter(l=>l.rulesPrimary);if(o.length===0)return null;let i=o.find(l=>l.ticker===s)??o[0];return i?.rulesPrimary?jsxs("div",{className:"flex flex-col gap-y-2",children:[jsx("span",{className:"text-sm font-medium lg:text-base",children:n("predict.event.rules")}),o.length>1&&jsx(Select,{size:"sm","aria-label":"Select market rules",className:"max-w-48",classNames:{trigger:"min-h-8 h-8",value:"text-xs"},selectedKeys:new Set([i.ticker]),onSelectionChange:l=>{if(l==="all")return;let c=Array.from(l);c.length>0&&a(c[0]);},children:o.map(l=>jsx(SelectItem,{textValue:l.yesSubTitle,children:jsx("span",{className:"text-xs truncate",children:l.yesSubTitle})},l.ticker))}),jsx("div",{className:"text-xs text-foreground lg:text-sm",children:i.rulesPrimary}),jsx("span",{className:"text-xs font-medium text-default-500 mt-2 lg:text-sm",children:"Timeline and payout"}),jsx(Sp,{market:i}),jsxs("div",{className:"flex flex-wrap items-center gap-x-3 text-xxs text-default-400 mt-2 lg:text-xs",children:[r?.ticker&&jsxs("span",{children:[jsx("span",{className:"text-default-500",children:"Series:"})," ",jsx("span",{className:"text-foreground",children:r.ticker})]}),t.ticker&&jsxs("span",{children:[jsx("span",{className:"text-default-500",children:"Event:"})," ",jsx("span",{className:"text-foreground",children:t.ticker})]}),jsxs("span",{children:[jsx("span",{className:"text-default-500",children:"Market:"})," ",jsx("span",{className:"text-foreground",children:i.ticker})]})]})]}):null}var Ip=[{value:S.ONE_DAY,label:"1D"},{value:S.ONE_WEEK,label:"1W"},{value:S.ONE_MONTH,label:"1M"},{value:S.ALL,label:"ALL"}];function Io({event:e,series:t,candlesticks:r,chartRange:n=S.ONE_DAY,periodInterval:s,isCandlesticksLoading:a,onRangeChange:o,selectedMarketTickers:i,onMarketSelectionChange:l,onTradeAction:c}){let{t:u}=useTranslation(),[p,d]=useState(Ht()),[y,f]=useState(false),g=useRef(null);useEffect(()=>{let m=g.current;if(!m)return;let P=false,w=0,O=()=>{let{bottom:C}=m.getBoundingClientRect(),V=P?C<0:C<-20;V!==P&&(P=V,f(V));},R=()=>{cancelAnimationFrame(w),w=requestAnimationFrame(O);};return window.addEventListener("scroll",R,{passive:true,capture:true}),O(),()=>{cancelAnimationFrame(w),window.removeEventListener("scroll",R,{capture:true});}},[]);let v=useMemo(()=>[...e.markets||[]].sort((m,P)=>Number(P.yesAsk??0)-Number(m.yesAsk??0)),[e.markets]),{holdings:h}=ro(v),b=useMemo(()=>formatAmountUSDCompact((e.volume??0)/100),[e.volume]),x=useMemo(()=>{if(!e.strikeDate)return null;let m=new Date(e.strikeDate*1e3),P=m.toLocaleString("default",{month:"short"}),w=m.getDate(),O=m.getFullYear();return `${P} ${w}, ${O}`},[e.strikeDate]);return jsxs("div",{className:"w-full flex flex-col gap-4 lg:gap-y-6 px-1 pb-8 lg:px-4 lg:pb-12 lg:max-w-3xl",children:[jsx("div",{ref:g,className:"h-0 w-0"}),jsxs("div",{className:`sticky top-0 z-30 flex items-center bg-background/80 backdrop-blur-md transition-all duration-300 ${y?"gap-x-2 py-2 px-1 lg:px-4 -mx-1 lg:-mx-4 shadow-sm":"gap-x-2 lg:gap-x-4"}`,children:[jsx(Avatar,{src:e.imageUrl||void 0,name:e.title||"Event",radius:"lg",className:`flex-shrink-0 transition-all duration-300 ${y?"!h-8 !w-8 lg:!h-10 lg:!w-10":"!h-14 !w-14 lg:!h-18 lg:!w-18"}`}),jsxs("div",{className:"flex flex-col min-w-0",children:[!y&&(t?.category||t?.tags&&t.tags.length>0)&&jsxs("span",{className:"text-xs text-default-500 lg:text-sm truncate",children:[t.category,t.category&&t.tags?.length>0&&" \xB7 ",t.tags?.join(", ")]}),jsx("span",{className:`font-semibold truncate transition-all duration-300 ${y?"text-sm lg:text-base":"text-lg lg:text-xl"}`,children:e.title})]})]}),jsx("div",{className:"flex flex-col gap-y-4",children:jsxs("div",{className:"flex flex-col",children:[p&&p.markets.length>0&&jsx("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2 text-xs lg:text-sm",children:p.markets.map(m=>jsxs("div",{className:"flex items-center gap-x-2",children:[jsx("div",{className:"h-3 w-3 shrink-0 rounded-full",style:{backgroundColor:m.color}}),jsx("span",{className:"text-default-600",children:m.label})]},m.id))}),jsx(qt,{candlesticks:r,chartRange:n,markets:v,isLoading:a,onDataChange:m=>d(m)}),jsxs("div",{className:"flex flex-wrap items-center justify-between gap-x-4 gap-y-2 mt-2",children:[jsxs("div",{className:"flex items-center gap-x-3 text-xs text-default-500 lg:text-sm",children:[jsxs("span",{children:[b," ",u("predict.event.volume")]}),x&&jsxs(Fragment,{children:[jsx("span",{className:"text-default-300",children:"\xB7"}),jsx("span",{children:u("predict.event.endDate",{date:x})})]})]}),jsx("div",{className:"flex items-center gap-x-1",children:Ip.map(m=>jsx("button",{type:"button",onClick:()=>o?.(m.value),className:`px-2 lg:px-3 py-1 text-xs rounded-md transition-colors cursor-pointer ${n===m.value?"bg-primary text-primary-foreground":"bg-default-100 text-default-600 hover:bg-default-200"}`,children:m.label},m.value))}),v.length>1&&jsx(Select,{size:"sm",selectionMode:"multiple",placeholder:"Markets","aria-label":"Select markets",className:"min-w-28 max-w-48",classNames:{trigger:"min-h-8 h-8",value:"text-xs"},selectedKeys:i?new Set(i):void 0,onSelectionChange:m=>{if(m==="all")return;let P=Array.from(m);P.length<=4&&l?.(P);},children:jsx(SelectSection,{title:`Pick up to ${4} markets`,classNames:{heading:"text-xs text-default-400 px-2 py-1"},children:v.map(m=>jsx(SelectItem,{textValue:m.yesSubTitle,children:jsx("span",{className:"text-xs truncate",children:m.yesSubTitle})},m.ticker))})})]})]})}),jsx(To,{markets:v,onTradeAction:c,marketHoldings:h,renderMarketDetail:m=>jsx($t,{market:m,onTradeAction:c})}),jsx(No,{markets:v,event:e,series:t})]})}function Gr({eventId:e,initialMarketTickers:t,initialChartRange:r=le,onTradeAction:n}){let[s,a]=useState(r),[o,i]=useState(t),{event:l,isEventLoading:c,eventError:u,series:p,isSeriesLoading:d,periodInterval:y,candlesticks:f,isCandlesticksLoading:g,candlestickErrors:v}=to({eventId:e,candlestickMarketTickers:o,chartRange:s}),h=useRef(!!t);useEffect(()=>{if(l?.markets&&!h.current){h.current=true;let m=[...l.markets].sort((P,w)=>Number(w.yesAsk??0)-Number(P.yesAsk??0)).slice(0,4).map(P=>P.ticker);i(m);}},[l?.markets]);let b=useMemo(()=>m=>{a(m);},[]),x=useMemo(()=>m=>{i(m);},[]);return c||d?jsx(ge,{}):u||!l?jsx("div",{className:"flex w-full items-center justify-center py-20 text-danger",children:u?.message||"Event not found"}):jsx(Io,{event:l,series:p,candlesticks:f,chartRange:s,periodInterval:y,isCandlesticksLoading:g,candlestickErrors:v,onRangeChange:b,selectedMarketTickers:o,onMarketSelectionChange:x,onTradeAction:n})}function fS({eventId:e,chain:t,...r}){let{t:n}=useTranslation(),{isMobile:s}=useScreen(),{isOpen:a,onOpen:o,onClose:i}=useDisclosure(),{data:l,isLoading:c}=Tt({id:e,withNestedMarkets:true}),u=useMemo(()=>[...l?.markets||[]].sort((v,h)=>Number(h.yesAsk??0)-Number(v.yesAsk??0)),[l?.markets]),[p,d]=useState(null),y=useCallback((v,h,b)=>{d(x=>({market:v,outcome:h,side:b,version:(x?.version??0)+1})),s&&o();},[s,o]),f=p?.market??u[0];if(c)return s?jsx(ge,{}):jsxs("div",{className:"flex w-full max-w-6xl mx-auto gap-x-4 lg:gap-x-6",children:[jsx("div",{className:"min-w-0 flex-1 max-w-3xl",children:jsx(ge,{})}),jsx("aside",{className:"hidden lg:block w-[340px] xl:w-[380px] shrink-0",children:jsx("div",{className:"sticky top-4",children:jsx(Ft,{})})})]});let g=p?`${p.market.ticker}-${p.version}`:f?.ticker??"default";return s?jsxs(Fragment,{children:[jsx("div",{className:"w-full pb-20",children:jsx(Gr,{eventId:e,onTradeAction:y,...r})}),f&&jsx("div",{className:"fixed inset-x-0 bottom-0 z-40 flex justify-center p-3 bg-gradient-to-t from-background via-background/90 to-transparent",children:jsx(Button,{color:"primary",size:"lg",className:"w-full max-w-md font-semibold",onPress:o,children:n("predict.trade.action")})}),jsx(Drawer,{isOpen:a,onClose:i,placement:"bottom",size:"lg",hideCloseButton:true,classNames:{base:"max-h-[85dvh] rounded-t-2xl",body:"p-0"},children:jsx(DrawerContent,{children:jsx(DrawerBody,{children:f&&jsx(je,{event:l,market:f,initialSide:p?.side,initialOutcome:p?.outcome,chain:t},g)})})})]}):jsxs("div",{className:"flex w-full max-w-6xl mx-auto gap-x-4 lg:gap-x-6",children:[jsx("div",{className:"min-w-0 flex-1 max-w-3xl",children:jsx(Gr,{eventId:e,onTradeAction:y,...r})}),f&&jsx("aside",{className:"hidden lg:block w-[340px] xl:w-[380px] shrink-0",children:jsx("div",{className:"sticky top-4 flex flex-col gap-y-4",children:jsx(je,{event:l,market:f,initialSide:p?.side,initialOutcome:p?.outcome,chain:t},g)})})]})}function Yt(e){if(!e)return 0;let t=new Date(e).getTime();return Number.isFinite(t)?Math.floor(t/1e3):0}function Gt(e){return e==null?null:String(Math.round(e*100))}var zp={pending:"initialized",open:"active",closed:"determined",voided:"finalized"};function Xe(e){let t=e.outcomes[0],r=e.outcomes[1];return {ticker:e.slug,eventTicker:e.event_slug,marketType:"binary",title:e.question,subtitle:e.description??e.question,yesSubTitle:e.question,noSubTitle:r?.label??"No",openTime:Yt(e.start_at),closeTime:Yt(e.end_at),expirationTime:Yt(e.expires_at??e.end_at),status:zp[e.status]??"active",volume:e.volume??0,result:e.result??"",openInterest:e.open_interest??0,canCloseEarly:false,rulesPrimary:e.rules?.[0]??"",accounts:{},yesAsk:Gt(t?.best_ask??t?.price),yesBid:Gt(t?.best_bid),noAsk:Gt(r?.best_ask??r?.price),noBid:Gt(r?.best_bid),rulesSecondary:e.rules?.slice(1).join(`
20
- `)??null}}function Bo(e){return {ticker:e.slug,seriesTicker:"",title:e.title,subtitle:e.subtitle??"",imageUrl:e.image_url,liquidity:e.liquidity,openInterest:e.open_interest,volume:e.volume!=null?Math.round(e.volume*100):null,volume24h:e.volume_24h!=null?Math.round(e.volume_24h*100):null,strikeDate:Yt(e.end_at),settlementSources:e.settlement_sources?.map(t=>({name:t.name??"",url:t.url})),markets:e.markets?.map(Xe)}}function _o(e){return e.outcomes[0]?.best_ask??e.outcomes[0]?.price??0}function Yp(e){if(!e)return 0;let t=new Date(e).getTime();return Number.isFinite(t)?Math.floor(t/1e3):0}var Qo=e=>{let{candlestickMarketSlugs:t,chartRange:r=le,source:n}=e,s=He[r],a=Ke[r],o=useMemo(()=>Math.floor(Date.now()/1e3),[r]),i=k(),{data:l,isLoading:c,error:u}=wt({slug:e.eventSlug,source:n}),p=useMemo(()=>{if(a!=null)return o-a;let h=l?.markets;return h?.length?Math.min(...h.map(b=>Yp(b.start_at))):o},[o,a,l?.markets]),d=useMemo(()=>l?.markets?(t&&t.length>0?t.slice(0,4).map(b=>l.markets.find(x=>x.slug===b)).filter(b=>b!==void 0):[...l.markets].sort((b,x)=>_o(x)-_o(b)).slice(0,4)).map(b=>b.slug):[],[t,l?.markets]),y=useQueries({queries:d.map(h=>({queryKey:rt({ticker:h,startTs:p,endTs:o,periodInterval:s}),queryFn:()=>nt(i,{ticker:h,startTs:p,endTs:o,periodInterval:s}),enabled:d.length>0}))}),f=y.some(h=>h.isLoading),g=useMemo(()=>{let h=new Map;return d.forEach((b,x)=>{let m=y[x]?.error;m&&h.set(b,m);}),h},[d,y]),v=useMemo(()=>{let h=new Map;return d.forEach((b,x)=>{let m=y[x]?.data;m&&h.set(b,m);}),h},[d,y]);return {event:l,isEventLoading:c,eventError:u,periodInterval:s,candlesticks:v,isCandlesticksLoading:f,candlestickErrors:g}};function Xr(e){return e.outcomes[0]?.best_ask??e.outcomes[0]?.price??0}function tm(e){let t=Math.round(e*100);return t<=1&&e>0?"< 1%":t>=99&&e<1?"> 99%":`${t}%`}function rm(e){if(!e)return null;try{let t=new Date(e);return isNaN(t.getTime())?null:t.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}catch{return null}}function qo(e){switch(e){case "polymarket":return "Polymarket";case "dflow":return "Kalshi";default:return e}}var nm=[{value:S.ONE_DAY,label:"1D"},{value:S.ONE_WEEK,label:"1W"},{value:S.ONE_MONTH,label:"1M"},{value:S.ALL,label:"ALL"}];function Ho({event:e,candlesticks:t,chartRange:r=S.ONE_DAY,isCandlesticksLoading:n,onRangeChange:s,selectedMarketSlugs:a,onMarketSelectionChange:o,onTradeAction:i}){let{t:l}=useTranslation(),[c,u]=useState(Ht()),[p,d]=useState(false),y=useRef(null);useEffect(()=>{let b=y.current;if(!b)return;let x=false,m=0,P=()=>{let{bottom:O}=b.getBoundingClientRect(),R=x?O<0:O<-20;R!==x&&(x=R,d(R));},w=()=>{cancelAnimationFrame(m),m=requestAnimationFrame(P);};return window.addEventListener("scroll",w,{passive:true,capture:true}),P(),()=>{cancelAnimationFrame(m),window.removeEventListener("scroll",w,{capture:true});}},[]);let f=useMemo(()=>[...e.markets||[]].sort((b,x)=>Xr(x)-Xr(b)),[e.markets]),g=useMemo(()=>formatAmountUSDCompact(e.volume??0),[e.volume]),v=useMemo(()=>rm(e.end_at),[e.end_at]),h=useMemo(()=>f.map(Xe),[f]);return jsxs("div",{className:"w-full flex flex-col gap-4 lg:gap-y-6 px-1 pb-8 lg:px-4 lg:pb-12 lg:max-w-3xl",children:[jsx("div",{ref:y,className:"h-0 w-0"}),jsxs("div",{className:`sticky top-0 z-30 flex items-center bg-background/80 backdrop-blur-md transition-all duration-300 ${p?"gap-x-2 py-2 px-1 lg:px-4 -mx-1 lg:-mx-4 shadow-sm":"gap-x-2 lg:gap-x-4"}`,children:[jsx(Avatar,{src:e.image_url||void 0,name:e.title||"Event",radius:"lg",className:`flex-shrink-0 transition-all duration-300 ${p?"!h-8 !w-8 lg:!h-10 lg:!w-10":"!h-14 !w-14 lg:!h-18 lg:!w-18"}`}),jsxs("div",{className:"flex flex-col min-w-0 flex-1",children:[!p&&jsxs("div",{className:"flex items-center gap-1.5",children:[jsx(am,{source:e.source}),e.tags?.slice(0,3).map(b=>jsx("span",{className:"text-xs text-default-500 truncate",children:b.label},b.slug))]}),jsx("span",{className:`font-semibold truncate transition-all duration-300 ${p?"text-sm lg:text-base":"text-lg lg:text-xl"}`,children:e.title})]})]}),jsx("div",{className:"flex flex-col gap-y-4",children:jsxs("div",{className:"flex flex-col",children:[c&&c.markets.length>0&&jsx("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2 text-xs lg:text-sm",children:c.markets.map(b=>jsxs("div",{className:"flex items-center gap-x-2",children:[jsx("div",{className:"h-3 w-3 shrink-0 rounded-full",style:{backgroundColor:b.color}}),jsx("span",{className:"text-default-600",children:b.label})]},b.id))}),jsx(qt,{candlesticks:t,chartRange:r,markets:h,isLoading:n,onDataChange:b=>u(b)}),jsxs("div",{className:"flex flex-wrap items-center justify-between gap-x-4 gap-y-2 mt-2",children:[jsxs("div",{className:"flex items-center gap-x-3 text-xs text-default-500 lg:text-sm",children:[jsxs("span",{children:[g," ",l("predict.event.volume")]}),v&&jsxs(Fragment,{children:[jsx("span",{className:"text-default-300",children:"\xB7"}),jsx("span",{children:l("predict.event.endDate",{date:v})})]})]}),jsx("div",{className:"flex items-center gap-x-1",children:nm.map(b=>jsx("button",{type:"button",onClick:()=>s?.(b.value),className:`px-2 lg:px-3 py-1 text-xs rounded-md transition-colors cursor-pointer ${r===b.value?"bg-primary text-primary-foreground":"bg-default-100 text-default-600 hover:bg-default-200"}`,children:b.label},b.value))}),f.length>1&&jsx(Select,{size:"sm",selectionMode:"multiple",placeholder:"Markets","aria-label":"Select markets",className:"min-w-28 max-w-48",classNames:{trigger:"min-h-8 h-8",value:"text-xs"},selectedKeys:a?new Set(a):void 0,onSelectionChange:b=>{if(b==="all")return;let x=Array.from(b);x.length<=4&&o?.(x);},children:jsx(SelectSection,{title:`Pick up to ${4} markets`,classNames:{heading:"text-xs text-default-400 px-2 py-1"},children:f.map(b=>jsx(SelectItem,{textValue:b.question,children:jsx("span",{className:"text-xs truncate",children:b.question})},b.slug))})})]})]})}),jsx(sm,{markets:f,onTradeAction:i}),jsx(om,{markets:f,event:e})]})}var jr=4;function sm({markets:e,onTradeAction:t}){let{t:r}=useTranslation(),[n,s]=useState(false),[a,o]=useState(null);if(e.length===0)return null;let i=e.length>jr,l=n?e:e.slice(0,jr),c=u=>{o(p=>p===u?null:u);};return jsxs("div",{className:"flex flex-col divide-y divide-default-200",children:[l.map(u=>{let p=Xr(u),d=u.outcomes[1]?.best_ask??u.outcomes[1]?.price,y=Math.round(p*100),f=d!=null?Math.round(d*100):null,g=a===u.slug;return jsxs("div",{className:"flex flex-col",children:[jsxs("div",{className:"flex items-center gap-x-3 px-2 py-3 transition-colors hover:bg-content2 lg:gap-x-4 cursor-pointer",onClick:()=>c(u.slug),role:"button",tabIndex:0,onKeyDown:v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),c(u.slug));},children:[jsx("div",{className:"flex flex-col gap-y-1 min-w-0 flex-1",children:jsx("span",{className:"text-sm font-medium truncate lg:text-base",children:u.question})}),jsx("span",{className:"text-lg font-bold shrink-0 text-center lg:text-xl",children:tm(p)}),jsxs("div",{className:"flex items-center gap-x-2 flex-1 justify-end",children:[jsx(Button,{size:"sm",color:"primary",className:"w-20 bg-primary-100 text-primary",onPress:()=>t?.(u,"yes","buy"),children:r("predict.market.action.yes",{price:y})}),jsx(Button,{size:"sm",color:"secondary",className:"w-20 bg-secondary-100 text-secondary",onPress:()=>t?.(u,"no","buy"),children:f!=null?r("predict.market.action.no",{price:f}):r("predict.market.no")})]})]}),g&&jsx("div",{className:"max-h-100 overflow-y-auto px-2 pb-3",children:jsx($t,{market:Xe(u),onTradeAction:t?(v,h,b)=>t(u,h,b):void 0})})]},u.slug)}),i&&jsx("button",{type:"button",onClick:()=>s(u=>!u),className:"flex items-center justify-center gap-x-1.5 px-2 py-2.5 text-sm text-default-500 transition-colors cursor-pointer hover:text-primary",children:n?r("predict.event.rules.collapse"):r("predict.event.moreMarkets",{count:e.length-jr})})]})}function Uo(e){if(!e)return "\u2014";let t=new Date(e);if(isNaN(t.getTime()))return "\u2014";let r=t.toLocaleString("default",{month:"short"}),n=t.getDate(),s=t.getFullYear(),a=t.getHours().toString().padStart(2,"0"),o=t.getMinutes().toString().padStart(2,"0");return `${r} ${n}, ${s} ${a}:${o}`}function om({markets:e,event:t}){let{t:r}=useTranslation(),[n,s]=useState(null),a=e.filter(i=>i.rules&&i.rules.length>0);if(a.length===0)return null;let o=a.find(i=>i.slug===n)??a[0];return o?.rules?.length?jsxs("div",{className:"flex flex-col gap-y-2",children:[jsx("span",{className:"text-sm font-medium lg:text-base",children:r("predict.event.rules")}),a.length>1&&jsx(Select,{size:"sm","aria-label":"Select market rules",className:"max-w-48",classNames:{trigger:"min-h-8 h-8",value:"text-xs"},selectedKeys:new Set([o.slug]),onSelectionChange:i=>{if(i==="all")return;let l=Array.from(i);l.length>0&&s(l[0]);},children:a.map(i=>jsx(SelectItem,{textValue:i.question,children:jsx("span",{className:"text-xs truncate",children:i.question})},i.slug))}),jsx("div",{className:"text-xs text-foreground lg:text-sm space-y-1",children:o.rules.map((i,l)=>jsx("p",{children:i},l))}),jsx("span",{className:"text-xs font-medium text-default-500 mt-2 lg:text-sm",children:"Timeline"}),jsx("div",{className:"flex flex-col",children:[{label:"Market Open",value:Uo(o.start_at),isActive:true},{label:"Market Closes",value:Uo(o.end_at),isActive:o.status==="closed"||o.status==="voided"}].map((i,l,c)=>jsxs("div",{className:"flex items-stretch gap-x-3",children:[jsxs("div",{className:"flex flex-col items-center w-3",children:[jsx("div",{className:`h-3 w-3 shrink-0 rounded-full border-2 mt-0.5 ${i.isActive?"border-primary bg-primary":"border-default-300 bg-transparent"}`}),l<c.length-1&&jsx("div",{className:"w-px flex-1 bg-default-200"})]}),jsxs("div",{className:`flex flex-col ${l<c.length-1?"pb-4":""}`,children:[jsx("span",{className:"text-xs font-medium text-foreground lg:text-sm",children:i.label}),jsx("span",{className:"text-xs text-default-500 lg:text-sm",children:i.value})]})]},i.label))}),jsxs("div",{className:"flex flex-wrap items-center gap-x-3 text-xxs text-default-400 mt-2 lg:text-xs",children:[jsxs("span",{children:[jsx("span",{className:"text-default-500",children:"Event:"})," ",jsx("span",{className:"text-foreground",children:t.slug})]}),jsxs("span",{children:[jsx("span",{className:"text-default-500",children:"Market:"})," ",jsx("span",{className:"text-foreground",children:o.slug})]}),jsxs("span",{children:[jsx("span",{className:"text-default-500",children:"Source:"})," ",jsx("span",{className:"text-foreground",children:qo(o.source)})]})]})]}):null}function am({source:e}){return jsxs("span",{className:cn("inline-flex items-center gap-x-1 rounded px-1.5 py-0.5","text-[10px] font-medium leading-none",e==="polymarket"?"bg-blue-500/15 text-blue-400":"bg-primary-500/15 text-primary"),children:[jsx("span",{className:cn("h-1.5 w-1.5 rounded-sm",e==="polymarket"?"bg-blue-400":"bg-primary")}),qo(e)]})}function zo(e){return e.outcomes[0]?.best_ask??e.outcomes[0]?.price??0}function en({eventSlug:e,source:t,initialMarketSlugs:r,initialChartRange:n=le,onTradeAction:s}){let[a,o]=useState(n),[i,l]=useState(r),{event:c,isEventLoading:u,eventError:p,periodInterval:d,candlesticks:y,isCandlesticksLoading:f,candlestickErrors:g}=Qo({eventSlug:e,source:t,candlestickMarketSlugs:i,chartRange:a}),v=useRef(!!r);useEffect(()=>{if(c?.markets&&!v.current){v.current=true;let x=[...c.markets].sort((m,P)=>zo(P)-zo(m)).slice(0,4).map(m=>m.slug);l(x);}},[c?.markets]);let h=useMemo(()=>x=>o(x),[]),b=useMemo(()=>x=>l(x),[]);return u?jsx(ge,{}):p||!c?jsx("div",{className:"flex w-full items-center justify-center py-20 text-danger",children:p?.message||"Event not found"}):jsx(Ho,{event:c,candlesticks:y,chartRange:a,periodInterval:d,isCandlesticksLoading:f,candlestickErrors:g,onRangeChange:h,selectedMarketSlugs:i,onMarketSelectionChange:b,onTradeAction:s})}function Go(e){return e.outcomes[0]?.best_ask??e.outcomes[0]?.price??0}function jS({eventSlug:e,source:t,chain:r,...n}){let{t:s}=useTranslation(),{isMobile:a}=useScreen(),{isOpen:o,onOpen:i,onClose:l}=useDisclosure(),{data:c,isLoading:u}=wt({slug:e,source:t}),p=useMemo(()=>[...c?.markets||[]].sort((x,m)=>Go(m)-Go(x)),[c?.markets]),[d,y]=useState(null),f=useCallback((x,m,P)=>{y(w=>({market:x,outcome:m,side:P,version:(w?.version??0)+1})),a&&i();},[a,i]),g=d?.market??p[0],v=useMemo(()=>c?Bo(c):void 0,[c]),h=useMemo(()=>g?Xe(g):void 0,[g]);if(u)return a?jsx(ge,{}):jsxs("div",{className:"flex w-full max-w-6xl mx-auto gap-x-4 lg:gap-x-6",children:[jsx("div",{className:"min-w-0 flex-1 max-w-3xl",children:jsx(ge,{})}),jsx("aside",{className:"hidden lg:block w-[340px] xl:w-[380px] shrink-0",children:jsx("div",{className:"sticky top-4",children:jsx(Ft,{})})})]});let b=d?`${d.market.slug}-${d.version}`:g?.slug??"default";return a?jsxs(Fragment,{children:[jsx("div",{className:"w-full pb-20",children:jsx(en,{eventSlug:e,source:t,onTradeAction:f,...n})}),h&&jsx("div",{className:"fixed inset-x-0 bottom-0 z-40 flex justify-center p-3 bg-gradient-to-t from-background via-background/90 to-transparent",children:jsx(Button,{color:"primary",size:"lg",className:"w-full max-w-md font-semibold",onPress:i,children:s("predict.trade.action")})}),jsx(Drawer,{isOpen:o,onClose:l,placement:"bottom",size:"lg",hideCloseButton:true,classNames:{base:"max-h-[85dvh] rounded-t-2xl",body:"p-0"},children:jsx(DrawerContent,{children:jsx(DrawerBody,{children:h&&jsx(je,{event:v,market:h,initialSide:d?.side,initialOutcome:d?.outcome,chain:r},b)})})})]}):jsxs("div",{className:"flex w-full max-w-6xl mx-auto gap-x-4 lg:gap-x-6",children:[jsx("div",{className:"min-w-0 flex-1 max-w-3xl",children:jsx(en,{eventSlug:e,source:t,onTradeAction:f,...n})}),h&&jsx("aside",{className:"hidden lg:block w-[340px] xl:w-[380px] shrink-0",children:jsx("div",{className:"sticky top-4 flex flex-col gap-y-4",children:jsx(je,{event:v,market:h,initialSide:d?.side,initialOutcome:d?.outcome,chain:r},b)})})]})}var Xt=4,Yo=["#22d3ee","#a3e635","#f97316","#f472b6","#a78bfa"];function jo(e,t){let r=new Date(e);return t===S.ONE_DAY?r.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:false}):r.toLocaleDateString("en-US",{month:"short",day:"numeric"})}function Xo(e){return `${(e*100).toFixed(2)}%`}var Rm=[{range:S.ONE_DAY,label:"1D"},{range:S.ONE_WEEK,label:"1W"},{range:S.ONE_MONTH,label:"1M"},{range:S.ALL,label:"ALL"}];function Nm({value:e,onChange:t}){return jsx("div",{style:{display:"flex",alignItems:"center",gap:2},children:Rm.map(({range:r,label:n})=>{let s=r===e;return jsx("button",{onClick:()=>t(r),style:{padding:"2px 8px",border:"none",background:"transparent",color:s?"#f9fafb":"#6b7280",fontWeight:s?700:400,fontSize:12,cursor:"pointer",borderRadius:4,letterSpacing:"0.02em",transition:"color 0.15s",userSelect:"none"},children:n},r)})})}function Om({dots:e}){return jsx(Fragment,{children:e.map(({cx:t,cy:r,color:n},s)=>jsxs("g",{children:[jsxs("circle",{cx:t,cy:r,r:6,fill:n,opacity:.3,children:[jsx("animate",{attributeName:"r",values:"4;9;4",dur:"2s",repeatCount:"indefinite"}),jsx("animate",{attributeName:"opacity",values:"0.4;0.05;0.4",dur:"2s",repeatCount:"indefinite"})]}),jsx("circle",{cx:t,cy:r,r:3.5,fill:n})]},s))})}function Im(){let e=useRef(null),t=useRef(null),r=useCallback(s=>{let a=e.current,o=t.current;if(!a||!o)return;let i=a.getBoundingClientRect(),l=(s.clientX-i.left)/i.width*100;o.style.background=`linear-gradient(to right, transparent ${l}%, rgba(0,0,0,0.38) ${l}%)`,o.style.opacity="1";},[]),n=useCallback(()=>{t.current&&(t.current.style.opacity="0");},[]);return {wrapperRef:e,overlayRef:t,onMouseMove:r,onMouseLeave:n}}function Lm({active:e,payload:t,label:r,labelMap:n}){if(!e||!t?.length)return null;let s=[...t].filter(a=>a.value!=null).sort((a,o)=>(o.value??0)-(a.value??0));return jsxs("div",{style:{background:"rgba(10,10,10,0.92)",border:"1px solid rgba(255,255,255,0.1)",borderRadius:8,padding:"8px 12px",minWidth:180,backdropFilter:"blur(8px)",fontSize:12},children:[jsx("div",{style:{color:"#9ca3af",marginBottom:6,fontWeight:500},children:typeof r=="number"?jo(r):r}),s.map(a=>jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:3},children:[jsx("span",{style:{display:"inline-block",width:3,height:14,borderRadius:2,background:a.stroke??a.color,flexShrink:0}}),jsx("span",{style:{color:"#e5e7eb",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:120},children:n.get(a.dataKey)??a.dataKey}),jsx("span",{style:{color:"#f9fafb",fontWeight:700,fontVariantNumeric:"tabular-nums"},children:a.value!=null?Xo(a.value):"-"})]},a.dataKey))]})}function Vm({markets:e,selectedSlugs:t,colorMap:r,onToggle:n}){let[s,a]=useState(false),o=useRef(null);useEffect(()=>{if(!s)return;function c(u){o.current&&!o.current.contains(u.target)&&a(false);}return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[s]);let i=t.length>=Xt,l=jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:0},children:[jsx("div",{style:{display:"flex",gap:3,flexShrink:0},children:t.map(c=>jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:r.get(c)??"#6b7280",display:"inline-block"}},c))}),jsx("span",{style:{color:"#e5e7eb",fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.length===1?e.find(c=>c.slug===t[0])?.question??"1 market":`${t.length} / ${e.length} markets`})]});return jsxs("div",{ref:o,style:{position:"relative",display:"inline-block",maxWidth:320},children:[jsxs("button",{onClick:()=>a(c=>!c),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"5px 10px",borderRadius:8,border:"1px solid rgba(255,255,255,0.12)",background:"rgba(255,255,255,0.05)",cursor:"pointer",minWidth:160,maxWidth:320,userSelect:"none"},children:[l,jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",style:{flexShrink:0,transform:s?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.15s",color:"#6b7280"},children:jsx("path",{d:"M2 4l4 4 4-4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),s&&jsxs("div",{style:{position:"absolute",top:"calc(100% + 4px)",left:0,zIndex:50,background:"#111827",border:"1px solid rgba(255,255,255,0.1)",borderRadius:10,boxShadow:"0 8px 24px rgba(0,0,0,0.5)",minWidth:260,maxWidth:360,maxHeight:320,overflowY:"auto",padding:"6px 0"},children:[jsxs("div",{style:{padding:"4px 12px 8px",fontSize:11,color:"#6b7280",borderBottom:"1px solid rgba(255,255,255,0.06)",marginBottom:4},children:["Select up to ",Xt," markets"]}),e.map(c=>{let u=t.includes(c.slug),p=!u&&i,d=u&&t.length===1,y=r.get(c.slug)??"#6b7280",f=c.outcomes.find(v=>v.label.toLowerCase()==="yes")??c.outcomes[0],g=f?.price!=null?`${Math.round(f.price*100)}%`:null;return jsxs("button",{onClick:()=>{d||p||n(c.slug);},style:{display:"flex",alignItems:"center",gap:10,width:"100%",padding:"7px 12px",border:"none",background:u?"rgba(255,255,255,0.05)":"transparent",cursor:p||d?"not-allowed":"pointer",opacity:p?.35:1,textAlign:"left",transition:"background 0.1s"},onMouseEnter:v=>{!p&&!d&&(v.currentTarget.style.background="rgba(255,255,255,0.07)");},onMouseLeave:v=>{v.currentTarget.style.background=u?"rgba(255,255,255,0.05)":"transparent";},children:[jsx("span",{style:{width:16,height:16,borderRadius:4,border:u?`2px solid ${y}`:"2px solid rgba(255,255,255,0.2)",background:u?`${y}30`:"transparent",flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center"},children:u&&jsx("svg",{width:"9",height:"7",viewBox:"0 0 9 7",fill:"none",children:jsx("path",{d:"M1 3.5L3.5 6L8 1",stroke:y,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:y,flexShrink:0}}),jsx("span",{style:{color:u?"#f9fafb":"#9ca3af",fontSize:12,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:c.question}),g&&jsx("span",{style:{color:y,fontWeight:700,fontSize:12,flexShrink:0},children:g})]},c.slug)})]})]})}function Bm({series:e,colorMap:t,currentValues:r}){return jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px 16px",padding:"0 2px"},children:e.map(n=>{let s=t.get(n.marketSlug)??"#6b7280",a=r.get(n.marketSlug);return jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:6,fontSize:12},children:[jsx("span",{style:{width:10,height:10,borderRadius:"50%",background:s,flexShrink:0}}),jsx("span",{style:{color:"#9ca3af"},children:n.label}),a!=null&&jsx("span",{style:{color:"#f9fafb",fontWeight:700},children:Xo(a)})]},n.marketSlug)})})}function _m(e){if(e.length===0)return [];let t=new Set;e.forEach(a=>a.data.forEach(o=>t.add(o.timestamp)));let r=Array.from(t).sort((a,o)=>a-o),n=e.map(a=>{let o=new Map;return a.data.forEach(i=>o.set(i.timestamp,i.price)),{slug:a.marketSlug,map:o}}),s=new Map;return r.map(a=>{let o={timestamp:a};return n.forEach(({slug:i,map:l})=>{let c=l.get(a);if(c!==void 0)s.set(i,c),o[i]=c;else {let u=s.get(i);u!==void 0&&(o[i]=u);}}),o})}function nC({event:e,isLoading:t}){let r=useMemo(()=>e.markets??[],[e.markets]),[n,s]=useState(()=>r.slice(0,Xt).map(x=>x.slug)),[a,o]=useState(le),i=useMemo(()=>{let x=new Map;return r.forEach((m,P)=>{x.set(m.slug,Yo[P%Yo.length]);}),x},[r]),l=useMemo(()=>r.filter(x=>n.includes(x.slug)),[r,n]),{series:c}=Cn(l,a),u=useMemo(()=>_m(c),[c]),p=useMemo(()=>{if(u.length===0)return [0,1];let x=1/0,m=-1/0;if(n.forEach(w=>{u.forEach(O=>{let R=O[w];R!=null&&(R<x&&(x=R),R>m&&(m=R));});}),!isFinite(x))return [0,1];let P=Math.max((m-x)*.15,.05);return [Math.max(0,x-P),Math.min(1,m+P)]},[u,n]),d=useMemo(()=>{let x=new Map;return c.forEach(m=>{m.data.length>0&&x.set(m.marketSlug,m.data[m.data.length-1].price);}),x},[c]),y=useMemo(()=>{let x=new Map;return c.forEach(m=>x.set(m.marketSlug,m.label)),x},[c]),{wrapperRef:f,overlayRef:g,onMouseMove:v,onMouseLeave:h}=Im(),b=useCallback(x=>{s(m=>m.includes(x)?m.length<=1?m:m.filter(P=>P!==x):m.length>=Xt?m:[...m,x]);},[]);return t?jsx("div",{style:{height:320,display:"flex",alignItems:"center",justifyContent:"center"},children:jsx("div",{style:{width:28,height:28,borderRadius:"50%",border:"2.5px solid #22d3ee",borderTopColor:"transparent",animation:"spin 0.7s linear infinite"}})}):u.length===0?jsx("div",{style:{height:320,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:13},children:"No price history data"}):jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[r.length>1&&jsx(Vm,{markets:r,selectedSlugs:n,colorMap:i,onToggle:b}),jsx(Bm,{series:c,colorMap:i,currentValues:d}),jsxs("div",{style:{display:"flex",flexDirection:"column",gap:0},children:[jsxs("div",{ref:f,style:{height:300,width:"100%",userSelect:"none",position:"relative"},onMouseMove:v,onMouseLeave:h,children:[jsx("div",{ref:g,style:{position:"absolute",inset:0,opacity:0,pointerEvents:"none",zIndex:1}}),jsx(ResponsiveContainer,{width:"100%",height:"100%",children:jsxs(LineChart,{data:u,margin:{top:8,right:16,left:0,bottom:0},children:[jsx(CartesianGrid,{horizontal:true,vertical:false,strokeDasharray:"3 3",stroke:"#374151",opacity:.5}),jsx(XAxis,{dataKey:"timestamp",type:"number",scale:"time",domain:["dataMin","dataMax"],tickFormatter:x=>jo(x,a),axisLine:false,tickLine:false,tick:{fill:"#6b7280",fontSize:11},minTickGap:70}),jsx(YAxis,{domain:p,tickFormatter:x=>`${Math.round(x*100)}%`,axisLine:false,tickLine:false,tick:{fill:"#6b7280",fontSize:11},width:40,tickCount:6}),jsx(Tooltip,{content:x=>jsx(Lm,{...x,labelMap:y}),cursor:{stroke:"#4b5563",strokeWidth:1,strokeDasharray:"4 4"},isAnimationActive:false}),c.map(x=>{let m=i.get(x.marketSlug)??"#6b7280";return jsx(Line,{type:"stepAfter",dataKey:x.marketSlug,stroke:m,strokeWidth:2,dot:false,activeDot:{r:4.5,strokeWidth:2,stroke:"rgba(10,10,10,0.8)",fill:m},connectNulls:true,isAnimationActive:false},x.marketSlug)}),jsx(Customized,{component:x=>{let m=x.xAxisMap?Object.values(x.xAxisMap)[0]?.scale:null,P=x.yAxisMap?Object.values(x.yAxisMap)[0]?.scale:null,w=[];if(m&&P&&u.length>0){let O=u[u.length-1];c.forEach(R=>{let C=O[R.marketSlug];if(C==null)return;let V=m(O.timestamp),Q=P(C);V==null||Q==null||w.push({cx:V,cy:Q,color:i.get(R.marketSlug)??"#6b7280"});});}return jsx(Om,{dots:w})}})]})})]}),jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",paddingRight:4,marginTop:2},children:jsx(Nm,{value:a,onChange:o})})]})]})}function Zo(e,t){if(!e)return [];let r=e.slice(0,t),n=0,s=r.map(o=>(n+=o.quantity,{...o,cumulative:n,depth:0})),a=s[s.length-1]?.cumulative??1;for(let o of s)o.depth=o.cumulative/a;return s}function Jo({marketTicker:e,maxLevels:t=10,refetchInterval:r=5e3,outcome:n="yes"}){let{data:s,isLoading:a,isFetching:o}=ze(e,{refetchInterval:r||void 0}),i=useMemo(()=>n==="yes"?s?.yesBids:s?.noBids,[s,n]),l=useMemo(()=>n==="yes"?s?.yesAsks:s?.noAsks,[s,n]),c=useMemo(()=>Zo(i,t),[i,t]),u=useMemo(()=>Zo(l,t),[l,t]),p=useMemo(()=>c.length===0||u.length===0?null:u[0].price-c[0].price,[c,u]),d=useMemo(()=>c.length===0||u.length===0?null:(c[0].price+u[0].price)/2,[c,u]),y=useMemo(()=>p===null||d===null||d===0?null:Math.round(p/d*1e4)/100,[p,d]);return {bids:c,asks:u,spread:p,spreadPercent:y,midpoint:d,isLoading:a,isFetching:o}}function ea({row:e,side:t,onClick:r}){let n=t==="bid",s=n?"bg-primary/10":"bg-danger/10",a=n?"text-primary":"text-danger";return jsxs("button",{type:"button",className:"relative flex w-full items-center justify-between px-3 py-1 text-xs hover:bg-default-100 cursor-pointer",onClick:()=>r?.(e.price),children:[jsx("div",{className:`absolute inset-y-0 ${n?"right-0":"left-0"} ${s}`,style:{width:`${e.depth*100}%`}}),jsxs("span",{className:`relative z-10 font-medium ${a}`,children:[e.price,"\xA2"]}),jsx("span",{className:"relative z-10 text-default-600",children:e.quantity}),jsx("span",{className:"relative z-10 text-default-400",children:e.cumulative})]})}function ta(){return jsx("div",{className:"flex flex-col gap-y-1 py-2",children:Array.from({length:5}).map((e,t)=>jsx("div",{className:"mx-3 h-4 animate-pulse rounded bg-default-100"},t))})}function ra({bids:e,asks:t,spread:r,spreadPercent:n,isLoading:s,onPriceClick:a}){let{t:o}=useTranslation();if(s)return jsxs("div",{className:"flex w-full flex-col rounded-xl border border-default-200 bg-content1",children:[jsx("div",{className:"border-b border-default-200 px-3 py-2 text-sm font-medium",children:o("predict.orderBook.title")}),jsx(ta,{}),jsx(ta,{})]});let i=e.length===0&&t.length===0;return jsxs("div",{className:"flex w-full flex-col rounded-xl border border-default-200 bg-content1",children:[jsx("div",{className:"flex items-center justify-between border-b border-default-200 px-3 py-2",children:jsx("span",{className:"text-sm font-medium",children:o("predict.orderBook.title")})}),i?jsx("div",{className:"flex items-center justify-center py-8 text-xs text-default-400",children:o("predict.orderBook.empty")}):jsxs(Fragment,{children:[jsxs("div",{className:"flex items-center justify-between px-3 py-1 text-xxs text-default-400",children:[jsx("span",{children:o("predict.orderBook.price")}),jsx("span",{children:o("predict.orderBook.qty")}),jsx("span",{children:o("predict.orderBook.total")})]}),jsx("div",{className:"flex flex-col-reverse",children:t.map(l=>jsx(ea,{row:l,side:"ask",onClick:a},l.price))}),r!==null&&jsxs("div",{className:"flex items-center justify-center gap-x-2 border-y border-default-200 py-1.5 text-xs text-default-500",children:[jsxs("span",{children:[o("predict.orderBook.spread"),": ",r,"\xA2"]}),n!==null&&jsxs("span",{className:"text-default-400",children:["(",n,"%)"]})]}),jsx("div",{className:"flex flex-col",children:e.map(l=>jsx(ea,{row:l,side:"bid",onClick:a},l.price))})]})]})}function NC({marketTicker:e,maxLevels:t,refetchInterval:r,onPriceClick:n,outcome:s}){let{bids:a,asks:o,spread:i,spreadPercent:l,isLoading:c}=Jo({marketTicker:e,maxLevels:t,refetchInterval:r,outcome:s});return jsx(ra,{bids:a,asks:o,spread:i,spreadPercent:l,isLoading:c,onPriceClick:n})}function sa(e={}){let[t,r]=useState(null),[n]=useState(null),s=useCallback(a=>{r(null);},[]);return {orders:[],isLoading:false,isFetching:false,cancellingOrderId:t,cancelOrder:s,cancelError:n}}function Ym(e){return new Date(e).toLocaleString("default",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function oa({orders:e,isLoading:t,cancellingOrderId:r,onCancel:n}){let{t:s}=useTranslation(),a=useMemo(()=>e.map(o=>({key:o.id,side:o.side,outcome:o.outcome,type:o.type,price:o.price,filled:`${o.filledQuantity}/${o.quantity}`,status:o.status,createdAt:Ym(o.createdAt),isCancelling:o.id===r,id:o.id})),[e,r]);return t?jsxs("div",{className:"flex w-full flex-col rounded-xl border border-default-200 bg-content1",children:[jsx("div",{className:"border-b border-default-200 px-3 py-2 text-sm font-medium",children:s("predict.openOrders.title")}),jsx("div",{className:"flex flex-col gap-y-2 p-3",children:Array.from({length:3}).map((o,i)=>jsx("div",{className:"h-8 animate-pulse rounded bg-default-100"},i))})]}):jsxs("div",{className:"flex w-full flex-col rounded-xl border border-default-200 bg-content1",children:[jsxs("div",{className:"border-b border-default-200 px-3 py-2 text-sm font-medium",children:[s("predict.openOrders.title"),e.length>0&&jsxs("span",{className:"ml-1 text-default-400",children:["(",e.length,")"]})]}),e.length===0?jsx("div",{className:"flex items-center justify-center py-8 text-xs text-default-400",children:s("predict.openOrders.empty")}):jsx("div",{className:"w-full overflow-x-auto",children:jsxs(StyledTable,{radius:"none","aria-label":"Open orders",className:"min-w-[600px]",children:[jsxs(TableHeader,{children:[jsx(TableColumn,{textValue:"Side",width:60,children:s("predict.openOrders.side")}),jsx(TableColumn,{textValue:"Outcome",width:60,children:s("predict.openOrders.outcome")}),jsx(TableColumn,{textValue:"Type",width:60,children:s("predict.openOrders.type")}),jsx(TableColumn,{textValue:"Price",width:60,children:s("predict.openOrders.price")}),jsx(TableColumn,{textValue:"Filled",width:80,children:s("predict.openOrders.filled")}),jsx(TableColumn,{textValue:"Status",width:70,children:s("predict.openOrders.status")}),jsx(TableColumn,{textValue:"Time",width:120,children:s("predict.openOrders.time")}),jsx(TableColumn,{textValue:"Action",width:80,align:"end",children:" "})]}),jsx(TableBody,{children:a.map(o=>jsxs(TableRow,{children:[jsx(TableCell,{children:jsx("span",{className:`text-xs font-medium ${o.side==="buy"?"text-primary":"text-danger"}`,children:o.side==="buy"?s("predict.trade.buy"):s("predict.trade.sell")})}),jsx(TableCell,{children:jsx("span",{className:`text-xs ${o.outcome==="yes"?"text-primary":"text-secondary"}`,children:o.outcome==="yes"?s("predict.trade.yes"):s("predict.trade.no")})}),jsx(TableCell,{children:jsx("span",{className:"text-xs capitalize",children:o.type})}),jsx(TableCell,{children:jsxs("span",{className:"text-xs",children:[o.price,"\xA2"]})}),jsx(TableCell,{children:jsx("span",{className:"text-xs",children:o.filled})}),jsx(TableCell,{children:jsx("span",{className:"text-xs capitalize",children:o.status})}),jsx(TableCell,{children:jsx("span",{className:"text-xs text-default-500",children:o.createdAt})}),jsx(TableCell,{className:"text-right",children:jsx(Button,{size:"sm",variant:"flat",color:"danger",isLoading:o.isCancelling,onPress:()=>n(o.id),children:s("predict.openOrders.cancel")})})]},o.key))})]})})]})}function $C({refetchInterval:e}={}){let{orders:t,isLoading:r,cancellingOrderId:n,cancelOrder:s}=sa({});return jsx(oa,{orders:t,isLoading:r,cancellingOrderId:n,onCancel:s})}function ia({ticker:e,pageSize:t=48}={}){let[r,n]=useState(1),[s,a]=useState([void 0]),o=s[r-1],i=useMemo(()=>({...e?{ticker:e}:{},limit:t,...o?{cursor:o}:{}}),[e,t,o]),{data:l,isLoading:c,isFetching:u}=Rn(i),p=l,d=p?.trades??[],y=!!p?.cursor,f=r>1,g=useCallback(b=>{b>=1&&b<=s.length&&n(b);},[s.length]),v=useCallback(()=>{y&&p?.cursor&&(a(b=>{let x=[...b];return x.length===r&&x.push(p.cursor),x}),n(b=>b+1));},[y,p?.cursor,r]),h=useCallback(()=>{f&&n(b=>b-1);},[f]);return {trades:d,isLoading:c,isFetching:u,page:r,pageSize:t,hasNextPage:y,hasPrevPage:f,goToPage:g,nextPage:v,prevPage:h}}function af(e){return new Date(e*1e3).toLocaleString("default",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function ca({trades:e,isLoading:t,isFetching:r,page:n,hasNextPage:s,hasPrevPage:a,onNextPage:o,onPrevPage:i}){let{t:l}=useTranslation(),c=useMemo(()=>e.map(u=>({key:u.tradeId,ticker:u.ticker,takerSide:u.takerSide,price:u.price,yesPrice:u.yesPrice,noPrice:u.noPrice,count:u.count,createdAt:af(u.createdTime)})),[e]);return t?jsxs("div",{className:"flex w-full flex-col rounded-xl border border-default-200 bg-content1",children:[jsx("div",{className:"border-b border-default-200 px-3 py-2 text-sm font-medium",children:l("predict.tradeHistory.title")}),jsx("div",{className:"flex flex-col gap-y-2 p-3",children:Array.from({length:3}).map((u,p)=>jsx("div",{className:"h-8 animate-pulse rounded bg-default-100"},p))})]}):jsxs("div",{className:"flex w-full flex-col rounded-xl border border-default-200 bg-content1",children:[jsx("div",{className:"border-b border-default-200 px-3 py-2 text-sm font-medium",children:l("predict.tradeHistory.title")}),e.length===0?jsx("div",{className:"flex items-center justify-center py-8 text-xs text-default-400",children:l("predict.tradeHistory.empty")}):jsxs(Fragment,{children:[jsx("div",{className:`w-full overflow-x-auto ${r?"opacity-60":""}`,children:jsxs(StyledTable,{radius:"none","aria-label":"Trade history",className:"min-w-[480px]",children:[jsxs(TableHeader,{children:[jsx(TableColumn,{textValue:"Side",width:60,children:l("predict.tradeHistory.side")}),jsx(TableColumn,{textValue:"Price",width:80,children:l("predict.tradeHistory.price")}),jsx(TableColumn,{textValue:"Yes",width:60,children:l("predict.trade.yes")}),jsx(TableColumn,{textValue:"No",width:60,children:l("predict.trade.no")}),jsx(TableColumn,{textValue:"Qty",width:60,children:l("predict.tradeHistory.qty")}),jsx(TableColumn,{textValue:"Time",width:120,children:l("predict.tradeHistory.time")})]}),jsx(TableBody,{children:c.map(u=>jsxs(TableRow,{children:[jsx(TableCell,{children:jsx("span",{className:`text-xs font-medium ${u.takerSide==="yes"?"text-primary":"text-secondary"}`,children:u.takerSide==="yes"?l("predict.trade.yes"):l("predict.trade.no")})}),jsx(TableCell,{children:jsxs("span",{className:"text-xs",children:[u.price,"\xA2"]})}),jsx(TableCell,{children:jsxs("span",{className:"text-xs text-primary",children:[u.yesPrice,"\xA2"]})}),jsx(TableCell,{children:jsxs("span",{className:"text-xs text-secondary",children:[u.noPrice,"\xA2"]})}),jsx(TableCell,{children:jsx("span",{className:"text-xs",children:u.count})}),jsx(TableCell,{children:jsx("span",{className:"text-xs text-default-500",children:u.createdAt})})]},u.key))})]})}),(a||s)&&jsxs("div",{className:"flex items-center justify-between border-t border-default-200 px-3 py-2",children:[jsx(Button,{size:"sm",variant:"flat",isDisabled:!a,onPress:i,startContent:jsx(ChevronLeftIcon,{className:"h-3 w-3"}),children:l("predict.pagination.prev")}),jsx("span",{className:"text-xs text-default-500",children:l("predict.pagination.page",{page:n})}),jsx(Button,{size:"sm",variant:"flat",isDisabled:!s,onPress:o,endContent:jsx(ChevronRightIcon,{className:"h-3 w-3"}),children:l("predict.pagination.next")})]})]})]})}function uE({ticker:e,pageSize:t}={}){let{trades:r,isLoading:n,isFetching:s,page:a,hasNextPage:o,hasPrevPage:i,nextPage:l,prevPage:c}=ia({ticker:e,pageSize:t});return jsx(ca,{trades:r,isLoading:n,isFetching:s,page:a,hasNextPage:o,hasPrevPage:i,onNextPage:l,onPrevPage:c})}function ua(e={}){let t=useMemo(()=>({totalValue:0,totalUnrealizedPnl:0,totalRealizedPnl:0,count:0}),[]);return {positions:[],isLoading:false,isFetching:false,summary:t}}var Zt=e=>formatAmountUSDCompact(e/100);function ln({value:e}){if(e===0)return jsx("span",{className:"text-default-500",children:Zt(0)});let t=e>0;return jsxs("span",{className:t?"text-success":"text-danger",children:[t?"+":"",Zt(e)]})}function da({positions:e,isLoading:t,summary:r,onSell:n}){let{t:s}=useTranslation(),a=useMemo(()=>e.map(o=>({key:`${o.marketId}-${o.outcome}`,marketTitle:o.marketTitle,outcome:o.outcome,quantity:o.quantity,avgCost:o.avgCostBasis,currentPrice:o.currentPrice,value:o.currentPrice*o.quantity,unrealizedPnl:o.unrealizedPnl,position:o})),[e]);return t?jsxs("div",{className:"flex w-full flex-col rounded-xl border border-default-200 bg-content1",children:[jsx("div",{className:"border-b border-default-200 px-3 py-2 text-sm font-medium",children:s("predict.positions.title")}),jsx("div",{className:"flex flex-col gap-y-2 p-3",children:Array.from({length:3}).map((o,i)=>jsx("div",{className:"h-8 animate-pulse rounded bg-default-100"},i))})]}):jsxs("div",{className:"flex w-full flex-col rounded-xl border border-default-200 bg-content1",children:[jsx("div",{className:"flex items-center justify-between border-b border-default-200 px-3 py-2",children:jsxs("span",{className:"text-sm font-medium",children:[s("predict.positions.title"),e.length>0&&jsxs("span",{className:"ml-1 text-default-400",children:["(",e.length,")"]})]})}),e.length===0?jsx("div",{className:"flex items-center justify-center py-8 text-xs text-default-400",children:s("predict.positions.empty")}):jsxs(Fragment,{children:[jsx("div",{className:"w-full overflow-x-auto",children:jsxs(StyledTable,{radius:"none","aria-label":"Positions",className:"min-w-[640px]",children:[jsxs(TableHeader,{children:[jsx(TableColumn,{textValue:"Market",width:200,children:s("predict.positions.market")}),jsx(TableColumn,{textValue:"Outcome",width:60,children:s("predict.positions.outcome")}),jsx(TableColumn,{textValue:"Qty",width:50,children:s("predict.positions.qty")}),jsx(TableColumn,{textValue:"Avg Cost",width:70,children:s("predict.positions.avgCost")}),jsx(TableColumn,{textValue:"Price",width:60,children:s("predict.positions.currentPrice")}),jsx(TableColumn,{textValue:"Value",width:80,children:s("predict.positions.value")}),jsx(TableColumn,{textValue:"PnL",width:80,children:s("predict.positions.pnl")})]}),jsx(TableBody,{children:a.map(o=>jsxs(TableRow,{className:n?"cursor-pointer hover:bg-default-50":"",onClick:()=>n?.(o.position),children:[jsx(TableCell,{children:jsx("span",{className:"text-xs font-medium line-clamp-1",children:o.marketTitle})}),jsx(TableCell,{children:jsx("span",{className:`text-xs font-medium ${o.outcome==="yes"?"text-primary":"text-secondary"}`,children:o.outcome==="yes"?s("predict.trade.yes"):s("predict.trade.no")})}),jsx(TableCell,{children:jsx("span",{className:"text-xs",children:o.quantity})}),jsx(TableCell,{children:jsxs("span",{className:"text-xs",children:[o.avgCost,"\xA2"]})}),jsx(TableCell,{children:jsxs("span",{className:"text-xs",children:[o.currentPrice,"\xA2"]})}),jsx(TableCell,{children:jsx("span",{className:"text-xs",children:Zt(o.value)})}),jsx(TableCell,{children:jsx("span",{className:"text-xs",children:jsx(ln,{value:o.unrealizedPnl})})})]},o.key))})]})}),jsxs("div",{className:"flex items-center justify-between border-t border-default-200 px-3 py-2 text-xs",children:[jsx("div",{className:"flex items-center gap-x-4",children:jsxs("span",{className:"text-default-500",children:[s("predict.positions.totalValue"),":"," ",jsx("span",{className:"font-medium text-foreground",children:Zt(r.totalValue)})]})}),jsxs("div",{className:"flex items-center gap-x-4",children:[jsxs("span",{className:"text-default-500",children:[s("predict.positions.unrealizedPnl"),":"," ",jsx(ln,{value:r.totalUnrealizedPnl})]}),jsxs("span",{className:"text-default-500",children:[s("predict.positions.realizedPnl"),":"," ",jsx(ln,{value:r.totalRealizedPnl})]})]})]})]})]})}function wE({refetchInterval:e,onSell:t}={}){let{positions:r,isLoading:n,summary:s}=ua({});return jsx(da,{positions:r,isLoading:n,summary:s,onSell:t})}var Pf=10,Sf=atomWithStorage("liberfi:predict_search_histories",[],void 0,{getOnInit:true});function Jt(){let[e,t]=useAtom(Sf),r=useCallback(s=>{let a=s.trim();a&&t(o=>{let i=o.filter(l=>l!==a);return [a,...i].slice(0,Pf)});},[t]),n=useCallback(()=>{t([]);},[t]);return {histories:e,addHistory:r,clearHistories:n}}function ya({histories:e,onSelect:t,onClear:r,className:n}){let{t:s}=useTranslation();return e.length===0?null:jsxs("div",{className:cn("px-4 pb-4",n),children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("span",{className:"text-sm font-medium",children:s("predict.search.history")}),jsx(Button,{isIconOnly:true,size:"sm",className:"bg-transparent min-w-6 w-6 h-6 text-neutral",onPress:r,children:jsx(TrashIcon,{width:20,height:20})})]}),jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:e.map(a=>jsx(Chip,{size:"sm",variant:"bordered",className:cn("text-neutral","border-border border-1","cursor-pointer","hover:opacity-hover"),onClick:()=>t?.(a),children:a},a))})]})}function ga({onSelect:e,className:t}){let{histories:r,clearHistories:n}=Jt();return jsx(ya,{className:cn(t),histories:r,onSelect:e,onClear:n})}function va({value:e,onValueChange:t,onClear:r,onEscape:n,className:s}){let{t:a}=useTranslation();return jsx("div",{className:s,children:jsx(StyledInput,{autoFocus:true,variant:"flat",radius:"full",value:e,onValueChange:t,placeholder:a("predict.search.placeholder"),startContent:jsx(SearchIcon,{width:20,height:20,className:"text-neutral"}),endContent:e?jsx(Button,{isIconOnly:true,className:"bg-transparent min-w-6 w-6 h-6 text-neutral",onPress:r,children:jsx(XCloseIcon,{width:20,height:20})}):jsx(Kbd,{className:"min-w-8 justify-center text-xs text-neutral bg-transparent border border-border rounded-full cursor-pointer select-none",onMouseDown:o=>{o.preventDefault(),n?.();},children:"Esc"})})})}function ba({event:e,href:t,LinkComponent:r,onSelect:n,onHover:s,className:a}){let o=e.tags?.[0];return jsxs(Linkable,{href:t,LinkComponent:r,className:cn("w-full h-full px-3 flex items-center gap-3","hover:cursor-pointer hover:bg-content2 rounded-lg","transition-colors duration-150",a),onClick:i=>{t&&n&&i.preventDefault(),n?.(e);},onMouseEnter:()=>s?.(e),children:[jsx(Avatar,{src:e.image_url||void 0,name:e.title||"Event",radius:"full",className:"h-10 w-10 flex-shrink-0"}),jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2.5",children:[jsx("span",{className:"min-w-0 text-sm font-medium truncate",children:e.title}),o&&jsx("span",{className:cn("flex-shrink-0 inline-flex items-center","rounded-full px-2.5 py-1.5","text-[11px] font-semibold leading-none uppercase","bg-primary/15 text-primary"),children:o.label})]})]})}function ka({keyword:e="",limit:t,source:r}){let{data:n,isLoading:s,isFetchingNextPage:a,hasNextPage:o,fetchNextPage:i}=Sn({keyword:e,limit:t,source:r},{enabled:true});return {events:useMemo(()=>n?.pages.flatMap(c=>c.items).filter(c=>c!=null)??[],[n]),isLoading:s,isFetchingNextPage:a,hasNextPage:o??false,fetchNextPage:i}}var Kf=56;function Ea({onSelect:e,getEventHref:t,LinkComponent:r,onHover:n,className:s,...a}){let{events:o,isLoading:i,isFetchingNextPage:l,hasNextPage:c,fetchNextPage:u}=ka(a),p=useRef(null),{height:d}=useResizeObserver({ref:p}),y=useCallback(h=>h<o.length,[o]),f=useCallback(async()=>{c&&!l&&await u();},[c,l,u]),g=useMemo(()=>c?o.length+1:o.length,[o,c]),v=useInfiniteLoader({isRowLoaded:y,loadMoreRows:f,rowCount:g,threshold:5});return i?jsx(zf,{className:s}):o.length===0?jsx(Gf,{className:s}):jsx("div",{className:cn("w-full h-full flex flex-col",s),children:jsx("div",{className:"flex-auto min-h-0",ref:p,children:jsx(List,{style:{height:d},onRowsRendered:v,rowComponent:$f,rowCount:g,rowHeight:Kf,rowProps:{events:o,onSelect:e,getEventHref:t,LinkComponent:r,onHover:n},overscanCount:5})})})}function $f({index:e,style:t,events:r,onSelect:n,getEventHref:s,LinkComponent:a,onHover:o}){let i=r[e];return i?jsx("div",{style:t,children:jsx(ba,{event:i,href:s?.(i),LinkComponent:a,onSelect:n,onHover:o})}):jsx("div",{style:t,className:"flex items-center justify-center",children:jsx(Spinner,{size:"sm"})})}function zf({className:e}){let{t}=useTranslation();return jsxs("div",{className:cn("flex items-center justify-center gap-2 py-16",e),children:[jsx(Spinner,{size:"sm"}),jsx("span",{className:"text-sm text-neutral",children:t("predict.search.loading")})]})}function Gf({className:e}){let{t}=useTranslation();return jsxs("div",{className:cn("flex flex-col items-center justify-center py-16",e),children:[jsx(EmptyIcon,{width:28,height:28,className:"text-neutral"}),jsx("p",{className:"mt-2 text-sm text-neutral",children:t("predict.search.noResults")})]})}function Ra({onKeywordChange:e}){let[t,r]=useState(""),[n,s]=useState(""),{addHistory:a}=Jt(),o=useCallbackRef(e),i=useCallbackRef(a),l=useMemo(()=>debounce(d=>{s(d),o(d),d&&i(d);},500),[o,i]),c=useCallback(d=>{r(d),l(d);},[l]),u=useCallback(d=>{l.cancel(),r(d),s(d),o(d),d&&i(d);},[l,o,i]),p=useCallback(()=>u(""),[u]);return {text:t,keyword:n,setText:c,setKeyword:u,clearKeyword:p}}function Na({onKeywordChange:e,onSelectEvent:t,getEventHref:r,LinkComponent:n,onHover:s,onEscape:a,source:o}){let{text:i,keyword:l,setText:c,setKeyword:u,clearKeyword:p}=Ra({onKeywordChange:e});return jsxs("div",{className:"w-full h-full flex flex-col gap-3",children:[jsx(va,{value:i,onValueChange:c,onClear:p,onEscape:a}),!l&&jsx(ga,{onSelect:u}),jsx(Ea,{className:"flex-auto min-h-0",keyword:l,onSelect:t,getEventHref:r,LinkComponent:n,onHover:s,source:o})]})}var mn="predict-search";function _2({id:e=mn}){return jsx(AsyncModal,{id:e,children:t=>jsx(iy,{...t})})}function iy({params:e,isOpen:t,onOpenChange:r,onResult:n}){let{t:s}=useTranslation(),{isMobile:a}=useScreen(),o=useCallback(l=>{n(l);},[n]),i=useCallback(()=>{r(false);},[r]);return jsx(StyledModal,{isOpen:t,onOpenChange:r,size:a?"full":"lg",hideCloseButton:true,backdrop:"blur",radius:"lg",children:jsxs(ModalContent,{className:"w-full h-full",children:[jsxs(ModalHeader,{className:"sm:hidden flex items-center justify-between pt-4 pb-2",children:[jsx("span",{className:"text-base font-semibold",children:s("predict.search.title")}),jsx(Button,{isIconOnly:true,onPress:()=>r(false),size:"sm",className:"bg-transparent min-w-6 w-6 h-6",children:jsx(XCloseIcon,{width:20,height:20})})]}),jsx(ModalBody,{className:"p-4",children:jsx(Na,{getEventHref:e?.getEventHref,LinkComponent:e?.LinkComponent,onHover:e?.onHover,source:e?.source,onSelectEvent:o,onEscape:i})})]})})}function K2({onSelectEvent:e,modalParams:t,className:r}){let{t:n}=useTranslation(),{isDesktop:s,isMobile:a}=useScreen(),{onOpen:o,onClose:i}=useAsyncModal(mn),l=useCallbackRef(e),c=useCallbackRef(async()=>{let p=await o({params:t});p&&l(p);}),u=useCallbackRef(()=>{i();});return useEffect(()=>{let p=d=>{let y=document.activeElement,f=!!y&&(y.tagName==="INPUT"||y.tagName==="TEXTAREA"||y.getAttribute("contenteditable")==="true");d.key==="/"&&!f&&(d.preventDefault(),c()),d.key==="Escape"&&(d.preventDefault(),u());};return window.addEventListener("keydown",p),()=>{window.removeEventListener("keydown",p);}},[c,u]),jsx(Button,{size:"sm",radius:"full",isIconOnly:!s,onPress:c,variant:a?"flat":"bordered",startContent:s?jsx(SearchIcon,{className:"text-neutral"}):void 0,endContent:s?jsx(Kbd,{className:"ml-auto min-w-6 justify-center text-xs bg-transparent border border-border rounded-full",children:"/"}):void 0,className:cn(s&&"min-w-56 justify-start pl-3 pr-1.5 text-neutral",r),children:s?n("predict.search.placeholder"):jsx(SearchIcon,{className:"text-neutral"})})}function xM({client:e,wsClient:t=null,children:r}){let n=useMemo(()=>({client:e,wsClient:t}),[e,t]);return jsx($e.Provider,{value:n,children:r})}var xy=3e4;function CM({walletAddress:e,pollingInterval:t=xy,enabled:r=true,children:n}){let{data:s,isLoading:a,error:o,refetch:i}=_n({walletAddress:e},{enabled:r&&!!e,refetchInterval:t}),l=useMemo(()=>({positions:s?.positions??[],usdcBalance:s?.usdcBalance??0,isLoading:a,error:o??null,refetch:i}),[s?.positions,s?.usdcBalance,a,o,i]);return jsx(Me.Provider,{value:l,children:n})}function RM({client:e,children:t}){let r=useMemo(()=>({client:e}),[e]);return jsx(Ct.Provider,{value:r,children:t})}function Va(e,t){let r=new URLSearchParams;t&&r.set("provider",t);for(let[s,a]of Object.entries(e))a!=null&&(typeof a=="object"?r.set(s,JSON.stringify(a)):r.set(s,String(a)));let n=r.toString();return n?`?${n}`:""}function Ba(e){return e}var vt=class{constructor(t,r){this.endpoint=t;this.provider=r;}buildUrl(t,r){let n=Va(r??{},this.provider);return `${this.endpoint}${t}${n}`}async fetch(t,r){let n=this.buildUrl(t,r);return await httpGet(n)}async postRequest(t,r,n){let s=this.buildUrl(t,n);return await httpPost(s,r)}};function tr(e,t){if(!e)return [];let r=Object.entries(e).map(([n,s])=>({price:parseFloat(n),quantity:s}));return r.sort((n,s)=>t==="desc"?s.price-n.price:n.price-s.price),r}function _a(e){return {yesBids:tr(e.yes_bids,"desc"),yesAsks:tr(e.yes_asks,"asc"),noBids:tr(e.no_bids,"desc"),noAsks:tr(e.no_asks,"asc"),sequence:e.sequence}}var rr=class extends vt{constructor(t){super(t,"dflow");}async getEvents(t){return await this.fetch("/v2/event",t??{})}async getEventById(t,r){return await this.fetch(`/v2/event/${t}`,{withNestedMarkets:r})}async getEventCandlesticks(t,r){return await this.fetch(`/v2/event/${t}/candlesticks`,r)}async getEventForecastPercentileHistory(t){let{seriesTicker:r,eventId:n,...s}=t;return await this.fetch(`/v2/event/${r}/${n}/forecast_percentile_history`,s)}async getEventForecastPercentileHistoryByMint(t){let{mintAddress:r,...n}=t;return await this.fetch(`/v2/event/by-mint/${r}/forecast_percentile_history`,n)}async getMarkets(t){return await this.fetch("/v2/market",t??{})}async getMarketById(t){return await this.fetch(`/v2/market/${t}`)}async getMarketByMint(t){return await this.fetch(`/v2/market/by-mint/${t}`)}async getMarketsBatch(t){return await this.postRequest("/v2/market/batch",t)}async getMarketCandlesticks(t,r){return await this.fetch(`/v2/market/${t}/candlesticks`,r)}async getMarketCandlesticksByMint(t,r){return await this.fetch(`/v2/market/by-mint/${t}/candlesticks`,r)}async getOrderbook(t){let r=await this.fetch(`/v2/orderbook/${t}`);return _a(r)}async getOrderbookByMint(t){let r=await this.fetch(`/v2/orderbook/by-mint/${t}`);return _a(r)}async getTrades(t){return await this.fetch("/v2/trades",t??{})}async getTradesByMint(t){let{mintAddress:r,...n}=t;return await this.fetch(`/v2/trades/by-mint/${r}`,n)}async getOnchainTradesByWallet(t){let{walletAddress:r,...n}=t;return await this.fetch(`/v2/trades/onchain/by-wallet/${r}`,n)}async getOnchainTradesByEvent(t){let{eventTicker:r,...n}=t;return await this.fetch(`/v2/trades/onchain/by-event/${r}`,n)}async getOnchainTradesByMarket(t){let{marketTicker:r,...n}=t;return await this.fetch(`/v2/trades/onchain/by-market/${r}`,n)}async getLiveData(t){return await this.fetch("/v2/live",{milestoneIds:t.milestoneIds.join(",")})}async getLiveDataByEvent(t){let{eventTicker:r,...n}=t;return await this.fetch(`/v2/live/event/${r}`,n)}async getLiveDataByMint(t){let{mintAddress:r,...n}=t;return await this.fetch(`/v2/live/by-mint/${r}`,n)}async getSeries(t){return await this.fetch("/v2/series",t??{})}async getSeriesByTicker(t){return await this.fetch(`/v2/series/${t}`)}async getTagsByCategories(){return await this.fetch("/v2/tags/by_categories")}async getFiltersBySports(){return await this.fetch("/v2/sports/filters")}async search(t){return await this.fetch("/v2/search",t)}async getPositionsByWallet(t){let{walletAddress:r}=t;return await this.fetch(`/v2/positions/by-wallet/${r}`)}async getOutcomeMints(t){return await this.fetch("/v2/outcome_mints",t??{})}async filterOutcomeMints(t){return await this.postRequest("/v2/filter_outcome_mints",t)}async getQuote(t){return await this.fetch("/v2/swap/quote",t)}async createSwap(t){return await this.postRequest("/v2/swap",t)}async createSwapInstructions(t){return await this.postRequest("/v2/swap/instructions",t)}async getOrder(t){return await this.fetch("/v2/order",t)}async getOrderStatus(t){try{return await this.fetch("/v2/order/status",t)}catch(r){if(r instanceof Error&&/\b404\b/.test(r.message))return {status:"pending",inAmount:"0",outAmount:"0"};throw r}}async getIntentQuote(t){return await this.fetch("/v2/intent/quote",t)}async submitIntentSwap(t){return await this.postRequest("/v2/intent/swap",t)}async initPredictionMarket(t){return await this.fetch("/v2/prediction-market/init",t)}async getTokens(){return await this.fetch("/v2/tokens")}async getTokensWithDecimals(){return await this.fetch("/v2/tokens/decimals")}async getVenues(){return await this.fetch("/v2/venues")}};function gn(e){let t=new URLSearchParams;for(let[n,s]of Object.entries(e))s!=null&&t.set(n,String(s));let r=t.toString();return r?`?${r}`:""}var xt=class{constructor(t){this.endpoint=t;}async listEvents(t){let r=gn(t??{}),n=`${this.endpoint}/api/v1/events${r}`;return await httpGet(n)}async getEvent(t,r){let n=r?gn({source:r}):"",s=`${this.endpoint}/api/v1/events/${encodeURIComponent(t)}${n}`;return await httpGet(s)}async getMarket(t,r){let n=r?gn({source:r}):"",s=`${this.endpoint}/api/v1/markets/${encodeURIComponent(t)}${n}`;return await httpGet(s)}};function Qa(e){return new xt(e)}export{vt as BasePredictClient,wr as CATEGORIES_V2,Ke as CHART_RANGE_DURATION,He as CHART_RANGE_PERIOD,Mt as CHART_RANGE_SAMPLE_INTERVAL,Et as CandlestickPeriod,It as CategoriesSkeleton,Ot as CategoriesUI,ss as CategoriesWidget,xs as CategoriesWidgetV2,S as ChartRange,le as DEFAULT_CHART_RANGE,Tr as DEFAULT_FILTER_STATE,de as DEFAULT_PAGE_SIZE,Fy as DEFAULT_PRICE_HISTORY_INTERVAL,rr as DflowPredictClient,st as DflowPredictWsClient,fS as EventDetailPage,jS as EventDetailPageV2,ge as EventDetailSkeleton,Io as EventDetailUI,Ho as EventDetailV2UI,Gr as EventDetailWidget,en as EventDetailWidgetV2,vc as EventItemSkeleton,cs as EventItemUI,As as EventItemV2UI,$t as EventMarketDetailWidget,nC as EventPriceChartV2,bs as EventsFilterV2UI,Kb as EventsPage,gb as EventsPageSkeleton,D0 as EventsPageV2,ot as EventsSkeleton,Es as EventsToolbarV2UI,ps as EventsUI,Hs as EventsV2UI,fs as EventsWidget,$s as EventsWidgetV2,J as MAX_PRICE_HISTORY_MARKETS,Uy as ORDER_MAX_PRICE,Dy as ORDER_MIN_PRICE,ir as ORDER_MIN_QUANTITY,Ay as ORDER_PRICE_STEP,oa as OpenOrdersUI,$C as OpenOrdersWidget,ra as OrderBookUI,NC as OrderBookWidget,mn as PREDICT_SEARCH_MODAL_ID,Wy as PRICE_HISTORY_SAMPLE_INTERVAL,da as PositionsUI,wE as PositionsWidget,rr as PredictClient,xt as PredictClientV2,$e as PredictContext,xM as PredictProvider,_2 as PredictSearchModal,Ct as PredictV2Context,RM as PredictV2Provider,st as PredictWsClient,qe as PriceHistoryInterval,Cs as SORT_PRESETS,K2 as SearchEventsButton,ya as SearchHistoryUI,ga as SearchHistoryWidget,va as SearchInputUI,ba as SearchResultItemUI,Ea as SearchResultListWidget,Na as SearchWidget,Ft as TradeFormSkeleton,eo as TradeFormUI,je as TradeFormWidget,ca as TradeHistoryUI,uE as TradeHistoryWidget,Me as UserPredictContext,CM as UserPredictProvider,Va as buildQuery,Rr as countActiveFilters,Rt as createDflowPredictWsClient,Qa as createPredictClientV2,Rt as createPredictWsClient,Vl as createSwap,Bl as createSwapInstructions,ki as eventByIdQueryKey,Yi as eventCandlesticksQueryKey,dr as eventV2QueryKey,hi as eventsInfiniteQueryKey,vi as eventsQueryKey,cr as eventsV2InfiniteQueryKey,ei as eventsV2QueryKey,Pi as fetchEventById,ji as fetchEventCandlesticks,pr as fetchEventV2,mr as fetchEvents,ti as fetchEventsV2,ur as fetchEventsV2Page,gl as fetchFiltersBySports,el as fetchForecastPercentileHistory,rl as fetchForecastPercentileHistoryByMint,ql as fetchIntentQuote,sl as fetchLiveData,al as fetchLiveDataByEvent,ll as fetchLiveDataByMint,Ti as fetchMarketById,Oi as fetchMarketByMint,nt as fetchMarketCandlesticks,Zi as fetchMarketCandlesticksByMint,ci as fetchMarketV2,Ei as fetchMarkets,Vi as fetchMarketsBatch,gr as fetchOnchainTradesByEvent,vr as fetchOnchainTradesByMarket,yr as fetchOnchainTradesByWallet,Ql as fetchOrder,_i as fetchOrderBook,Ai as fetchOrderBookByMint,Dl as fetchOrderStatus,Rl as fetchOutcomeMints,Pl as fetchPositionsByWallet,Ll as fetchQuote,hl as fetchSearch,ul as fetchSeries,pl as fetchSeriesByTicker,fl as fetchTagsByCategories,Gl as fetchTokens,jl as fetchTokensWithDecimals,Ui as fetchTrades,Wi as fetchTradesByMint,Jl as fetchVenues,Nl as filterOutcomeMints,yl as filtersBySportsQueryKey,tl as forecastPercentileHistoryByMintQueryKey,Ji as forecastPercentileHistoryQueryKey,$l as initPredictionMarket,Wl as intentQuoteQueryKey,ol as liveDataByEventQueryKey,il as liveDataByMintQueryKey,nl as liveDataQueryKey,wi as marketByIdQueryKey,Ni as marketByMintQueryKey,Xi as marketCandlesticksByMintQueryKey,rt as marketCandlesticksQueryKey,li as marketV2QueryKey,Li as marketsBatchQueryKey,Ci as marketsQueryKey,zi as onchainTradesByEventInfiniteQueryKey,Hi as onchainTradesByEventQueryKey,Gi as onchainTradesByMarketInfiniteQueryKey,Ki as onchainTradesByMarketQueryKey,$i as onchainTradesByWalletInfiniteQueryKey,qi as onchainTradesByWalletQueryKey,Qi as orderBookByMintQueryKey,Bi as orderBookQueryKey,_l as orderQueryKey,Al as orderStatusQueryKey,Tl as outcomeMintsQueryKey,kl as positionsByWalletQueryKey,Il as quoteQueryKey,lr as resolveEventsV2Params,kn as resolveTagSlug,xl as searchQueryKey,dl as seriesByTickerQueryKey,cl as seriesQueryKey,Hl as submitIntentSwap,ml as tagsByCategoriesQueryKey,Ba as toRecord,zl as tokensQueryKey,Yl as tokensWithDecimalsQueryKey,Fi as tradesByMintQueryKey,Di as tradesQueryKey,Xv as useCategoriesQuery,Ex as useCreateSwapInstructionsMutation,Cx as useCreateSwapMutation,Tt as useEventByIdQuery,Nv as useEventCandlesticksQuery,to as useEventDetail,Qo as useEventDetailV2,wt as useEventV2Query,os as useEvents,Zn as useEventsCategories,Mn as useEventsInfiniteQuery,Qg as useEventsQuery,Ts as useEventsV2,Pn as useEventsV2InfiniteQuery,_y as useEventsV2Query,gx as useFilterOutcomeMintsMutation,jv as useFiltersBySportsQuery,Qv as useForecastPercentileHistoryByMintQuery,_v as useForecastPercentileHistoryQuery,Qx as useInitPredictionMarketMutation,Ix as useIntentQuoteQuery,Wv as useLiveDataByEventQuery,qv as useLiveDataByMintQuery,Fv as useLiveDataQuery,Zg as useMarketByIdQuery,rv as useMarketByMintQuery,Ov as useMarketCandlesticksByMintQuery,kr as useMarketCandlesticksQuery,Cn as useMarketHistoryV2,Qn as useMarketPositions,lg as useMarketV2Query,av as useMarketsBatchQuery,Gg as useMarketsQuery,Ev as useOnchainTradesByEventInfiniteQuery,xv as useOnchainTradesByEventQuery,Mv as useOnchainTradesByMarketInfiniteQuery,hv as useOnchainTradesByMarketQuery,Cv as useOnchainTradesByWalletInfiniteQuery,Nn as useOnchainTradesByWalletQuery,sa as useOpenOrders,Jo as useOrderBook,uv as useOrderBookByMintQuery,ze as useOrderBookQuery,Un as useOrderQuery,Fn as useOrderStatusQuery,dh as useOrderbookSubscription,yx as useOutcomeMintsQuery,ua as usePositions,_n as usePositionsByWalletQuery,k as usePredictClient,En as usePredictContext,Jt as usePredictSearchHistory,fe as usePredictV2Client,bn as usePredictV2Context,Iv as usePriceHistoryQuery,oh as usePricesSubscription,bx as useQuoteQuery,Sn as useSearchEventsInfiniteQuery,tx as useSearchQuery,ka as useSearchResultListScript,Ra as useSearchScript,Vn as useSeriesByTickerQuery,Ln as useSeriesQuery,Lx as useSubmitIntentSwapMutation,Sr as useTagsByCategoriesQuery,Fx as useTokensQuery,Wx as useTokensWithDecimalsQuery,js as useTradeForm,ia as useTradeHistory,fv as useTradesByMintQuery,Rn as useTradesQuery,lh as useTradesSubscription,lx as useUserPredictContext,$x as useVenuesQuery,rh as useWsClient,Zx as useWsConnection,Zl as venuesQueryKey,ja as version};//# sourceMappingURL=index.mjs.map
19
+ `;function As({event:e,href:t,LinkComponent:r,onSelect:n,onSelectOutcome:s,onHover:a}){let[o,i]=useState(null),l=e.markets??[],u=useMemo(()=>l.length>2?[...l].sort((m,P)=>(P.outcomes?.[0]?.price??0)-(m.outcomes?.[0]?.price??0)):l,[l]).filter(m=>m.status==="open"),p=u.length===1,d=u.slice(0,Rs),y=u.length-Rs,f=useMemo(()=>`$${Math.round(e.volume??0).toLocaleString("en-US")}`,[e.volume]),g=o?u.find(m=>m.slug===o)??null:null,v=!!g||p,h=()=>{v||n?.(e);},b=m=>{m.stopPropagation(),g&&(m.preventDefault(),i(null));},x=m=>{m.stopPropagation(),t||(m.preventDefault(),n?.(e));};return jsxs("div",{className:cn("group flex h-full w-full flex-col rounded-xl","min-h-52 border border-border/90 bg-background p-3","lg:min-h-72 lg:max-w-md lg:p-4","gap-y-1.5 lg:gap-y-4","transition duration-300","hover:border-primary/40 hover:shadow-card-glow","focus-within:border-primary/40 focus-within:shadow-card-glow",!v&&"cursor-pointer"),onMouseEnter:()=>a?.(e),onClick:h,children:[jsx("style",{children:Mu}),jsx(wu,{event:e,href:t,LinkComponent:r,onClick:b,isExpanded:v}),jsx("div",{className:"flex flex-1 flex-col",children:p?jsx(Bu,{market:u[0],event:e,formattedVolume:f,href:t,LinkComponent:r,onSelect:n,onSelectOutcome:s}):g?jsx(_u,{market:g,event:e,onCollapse:()=>i(null),onSelectOutcome:s}):jsx(Lu,{displayedMarkets:d,moreCount:y,formattedVolume:f,source:e.source,href:t,LinkComponent:r,onMarketClick:m=>i(m.slug),onShowMore:x})})]})}function wu({event:e,href:t,LinkComponent:r,onClick:n,isExpanded:s}){let a=e.start_at?Eu(e.start_at):null;return jsxs(Linkable,{href:t,LinkComponent:r,as:"button",className:"group/header flex items-center gap-x-2 lg:gap-x-4 w-full text-left cursor-pointer",onClick:n,children:[jsx(Avatar,{src:e.image_url||void 0,name:e.title||"Event",radius:"lg",className:"h-8 w-8 flex-shrink-0 transition-transform duration-300 group-hover/header:scale-110 lg:h-12 lg:w-12",classNames:{base:"bg-transparent"}}),jsxs("div",{className:"flex min-w-0 flex-1 flex-col justify-center gap-y-0.5",children:[jsx("p",{className:cn("min-w-0 text-sm font-semibold leading-snug text-slate-200 line-clamp-2 lg:text-base",s&&"group-hover/header:text-neutral-400"),children:e.title}),a&&jsxs("span",{className:"text-[10px] leading-4 text-neutral-500",children:["Live in ",a]})]}),jsx(Ru,{event:e})]})}function Tu(e){let t=[];if(e.status==="closed")return t.push({kind:"closed"}),t.slice(0,2);let r=e.tags?.some(s=>s.label?.toLowerCase()==="crypto"),n=e.tags?.some(s=>s.label?.toLowerCase()==="live");if(r&&e.end_at){let s=new Date(e.end_at).getTime()-Date.now(),a=300*1e3,o=900*1e3;if(s>0&&s<=o){let i=s<=a?"#ef4444":"#f59e0b";t.push({kind:"crypto-short",label:s<=a?"5m":"15m",color:i});}}return n&&t.push({kind:"live"}),t.slice(0,2)}function Ru({event:e}){let t=useMemo(()=>Tu(e),[e]);return t.length===0?null:jsx("div",{className:"flex flex-shrink-0 flex-col items-end gap-1",children:t.map((r,n)=>{switch(r.kind){case "live":return jsx(Nu,{},n);case "crypto-short":return jsx(Ou,{label:r.label,color:r.color},n);case "closed":return jsx(Iu,{},n)}})})}function Nu(){let{t:e}=useTranslation();return jsxs("span",{className:"badge-shine relative inline-flex items-center gap-1 overflow-hidden rounded-md bg-[rgb(240,68,56)]/10 px-1.5 py-0.5 text-xs font-semibold text-[rgb(240,68,56)]",children:[jsx("span",{className:"h-2 w-2 animate-pulse rounded-full bg-current"}),e("predict.event.status.live")]})}function Ou({label:e,color:t}){return jsxs("span",{className:"badge-shine relative inline-flex items-center gap-1 overflow-hidden rounded-md px-1.5 py-0.5 text-xs font-semibold",style:{backgroundColor:`${t}26`,color:t},children:[jsx(TimerIcon,{className:"size-3 shrink-0"}),e]})}function Iu(){let{t:e}=useTranslation();return jsx("span",{className:"inline-flex items-center rounded-md bg-neutral-800/80 px-1.5 py-0.5 text-xs font-semibold text-neutral-400",children:e("predict.event.status.closed")})}function Lu({displayedMarkets:e,moreCount:t,formattedVolume:r,source:n,href:s,LinkComponent:a,onMarketClick:o,onShowMore:i}){let{t:l}=useTranslation();return jsxs(Fragment,{children:[e.length>0&&jsx("div",{className:"flex w-full flex-1 flex-col gap-y-0.5 lg:gap-y-2",children:e.map(c=>{let u=_s(c);return jsxs("button",{type:"button",className:"flex h-9 w-full items-center justify-between gap-x-2 transition-opacity hover:cursor-pointer hover:opacity-80",onClick:p=>{p.stopPropagation(),o(c);},children:[jsx("span",{className:"min-w-0 flex-1 text-left text-xs text-slate-200 line-clamp-1 lg:text-sm",children:c.outcomes?.[0]?.label??c.question}),jsxs("div",{className:"flex items-center gap-x-2",children:[jsx("span",{className:"text-sm font-semibold text-slate-200 lg:text-lg",children:Qs(u)}),jsx(Vu,{})]})]},c.slug)})}),jsxs("div",{className:"mt-auto flex items-center justify-between pt-3",children:[t>0?jsxs(Linkable,{href:s,LinkComponent:a,as:"button",className:"flex items-center gap-1 text-[10px] font-normal text-neutral-500 transition-colors hover:text-slate-200 cursor-pointer lg:text-xs",onClick:i,children:[l("predict.event.showMore"),jsx(Us,{className:"h-3 w-3"})]}):jsx("div",{}),jsxs("span",{className:"inline-flex items-center gap-x-1.5 text-[10px] font-normal text-neutral-500 lg:text-xs",children:[r," ",l("predict.event.volume"),jsx(Fs,{source:n})]})]})]})}function Ls({bgColor:e,textColor:t,shadowColor:r,onClick:n,children:s}){return jsx("button",{type:"button",className:"flex h-12 flex-1 w-full items-center justify-center gap-x-1 overflow-hidden rounded-lg p-3 text-base font-normal hover:cursor-pointer will-change-transform [-webkit-tap-highlight-color:transparent]",style:{backgroundColor:e,color:t,"--shadow-color":r,"--shadow-offset":"4px",boxShadow:"inset 0 -1px 0 rgba(255,255,255,0.08), 0 var(--shadow-offset, 4px) 0 var(--shadow-color, rgba(0,0,0,0.22))",transition:"transform .12s, box-shadow .12s, opacity .14s"},onMouseEnter:i=>{let l=i.currentTarget;l.style.setProperty("--shadow-offset","2px"),l.style.transform="translateY(2px)";},onMouseLeave:i=>{let l=i.currentTarget;l.style.setProperty("--shadow-offset","4px"),l.style.transform="translateY(0px)";},onClick:n,children:s})}function Ds({market:e,event:t,onSelectOutcome:r,dynamicColors:n=false,labelFormat:s="action"}){let{t:a}=useTranslation(),[o,i]=n?Su(e):[Nr,Bs],l=s==="label"?`${e.outcomes?.[0]?.label??"Yes"} ${Os(e)}\xA2`:a("predict.market.action.yes",{price:Os(e)}),c=s==="label"?`${e.outcomes?.[1]?.label??"No"} ${Is(e)}\xA2`:a("predict.market.action.no",{price:Is(e)});return jsxs("div",{className:"flex gap-2",children:[jsx(Ls,{bgColor:o.bg,textColor:o.text,shadowColor:o.shadow,onClick:u=>{u.stopPropagation(),r?.(t,e,"yes");},children:l}),jsx(Ls,{bgColor:i.bg,textColor:i.text,shadowColor:i.shadow,onClick:u=>{u.stopPropagation(),r?.(t,e,"no");},children:c})]})}function Vu(){let{t:e}=useTranslation();return jsxs("span",{className:"inline-flex h-7 w-[85px] items-center justify-center gap-x-3 rounded-lg p-1.5 text-xs font-semibold flex-shrink-0 bg-gradient-to-r from-primary/15 to-secondary/15 lg:h-9 lg:w-24 lg:gap-x-4 lg:p-2 lg:text-sm",children:[jsx("span",{className:"text-primary",children:e("predict.market.yes")}),jsx("span",{className:"text-neutral-400",children:"/"}),jsx("span",{className:"text-secondary",children:e("predict.market.no")})]})}function Bu({market:e,event:t,formattedVolume:r,href:n,LinkComponent:s,onSelect:a,onSelectOutcome:o}){let{t:i}=useTranslation();return jsxs(Fragment,{children:[jsx("div",{className:"flex-1",children:jsx(Ds,{market:e,event:t,onSelectOutcome:o,dynamicColors:true,labelFormat:"label"})}),jsxs("div",{className:"mt-auto flex items-center justify-between pt-3",children:[jsxs(Linkable,{href:n,LinkComponent:s,as:"button",className:"flex items-center gap-1 text-[10px] font-normal text-neutral-500 transition-colors hover:text-slate-200 cursor-pointer lg:text-xs",onClick:c=>{c.stopPropagation(),n||(c.preventDefault(),a?.(t));},children:[i("predict.event.viewEvent"),jsx(Us,{className:"h-3 w-3"})]}),jsxs("span",{className:"inline-flex items-center gap-x-1.5 text-[10px] font-normal text-neutral-500 lg:text-xs",children:[r," ",i("predict.event.volume"),jsx(Fs,{source:t.source})]})]})]})}function _u({market:e,event:t,onCollapse:r,onSelectOutcome:n}){let{t:s}=useTranslation(),a=_s(e);return jsxs(Fragment,{children:[jsxs("div",{className:"flex-1",children:[jsxs("button",{type:"button",className:"flex h-9 w-full items-center justify-between cursor-pointer",onClick:o=>{o.stopPropagation(),r();},children:[jsx("span",{className:"min-w-0 flex-1 text-left text-xs text-slate-200 lg:text-sm",children:e.outcomes?.[0]?.label??e.question}),jsxs("div",{className:"flex items-center gap-x-1 flex-shrink-0",children:[jsx("span",{className:"text-sm font-semibold text-slate-200 lg:text-lg",children:Qs(a)}),jsx(ChevronUpIcon,{className:"h-4 w-4 text-neutral-400"})]})]}),jsx("div",{className:"mt-3",children:jsx(Ds,{market:e,event:t,onSelectOutcome:n,labelFormat:"action"})})]}),jsxs("button",{type:"button",className:"mt-auto flex items-center gap-x-1 pt-4 text-[10px] font-normal text-neutral-500 transition-colors hover:text-slate-200 cursor-pointer lg:text-xs",onClick:o=>{o.stopPropagation(),r();},children:[jsx(Qu,{className:"h-3 w-3"}),s("predict.event.back")]})]})}function Us({className:e}){return jsx("svg",{viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:e,children:jsx("path",{d:"M4.5 2.5L8 6l-3.5 3.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}function Qu({className:e}){return jsx("svg",{viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:e,children:jsx("path",{d:"M7.5 2.5L4 6l3.5 3.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}function Fs({source:e}){return jsxs("span",{className:"inline-flex items-center gap-x-1 text-neutral-400",title:e==="polymarket"?"Polymarket":"Kalshi",children:[jsx("span",{className:"text-neutral-600",children:"\xB7"}),e==="polymarket"?jsx(PolymarketIcon,{className:"h-5 w-auto shrink-0"}):jsx(KalshiIcon,{className:"h-3 w-auto shrink-0"})]})}var qu=768,qs=1024,Hu=1280,Ku=8,$u=224,zu=304,Gu=114;function Yu(e){return e>=Hu?4:e>=qs?3:e>=qu?2:1}function ju(e){return e>=qs?zu:$u}function Hs({events:e,hasMore:t=false,onFetchMore:r,onSelect:n,onSelectOutcome:s,getEventHref:a,LinkComponent:o,onHover:i}){let l=useRef(null),c=useRef(null),{width:u=0,height:p=0}=useResizeObserver({ref:l}),d=Yu(u),y=ju(u),f=Math.ceil(e.length/d)||0,g=!t&&e.length>0,v=f+(t?1:0)+(g?1:0),h=useCallback(P=>P<f,[f]),b=useCallback(async()=>{r?.();},[r]),x=useInfiniteLoader({isRowLoaded:h,loadMoreRows:b,rowCount:v,threshold:3}),m=useCallback(()=>{c.current?.scrollToRow({index:0,behavior:"smooth"});},[]);return jsx("div",{ref:l,className:"@container w-full h-full",children:p>0&&jsx(List,{listRef:c,className:"no-scrollbar",style:{height:p},onRowsRendered:x,rowComponent:Xu,rowCount:v,rowHeight:P=>g&&P===v-1?Gu:(y),rowProps:{events:e,columnCount:d,dataRowCount:f,showEndOfList:g,totalRowCount:v,onSelect:n,onSelectOutcome:s,getEventHref:a,LinkComponent:o,onHover:i,onScrollToTop:m}})})}function Xu({index:e,style:t,events:r,columnCount:n,dataRowCount:s,showEndOfList:a,totalRowCount:o,onSelect:i,onSelectOutcome:l,getEventHref:c,LinkComponent:u,onHover:p,onScrollToTop:d}){if(a&&e===o-1)return jsx("div",{style:t,children:jsx(Zu,{onScrollToTop:d})});if(e>=s)return jsx("div",{style:t,className:"flex justify-center items-start pt-4",children:jsx(Spinner,{size:"sm"})});let y=e*n,f=r.slice(y,y+n),g=n-f.length;return jsx("div",{style:t,children:jsxs("div",{className:"flex w-full h-full",children:[f.map(v=>v==null?null:jsx("div",{className:"flex-1 min-w-0 flex",style:{padding:Ku},children:jsx(As,{event:v,href:c?.(v),LinkComponent:u,onSelect:i,onSelectOutcome:l,onHover:p})},v.slug)),g>0&&Array.from({length:g}).map((v,h)=>jsx("div",{style:{flex:1,minWidth:0}},`spacer-${h}`))]})})}function Zu({onScrollToTop:e}){let{t}=useTranslation();return jsxs("div",{className:"flex w-full flex-col items-center justify-center gap-y-4 py-6",children:[jsxs("div",{className:"flex w-full items-center justify-center gap-x-4",children:[jsx("div",{className:"h-px w-16 bg-neutral-700"}),jsx("span",{className:"text-xs font-medium text-neutral-500",children:t("predict.event.endOfList")}),jsx("div",{className:"h-px w-16 bg-neutral-700"})]}),jsxs("button",{type:"button",className:"flex cursor-pointer items-center gap-x-1 text-xs font-medium text-neutral-400",onClick:e,children:[jsx("span",{className:"iconify size-4 ph--arrow-up-bold"}),jsx("span",{children:t("predict.event.backToTop")})]})]})}function $s({tagSlugSelection:e,limit:t=48,status:r,sort_by:n,sort_asc:s,source:a,with_markets:o,onSelect:i,onSelectOutcome:l,getEventHref:c,LinkComponent:u,onHover:p}){let{data:d,hasMore:y,fetchMore:f,isFetching:g}=Ts({tagSlugSelection:e,limit:t,status:r,sort_by:n,sort_asc:s,source:a,with_markets:o});return g?jsx(ot,{count:48}):jsx(Hs,{events:d,hasMore:y,onFetchMore:f,onSelect:i,onSelectOutcome:l,getEventHref:c,LinkComponent:u,onHover:p})}function D0({onSelect:e,onSelectOutcome:t,getEventHref:r,LinkComponent:n,onHover:s}){let[a,o]=useState({categorySlug:null,tagSlug:null}),[i,l]=useState(wr),{isOpen:c,onOpen:u,onClose:p}=useDisclosure(),d=useCallback(x=>{o(x);},[]),y=useCallback(x=>{l(m=>({...m,sortPreset:x}));},[]),f=useCallback(x=>{l(m=>({...m,sortAsc:x}));},[]),g=useCallback(x=>{l(x);},[]),v=useMemo(()=>Cs[i.sortPreset].sort_by,[i.sortPreset]),h=useMemo(()=>Tr(i),[i]),b=jsx(Es,{sortPreset:i.sortPreset,onSortChange:y,sortAsc:i.sortAsc,onSortAscChange:f,onFilterPress:u,filterCount:h});return jsxs("div",{className:"flex h-full w-full max-w-[1680px] mx-auto flex-col gap-y-3",children:[jsx(xs,{onSelect:d,trailing:b}),jsx(bs,{isOpen:c,onClose:p,value:i,onChange:g}),jsx("div",{className:"min-h-0 flex-1",children:jsx($s,{tagSlugSelection:a,sort_by:v,sort_asc:i.sortAsc,source:i.source,onSelect:e,onSelectOutcome:t,getEventHref:r,LinkComponent:n,onHover:s})})]})}function _r(e,t,r){let n=e[t];return n?r==="yes"?n.yesMint:n.noMint:null}var ut=SOLANA_TOKENS.stablecoins.USDC.address;function id(){let e={startVelocity:30,spread:360,ticks:60,zIndex:9999};Vr({...e,particleCount:80,origin:{x:.5,y:.4}}),setTimeout(()=>{Vr({...e,particleCount:40,origin:{x:.3,y:.6}});},150),setTimeout(()=>{Vr({...e,particleCount:40,origin:{x:.7,y:.6}});},300);}function js({market:e,chain:t="solana",initialOutcome:r="yes",initialSide:n="buy"}){let{t:s}=useTranslation(),a=useContext(Me),{status:o}=useAuth(),l=useWallets().find(N=>N.chainNamespace===ChainNamespace.SOLANA&&N.isConnected),c=o==="authenticated",u=l?.address,[p,d]=useState(r),[y,f]=useState(n),[g,v]=useState(NaN),h=useMemo(()=>_r(e.accounts,ut,p),[e.accounts,p]),{inputMint:b,outputMint:x}=useMemo(()=>y==="buy"?{inputMint:ut,outputMint:h}:{inputMint:h,outputMint:ut},[y,h]),m=!!b&&!!x&&g>0,P=useMemo(()=>Number(p==="yes"?e.yesAsk??.5:e.noAsk??.5),[p,e.yesAsk,e.noAsk]),w=useMemo(()=>isNaN(g)||g<=0?0:y==="buy"?P>0?g/P:0:g,[y,g,P]),O=useMemo(()=>isNaN(g)||g<=0?0:Math.round(g*1e6),[g]),{data:R,isLoading:C,error:V,refetch:Q}=Un({userPublicKey:u??void 0,inputMint:b??"",outputMint:x??"",amount:O,slippageBps:100},{enabled:m}),Le=a?.usdcBalance??null,Ee=a?.isLoading??false,vn=a?.refetch,be=a?.positions,ht=useMemo(()=>{if(!be||!h)return null;let N=be.find(me=>me.mint===h);return N?N.balance:0},[be,h]),rr=useMemo(()=>_r(e.accounts,ut,"yes"),[e.accounts]),nr=useMemo(()=>_r(e.accounts,ut,"no"),[e.accounts]),Aa=useMemo(()=>{if(!be||!rr)return null;let N=be.find(me=>me.mint===rr);return N?N.balance:0},[be,rr]),Da=useMemo(()=>{if(!be||!nr)return null;let N=be.find(me=>me.mint===nr);return N?N.balance:0},[be,nr]),{data:Fe}=ze(e.ticker,{refetchInterval:5e3}),Ua=useMemo(()=>(p==="yes"?Fe?.yesBids:Fe?.noBids)?.[0]?.price??null,[Fe,p]),Fa=useMemo(()=>(p==="yes"?Fe?.yesAsks:Fe?.noAsks)?.[0]?.price??null,[Fe,p]),Wa=useMemo(()=>R?.priceImpactPct?parseFloat(R.priceImpactPct):null,[R]),bt=useMemo(()=>{if(isNaN(g)||g<=0)return 0;if(R)return parseInt(R.inAmount)/1e6;if(y==="buy")return g;let N=Number(p==="yes"?e.yesBid??0:e.noBid??0);return g*N},[R,y,p,g,e.yesBid,e.noBid]),xn=useMemo(()=>isNaN(g)||g<=0?0:y==="buy"?w*1:bt,[y,w,bt,g]),qa=xn-bt,Ha=useCallback(N=>{f(N),v(NaN);},[]),Ka=useCallback(N=>{if(isNaN(N)){v(NaN);return}let me=Math.max(0,N),St=y==="buy"?Math.round(me*100)/100:Math.round(me);v(St);},[y]);useEffect(()=>{m&&Q();},[g,p,y,m,Q]);let sr=useMemo(()=>{let N=[];return (isNaN(g)||g<ar)&&N.push(`Minimum quantity is ${ar}`),e.status!=="active"&&N.push("Market is not active"),y==="buy"&&Le!=null&&!isNaN(g)&&g>0&&g>Le&&N.push("Insufficient USDC balance"),y==="sell"&&ht!=null&&!isNaN(g)&&g>0&&g>ht&&N.push("Insufficient shares"),{isValid:N.length===0,errors:N}},[g,e.status,y,Le,ht]),[$a,or]=useState(null),[za,We]=useState(false),[kt,tt]=useState(null),{data:Pt}=Fn({signature:kt??""},{enabled:!!kt});useEffect(()=>{if(!Pt||!kt)return;let{status:N}=Pt;N==="closed"?(We(false),tt(null),toast.success(s("predict.trade.submitSuccess")),id(),v(NaN),vn?.()):(N==="failed"||N==="expired")&&(We(false),tt(null),toast.error(s("predict.trade.submitError")));},[Pt,kt,vn,s]);let Ga=useCallback(async()=>{if(!(!sr.isValid||!c||!u||!l||Ee)){or(null),tt(null),We(true);try{let N=R;if(N?.transaction||(N=(await Q()).data),!N?.transaction){We(!1);return}let me=Uint8Array.from(atob(N.transaction),hn=>hn.charCodeAt(0)),St=await l.sendTransaction(me);or(St),tt(St);}catch{toast.error(s("predict.trade.submitError")),We(false);}}},[sr.isValid,c,u,l,R,Ee,Q,s]),Ya=useCallback(()=>{d(r),f(n),v(NaN),or(null),tt(null),We(false);},[r,n]);return {outcome:p,side:y,quantity:g,shares:w,estimatedCost:bt,potentialPayout:xn,potentialProfit:qa,isAuthenticated:c,bestBid:Ua,bestAsk:Fa,order:R??null,priceImpact:Wa,usdcBalance:Le,outcomeTokenBalance:ht,yesTokenBalance:Aa,noTokenBalance:Da,isBalanceLoading:Ee,isQuoteLoading:C,isSubmitting:za,quoteError:V??null,txHash:$a,orderStatus:Pt??null,validation:sr,setOutcome:d,setSide:Ha,setQuantity:Ka,submit:Ga,reset:Ya}}var md=`https://s1.chainstream.io/chains/sol/tokens/${SOLANA_TOKENS.stablecoins.USDC.address}/image.png`;function eo({event:e,market:t,outcome:r,side:n,quantity:s,potentialProfit:a,estimatedCost:o,usdcBalance:i,yesTokenBalance:l,noTokenBalance:c,isBalanceLoading:u,isSubmitting:p,isValid:d,onOutcomeChange:y,onSideChange:f,onQuantityChange:g,onSubmit:v}){let{t:h}=useTranslation(),b=useMemo(()=>{if(p)return h("predict.trade.submitting");let m=h(n==="buy"?"predict.trade.buy":"predict.trade.sell"),P=h(r==="yes"?"predict.trade.yes":"predict.trade.no");return `${m} ${P}`},[p,n,r,h]),x=useMemo(()=>r==="yes"?"primary":"secondary",[r]);return jsxs("div",{className:"flex w-full flex-col gap-y-4 rounded-xl border border-default-200 bg-content1 p-4",children:[e&&jsxs("div",{className:"flex items-center gap-x-3",children:[e.imageUrl&&jsx("img",{src:e.imageUrl,alt:e.title,className:"h-10 w-10 shrink-0 rounded-lg object-cover"}),jsxs("div",{className:"flex min-w-0 flex-col gap-y-0.5",children:[jsx("span",{className:"text-sm text-neutral-500 leading-tight line-clamp-1",children:e.title}),jsxs("span",{className:"text-base font-semibold leading-tight line-clamp-1",children:[jsxs("span",{className:r==="yes"?"text-bullish":"text-bearish",children:[h(n==="buy"?"predict.trade.buy":"predict.trade.sell")," ",h(r==="yes"?"predict.trade.yes":"predict.trade.no")]}),jsxs("span",{className:"text-foreground",children:[" \xB7 ",r==="yes"?t.yesSubTitle:t.noSubTitle]})]})]})]}),jsxs(Tabs,{variant:"underlined",selectedKey:n,onSelectionChange:m=>f(m),classNames:{tabList:"gap-x-4",tab:"px-0"},children:[jsx(Tab,{title:h("predict.trade.buy")},"buy"),jsx(Tab,{title:h("predict.trade.sell")},"sell")]}),jsx("div",{className:"flex gap-x-2",children:["yes","no"].map(m=>{let P=m==="yes"?l:c;return jsxs("div",{className:"flex flex-1 flex-col gap-y-1",children:[jsxs("button",{type:"button",onClick:()=>y(m),className:`w-full rounded-lg border py-2 text-sm font-medium transition-colors cursor-pointer ${r===m?m==="yes"?"border-primary bg-primary-50 text-primary":"border-secondary bg-secondary-50 text-secondary":"border-default-400 text-foreground hover:border-default-500"}`,children:[jsx("span",{children:h(m==="yes"?"predict.trade.yes":"predict.trade.no")}),(()=>{let w=n==="buy"?m==="yes"?t.yesAsk:t.noAsk:m==="yes"?t.yesBid:t.noBid;return w!=null?jsxs("span",{className:"ml-1 opacity-70",children:[Math.round(Number(w)*100),"\xA2"]}):null})()]}),n==="sell"&&r===m&&jsx("span",{className:"text-center text-xs text-foreground",children:u?"\u2013":`${P??0} shares`})]},m)})}),n==="buy"&&jsxs("div",{className:"flex items-center justify-end gap-x-1 text-xs text-default-500",children:[jsx("img",{src:md,alt:"USDC",className:"h-4 w-4 rounded-full object-cover"}),jsxs("span",{children:[h("predict.trade.balance"),":"]}),jsx("span",{className:"font-medium text-foreground",children:i!=null?`$${i.toFixed(2)}`:"\u2013"})]}),jsxs("div",{className:"flex flex-col gap-y-1.5",children:[jsx("span",{className:"text-sm font-medium text-foreground",children:h(n==="buy"?"predict.trade.amount":"predict.trade.contracts")}),jsx(StyledNumberInput,{fullWidth:true,placeholder:"0",radius:"lg",size:"lg",value:isNaN(s)?void 0:s,onValueChange:m=>{g(m);},minValue:0,step:n==="buy"?.01:1,formatOptions:n==="buy"?{maximumFractionDigits:2}:{maximumFractionDigits:0},startContent:n==="buy"?jsx("span",{className:"text-default-600 text-xl",children:"$"}):void 0,classNames:{inputWrapper:"bg-content2 data-[hover=true]:bg-content2 group-data-[focus=true]:bg-content2 h-14 min-h-14",input:"text-lg"}},n),jsx("div",{className:"flex gap-x-2 justify-end",children:n==="buy"?jsxs(Fragment,{children:[[1,5,10,100].map(m=>jsxs("button",{type:"button",onClick:()=>g(Math.round(((isNaN(s)?0:s)+m)*100)/100),className:"rounded-md bg-content2 px-2.5 py-1 text-xs font-medium text-default-600 transition-colors hover:bg-content3 cursor-pointer",children:["+",m,"$"]},m)),jsx("button",{type:"button",onClick:()=>{},className:"rounded-md bg-content2 px-2.5 py-1 text-xs font-medium text-default-600 transition-colors hover:bg-content3 cursor-pointer",children:h("common.all")})]}):jsxs(Fragment,{children:[[25,50].map(m=>jsxs("button",{type:"button",onClick:()=>{},className:"rounded-md bg-content2 px-2.5 py-1 text-xs font-medium text-default-600 transition-colors hover:bg-content3 cursor-pointer",children:[m,"%"]},m)),jsx("button",{type:"button",onClick:()=>{},className:"rounded-md bg-content2 px-2.5 py-1 text-xs font-medium text-default-600 transition-colors hover:bg-content3 cursor-pointer",children:h("common.all")})]})})]}),!isNaN(s)&&s>0&&jsxs("div",{className:"flex flex-col items-end gap-y-0.5",children:[jsx("span",{className:"text-sm text-foreground",children:h(n==="buy"?"predict.trade.potentialWin":"predict.trade.estimatedReceive")}),jsxs("span",{className:"text-xl font-semibold text-bullish",children:["$",(n==="buy"?a:o).toFixed(2)]})]}),jsx(Button,{color:x,fullWidth:true,radius:"lg",size:"lg",isDisabled:!d||p,isLoading:p,onPress:v,children:b})]})}function je({event:e,market:t,initialSide:r,initialOutcome:n,chain:s}){let{outcome:a,side:o,quantity:i,estimatedCost:l,potentialPayout:c,potentialProfit:u,usdcBalance:p,yesTokenBalance:d,noTokenBalance:y,isBalanceLoading:f,isSubmitting:g,validation:v,setOutcome:h,setSide:b,setQuantity:x,submit:m}=js({market:t,initialSide:r,initialOutcome:n,chain:s}),P=useAuthCallback(m);return jsx(eo,{event:e,market:t,outcome:a,side:o,quantity:i,estimatedCost:l,potentialPayout:c,potentialProfit:u,usdcBalance:p,yesTokenBalance:d,noTokenBalance:y,isBalanceLoading:f,isSubmitting:g,isValid:v.isValid,validationErrors:v.errors,onOutcomeChange:h,onSideChange:b,onQuantityChange:x,onSubmit:P})}function gd(){return jsxs("div",{className:"flex items-center gap-x-3 px-2 py-3 lg:gap-x-4",children:[jsx(Skeleton,{className:"h-4 flex-1 rounded-md"}),jsx(Skeleton,{className:"h-5 w-10 shrink-0 rounded-md"}),jsxs("div",{className:"flex gap-x-2",children:[jsx(Skeleton,{className:"h-8 w-16 rounded-lg"}),jsx(Skeleton,{className:"h-8 w-16 rounded-lg"})]})]})}function ge({marketCount:e=4}){return jsxs("div",{className:"w-full flex flex-col gap-4 lg:gap-y-6 px-1 lg:px-4 lg:max-w-3xl animate-pulse",children:[jsxs("div",{className:"flex items-center gap-x-3 lg:gap-x-4",children:[jsx(Skeleton,{className:"h-14 w-14 shrink-0 rounded-lg lg:h-18 lg:w-18"}),jsxs("div",{className:"flex flex-col gap-y-1.5 min-w-0 flex-1",children:[jsx(Skeleton,{className:"h-3 w-24 rounded-md lg:w-32"}),jsx(Skeleton,{className:"h-5 w-48 rounded-md lg:h-6 lg:w-72"})]})]}),jsx(Skeleton,{className:"h-[200px] w-full rounded-xl lg:h-[280px]"}),jsxs("div",{className:"flex items-center justify-between",children:[jsx(Skeleton,{className:"h-3 w-32 rounded-md"}),jsx("div",{className:"flex gap-x-1",children:Array.from({length:4}).map((t,r)=>jsx(Skeleton,{className:"h-7 w-10 rounded-md"},r))})]}),jsx("div",{className:"flex flex-col divide-y divide-default-200",children:Array.from({length:e}).map((t,r)=>jsx(gd,{},r))})]})}function Ut(){return jsxs("div",{className:"flex w-full flex-col gap-y-4 rounded-xl border border-default-200 bg-content1 p-4 animate-pulse",children:[jsxs("div",{className:"flex items-center gap-x-3",children:[jsx(Skeleton,{className:"h-10 w-10 shrink-0 rounded-lg"}),jsxs("div",{className:"flex flex-col gap-y-1 flex-1",children:[jsx(Skeleton,{className:"h-3 w-28 rounded-md"}),jsx(Skeleton,{className:"h-4 w-40 rounded-md"})]})]}),jsxs("div",{className:"flex gap-x-4",children:[jsx(Skeleton,{className:"h-4 w-12 rounded-md"}),jsx(Skeleton,{className:"h-4 w-12 rounded-md"})]}),jsxs("div",{className:"flex gap-x-2",children:[jsx(Skeleton,{className:"h-10 flex-1 rounded-lg"}),jsx(Skeleton,{className:"h-10 flex-1 rounded-lg"})]}),jsx(Skeleton,{className:"h-14 w-full rounded-lg"}),jsx(Skeleton,{className:"h-12 w-full rounded-lg"})]})}var to=e=>{let{candlestickMarketTickers:t,chartRange:r=le}=e,n=He[r],s=Ke[r],a=useMemo(()=>Math.floor(Date.now()/1e3),[r]),o=k(),{data:i,isLoading:l,error:c}=Tt({id:e.eventId,withNestedMarkets:true}),u=useMemo(()=>{if(s!=null)return a-s;let x=i?.markets;return x?.length?Math.min(...x.map(m=>m.openTime)):a},[a,s,i?.markets]),{data:p,isLoading:d,error:y}=Vn(i?.seriesTicker??"",{enabled:!!i?.seriesTicker}),f=useMemo(()=>i?.markets?(t&&t.length>0?t.slice(0,4).map(m=>i.markets.find(P=>P.ticker===m)).filter(m=>m!==void 0):[...i.markets].sort((m,P)=>Number(P.yesAsk??0)-Number(m.yesAsk??0)).slice(0,4)).map(m=>m.ticker):[],[t,i?.markets]),g=useQueries({queries:f.map(x=>({queryKey:rt({ticker:x,startTs:u,endTs:a,periodInterval:n}),queryFn:()=>nt(o,{ticker:x,startTs:u,endTs:a,periodInterval:n}),enabled:f.length>0}))}),v=g.some(x=>x.isLoading),h=useMemo(()=>{let x=new Map;return f.forEach((m,P)=>{let w=g[P]?.error;w&&x.set(m,w);}),x},[f,g]),b=useMemo(()=>{let x=new Map;return f.forEach((m,P)=>{let w=g[P]?.data;w&&x.set(m,w);}),x},[f,g]);return {event:i,isEventLoading:l,eventError:c,series:p,isSeriesLoading:d,seriesError:y,periodInterval:n,candlesticks:b,isCandlesticksLoading:v,candlestickErrors:h}};var Ed=SOLANA_TOKENS.stablecoins.USDC.address;function ro(e){let{status:t}=useAuth(),n=useWallets().find(c=>c.chainNamespace===ChainNamespace.SOLANA&&c.isConnected),s=t==="authenticated",a=n?.address,{data:o,isLoading:i}=useWalletPortfoliosQuery({chain:Chain.SOLANA,address:a??""},{enabled:s&&!!a,refetchInterval:1e4});return {holdings:useMemo(()=>{let c=new Map;if(!o?.portfolios||e.length===0)return c;let u=new Map;for(let p of o.portfolios)u.set(p.address,parseFloat(p.amount));for(let p of e){let d=p.accounts[Ed];if(!d)continue;let y=u.get(d.yesMint)??0,f=u.get(d.noMint)??0;(y>0||f>0)&&c.set(p.ticker,{yesShares:y,noShares:f});}return c},[o,e]),isLoading:i}}function Bd(e){let{cx:t,cy:r,index:n,dataLength:s,stroke:a}=e;return n!==s-1||t==null||r==null?null:jsxs("g",{children:[jsxs("circle",{cx:t,cy:r,r:6,fill:a,opacity:.3,children:[jsx("animate",{attributeName:"r",values:"4;8;4",dur:"2s",repeatCount:"indefinite"}),jsx("animate",{attributeName:"opacity",values:"0.4;0.1;0.4",dur:"2s",repeatCount:"indefinite"})]}),jsx("circle",{cx:t,cy:r,r:3,fill:a})]})}var Ft=[{stroke:"hsl(var(--heroui-primary))",id:"colorMarket0"},{stroke:"hsl(var(--heroui-secondary))",id:"colorMarket1"},{stroke:"hsl(var(--heroui-success))",id:"colorMarket2"},{stroke:"hsl(var(--heroui-warning))",id:"colorMarket3"}];function no(e,t){let r=new Date(e*1e3);switch(t){case S.ONE_DAY:return r.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:false});case S.ONE_WEEK:case S.ONE_MONTH:return r.toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:false});case S.ALL:default:return r.toLocaleDateString("en-US",{month:"short",day:"numeric"})}}function _d(e,t,r){let n=Mt[r],s=new Map;e.forEach((l,c)=>{let u=new Map;(l.candlesticks??[]).forEach(d=>{let y=d.end_period_ts-d.end_period_ts%n;u.set(y,d.yes_ask.close);}),s.set(c,u);});let a=new Set;for(let l of s.values())for(let c of l.keys())a.add(c);let o=Array.from(a).sort((l,c)=>l-c),i=new Map;return o.map(l=>{let u={date:new Date(l*1e3).toLocaleDateString("en-US",{month:"short",day:"numeric"}),timestamp:l};return t.forEach(p=>{let d=s.get(p)?.get(l);if(d!==void 0)u[p]=Math.round(d*100)/100,i.set(p,u[p]);else {let y=i.get(p);y!==void 0&&(u[p]=y);}}),u})}function Wt({candlesticks:e,markets:t=[],isLoading:r,chartRange:n=S.ALL,onDataChange:s}){let[a,o]=useState(null),i=useRef(s);useEffect(()=>{i.current=s;});let l=useMemo(()=>e?Array.from(e.keys()).slice(0,4):[],[e]),c=useMemo(()=>!e||e.size===0?[]:_d(e,l,n),[e,l,n]),u=useMemo(()=>{if(c.length===0||l.length===0)return [0,100];let f=1/0,g=-1/0;if(c.forEach(m=>{l.forEach(P=>{let w=m[P];w!==void 0&&(f=Math.min(f,w),g=Math.max(g,w));});}),f===1/0||g===-1/0)return [0,100];let v=g-f,h=Math.max(v*.2,5),b=Math.max(0,Math.floor(f-h)),x=Math.min(100,Math.ceil(g+h));return [b,x]},[c,l]),p=useCallback(f=>{if(c.length===0)return null;let g=f!==null?c[f]:c[c.length-1];return g?{timestamp:g.timestamp,date:g.date,markets:l.map((v,h)=>{let b=t.find(x=>x.ticker===v);return {id:v,label:b?.yesSubTitle||`Market ${h+1}`,value:g[v]??0,color:Ft[h%Ft.length].stroke}})}:null},[c,l,t]);useEffect(()=>{i.current&&c.length>0&&i.current(p(null));},[c,p]),useEffect(()=>{i.current&&i.current(p(a));},[a,p]);let d=useCallback(f=>{typeof f?.activeTooltipIndex=="number"&&o(f.activeTooltipIndex);},[]),y=useCallback(()=>{o(null);},[]);return r?jsx("div",{className:"h-[200px] w-full lg:h-[300px] flex items-center justify-center",children:jsx("div",{className:"text-default-400 text-sm",children:"Loading chart..."})}):c.length===0?jsx("div",{className:"h-[200px] w-full lg:h-[300px] flex items-center justify-center",children:jsx("div",{className:"text-default-400 text-sm",children:"No price history data"})}):jsx("div",{className:"h-[200px] w-full lg:h-[300px]",children:jsx(ResponsiveContainer,{width:"100%",height:"100%",children:jsxs(LineChart,{data:c,margin:{top:10,right:16,left:16,bottom:0},onMouseMove:d,onMouseLeave:y,children:[jsx(XAxis,{dataKey:"timestamp",tick:f=>{let{x:g,y:v,payload:h,index:b}=f,x=c.length,P=Math.max(1,Math.ceil(x/6)),w=b===0,O=b===x-1,R=b%P===0;return !w&&!O&&!R?null:jsx("text",{x:g,y:v+10,textAnchor:"middle",fill:"hsl(var(--heroui-default-500))",fontSize:10,children:no(h.value,n)})},tickLine:false,axisLine:false,interval:0}),jsx(CartesianGrid,{horizontal:true,vertical:false,strokeDasharray:"3 3",stroke:"hsl(var(--heroui-default-200))"}),jsx(YAxis,{domain:u,tickLine:false,axisLine:false,tick:{fontSize:10,fill:"hsl(var(--heroui-default-500))"},tickFormatter:f=>`${f}%`,width:40}),jsx(Tooltip,{contentStyle:{backgroundColor:"hsl(var(--heroui-content1))",border:"1px solid hsl(var(--heroui-default-200))",borderRadius:"8px",fontSize:"12px"},labelFormatter:f=>no(f,n),formatter:(f,g)=>{let h=t.find(b=>b.ticker===g)?.yesSubTitle||g;return [`${f.toFixed(2)}%`,h]}}),l.map((f,g)=>jsx(Line,{type:"monotone",dataKey:f,stroke:Ft[g%Ft.length].stroke,strokeWidth:2,isAnimationActive:false,dot:v=>jsx(Bd,{...v,dataLength:c.length},`dot-${f}-${v.index}`),activeDot:false},f))]})})})}function qt(){return {timestamp:Date.now()/1e3,date:new Date().toLocaleDateString("en-US",{month:"short",day:"numeric"}),markets:[]}}function oo({marketTicker:e,openTime:t,chartRange:r=le}){let n=He[r],s=Ke[r],a=useMemo(()=>Math.floor(Date.now()/1e3),[r]),o=useMemo(()=>s!=null?a-s:t??a,[a,s,t]),{data:i,isLoading:l,isFetching:c,error:u}=br({ticker:e,startTs:o,endTs:a,periodInterval:n},{enabled:!!e});return {candlesticks:i,isLoading:l,isFetching:c,error:u,periodInterval:n}}var Hd="hsl(var(--heroui-primary))",Kd=[{value:S.ONE_DAY,label:"1D"},{value:S.ONE_WEEK,label:"1W"},{value:S.ONE_MONTH,label:"1M"},{value:S.ALL,label:"ALL"}];function $d(e){let{cx:t,cy:r,index:n,dataLength:s,stroke:a}=e;return n!==s-1||t==null||r==null?null:jsxs("g",{children:[jsxs("circle",{cx:t,cy:r,r:6,fill:a,opacity:.3,children:[jsx("animate",{attributeName:"r",values:"4;8;4",dur:"2s",repeatCount:"indefinite"}),jsx("animate",{attributeName:"opacity",values:"0.4;0.1;0.4",dur:"2s",repeatCount:"indefinite"})]}),jsx("circle",{cx:t,cy:r,r:3,fill:a})]})}function io(e,t){let r=new Date(e*1e3);switch(t){case S.ONE_DAY:return r.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:false});case S.ONE_WEEK:case S.ONE_MONTH:return r.toLocaleDateString("en-US",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",hour12:false});case S.ALL:default:return r.toLocaleDateString("en-US",{month:"short",day:"numeric"})}}function zd(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:e.toFixed(0)}function Gd(e,t){let r=Mt[t],n=e.candlesticks??[],s=new Map;for(let o of n){let i=o.end_period_ts-o.end_period_ts%r,l=s.get(i);s.set(i,{close:o.yes_ask.close,volume:(l?.volume??0)+(o.volume??0)});}return Array.from(s.entries()).sort((o,i)=>o[0]-i[0]).map(([o,{close:i,volume:l}])=>({timestamp:o,date:new Date(o*1e3).toLocaleDateString("en-US",{month:"short",day:"numeric"}),value:Math.round(i*100)/100,volume:l}))}function lo({candlesticks:e,isLoading:t,chartRange:r,onRangeChange:n}){let s=useMemo(()=>e?Gd(e,r):[],[e,r]),a=useMemo(()=>{if(s.length===0)return [0,100];let o=1/0,i=-1/0;for(let d of s)d.value<o&&(o=d.value),d.value>i&&(i=d.value);if(o===1/0||i===-1/0)return [0,100];let l=i-o,c=Math.max(l*.2,5),u=Math.max(0,Math.floor(o-c)),p=Math.min(100,Math.ceil(i+c));return [u,p]},[s]);return t?jsxs("div",{className:"flex flex-col gap-y-2",children:[jsx("div",{className:"h-[200px] w-full flex items-center justify-center",children:jsx("div",{className:"text-neutral text-sm",children:"Loading chart..."})}),jsx(Fr,{chartRange:r,onRangeChange:n})]}):s.length===0?jsxs("div",{className:"flex flex-col gap-y-2",children:[jsx("div",{className:"h-[200px] w-full flex items-center justify-center",children:jsx("div",{className:"text-neutral text-sm",children:"No price history data"})}),jsx(Fr,{chartRange:r,onRangeChange:n})]}):jsxs("div",{className:"flex flex-col gap-y-2",children:[jsx("div",{className:"h-[200px] w-full",children:jsx(ResponsiveContainer,{width:"100%",height:"100%",children:jsxs(LineChart,{data:s,margin:{top:10,right:16,left:16,bottom:0},children:[jsx(XAxis,{dataKey:"timestamp",tick:o=>{let{x:i,y:l,payload:c,index:u}=o,p=s.length,y=Math.max(1,Math.ceil(p/6)),f=u===0,g=u===p-1,v=u%y===0;return !f&&!g&&!v?null:jsx("text",{x:i,y:l+10,textAnchor:"middle",fill:"hsl(var(--heroui-default-500))",fontSize:10,children:io(c.value,r)})},tickLine:false,axisLine:false,interval:0}),jsx(CartesianGrid,{horizontal:true,vertical:false,strokeDasharray:"3 3",stroke:"hsl(var(--heroui-default-200))"}),jsx(YAxis,{domain:a,tickLine:false,axisLine:false,tick:{fontSize:10,fill:"hsl(var(--heroui-default-500))"},tickFormatter:o=>`${o}%`,width:40}),jsx(Tooltip,{cursor:{stroke:"hsl(var(--heroui-default-300))"},content:({active:o,payload:i})=>{if(!o||!i?.length)return null;let l=i[0].payload,c=Math.round(l.value);return jsxs("div",{className:"rounded-lg border border-default-200 bg-content1 px-3 py-2 shadow-md",children:[jsxs("div",{className:"text-lg font-semibold text-primary",children:["Yes ",c,"\xA2"]}),jsxs("div",{className:"text-sm text-neutral",children:["Vol ",zd(l.volume)," \xB7"," ",io(l.timestamp,r)]})]})}}),jsx(Line,{type:"monotone",dataKey:"value",stroke:Hd,strokeWidth:2,isAnimationActive:false,dot:o=>jsx($d,{...o,dataLength:s.length},`dot-${o.index}`),activeDot:false})]})})}),jsx(Fr,{chartRange:r,onRangeChange:n})]})}function Fr({chartRange:e,onRangeChange:t}){return jsx("div",{className:"flex items-center justify-end gap-x-1",children:Kd.map(r=>{let n=e===r.value;return jsx("button",{type:"button",className:`px-3 py-1 text-xs rounded-md transition-colors cursor-pointer ${n?"bg-primary text-primary-foreground":"bg-default-100 text-default-600 hover:bg-default-200"}`,onClick:()=>t?.(r.value),children:r.label},r.value)})})}function co({marketTicker:e}){let{data:t,isLoading:r,error:n}=ze(e,{enabled:!!e});return {orderbook:useMemo(()=>{if(!t)return null;let{yesBids:a,yesAsks:o,noBids:i,noAsks:l}=t;return {yesBids:a,yesAsks:o,noBids:i,noAsks:l,bestYesBid:a.length>0?a[0].price:null,bestYesAsk:o.length>0?o[0].price:null,bestNoBid:i.length>0?i[0].price:null,bestNoAsk:l.length>0?l[0].price:null,sequence:t.sequence??null}},[t]),isOrderbookLoading:r,orderbookError:n}}function uo(e,t){let r=e.slice(0,t),n=0;return r.map(s=>(n+=s.quantity,{...s,cumulative:n,depth:0,total:s.price*s.quantity}))}function po(e,t){for(let r of e)r.depth=t>0?r.cumulative/t:0;}function go(e){return `${Math.round(e*100)}\xA2`}function Xd(e){return e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}K`:e.toLocaleString()}function Zd(e){return e>=1e6?`$${(e/1e6).toFixed(2)}M`:e>=1e3?`$${(e/1e3).toFixed(2)}K`:e>=1?`$${e.toFixed(2)}`:`$${e.toFixed(4)}`}function mo({row:e,side:t,showType:r=false,onClick:n}){let{t:s}=useTranslation(),a=t==="ask",o=a?"bg-bullish/10":"bg-bearish/10",i=a?"text-bullish":"text-bearish";return jsxs("button",{type:"button",className:"relative grid w-full grid-cols-4 px-2 py-2.5 text-xs cursor-pointer hover:bg-default-100 transition-colors",onClick:()=>n?.(e.price,t),children:[jsx("div",{className:`absolute inset-y-0 left-0 ${o} transition-[width] duration-200`,style:{width:`${e.depth*100}%`}}),jsx("span",{className:`relative z-10 font-mono font-medium ${i} text-left`,children:r?s(a?"predict.trade.bestAsk":"predict.trade.bestBid"):""}),jsx("span",{className:"relative z-10 font-mono text-foreground text-right",children:go(e.price)}),jsx("span",{className:"relative z-10 font-mono text-foreground text-right",children:Xd(e.quantity)}),jsx("span",{className:"relative z-10 font-mono text-foreground text-right",children:Zd(e.total)})]})}function fo({index:e}){let t=["60%","45%","75%","55%","65%","50%","70%","40%"];return jsxs("div",{className:"grid grid-cols-4 gap-x-2 px-2 py-2.5",children:[jsx("div",{className:"h-4 animate-pulse rounded bg-default-100",style:{width:t[e%t.length]}}),jsx("div",{className:"h-4 animate-pulse rounded bg-default-100 ml-auto w-3/4"}),jsx("div",{className:"h-4 animate-pulse rounded bg-default-100 ml-auto w-3/4"}),jsx("div",{className:"h-4 animate-pulse rounded bg-default-100 ml-auto w-3/4"})]})}function Jd(){return jsxs("div",{className:"flex flex-col",children:[jsxs("div",{className:"grid grid-cols-4 gap-x-2 px-2 py-2.5",children:[jsx("div",{}),jsx("div",{className:"h-4 animate-pulse rounded bg-default-100 ml-auto w-1/2"}),jsx("div",{className:"h-4 animate-pulse rounded bg-default-100 ml-auto w-1/2"}),jsx("div",{className:"h-4 animate-pulse rounded bg-default-100 ml-auto w-1/2"})]}),Array.from({length:Wr}).map((e,t)=>jsx(fo,{index:t},`ask-${t}`)),jsx("div",{className:"flex justify-center border-y border-default-200 px-2 py-2.5",children:jsx("div",{className:"h-4 w-24 animate-pulse rounded bg-default-100"})}),Array.from({length:Wr}).map((e,t)=>jsx(fo,{index:t+3},`bid-${t}`))]})}var Wr=8;function qr({bids:e,asks:t,isLoading:r=false,maxLevels:n=Wr,onPriceClick:s}){let{t:a}=useTranslation(),{bidRows:o,askRows:i,spread:l,spreadPercent:c}=useMemo(()=>{let p=uo(e,n),d=uo(t,n),y=Math.max(p[p.length-1]?.cumulative??0,d[d.length-1]?.cumulative??0);po(p,y),po(d,y);let f=p[0]?.price??null,g=d[0]?.price??null,v=null,h=null;if(f!=null&&g!=null){v=g-f;let b=(f+g)/2;b>0&&(h=Math.round(v/b*1e4)/100);}return {bidRows:p,askRows:d,spread:v,spreadPercent:h}},[e,t,n]);return r?jsx(Jd,{}):o.length===0&&i.length===0?jsx("div",{className:"flex items-center justify-center py-6 text-sm text-neutral",children:a("predict.orderBook.empty")}):jsxs("div",{className:"flex flex-col",children:[jsxs("div",{className:"grid grid-cols-4 px-2 py-2.5 text-xs text-neutral",children:[jsx("span",{}),jsx("span",{className:"text-right",children:a("predict.orderBook.price")}),jsx("span",{className:"text-right",children:a("predict.orderBook.contracts")}),jsx("span",{className:"text-right",children:a("predict.orderBook.total")})]}),jsx("div",{className:"flex flex-col-reverse",children:i.map((p,d)=>jsx(mo,{row:p,side:"ask",showType:d===0,onClick:s},p.price))}),l!=null&&jsxs("div",{className:"flex items-center justify-center gap-x-2 border-y border-default-200 px-2 py-2.5 text-xs text-default-500",children:[jsxs("span",{children:[a("predict.orderBook.spread"),": ",go(l)]}),c!=null&&jsxs("span",{className:"text-default-400",children:["(",c,"%)"]})]}),jsx("div",{className:"flex flex-col",children:o.map((p,d)=>jsx(mo,{row:p,side:"bid",showType:d===0,onClick:s},p.price))})]})}function rp(e){return e>=1e6?`${(e/1e6).toFixed(2)}M`:e>=1e3?`${(e/1e3).toFixed(2)}K`:e.toLocaleString(void 0,{maximumFractionDigits:2})}function np(e){let t=Math.abs(e),r=e>=0?"+":"-";return t>=1e3?`${r}$${(t/1e3).toFixed(1)}K`:t>=1?`${r}$${t.toFixed(2)}`:`${r}$${t.toFixed(4)}`}function vo({positions:e,isLoading:t=false}){let{t:r}=useTranslation();return t?jsx("div",{className:"flex items-center justify-center py-8",children:jsx(Spinner,{size:"sm"})}):e.length===0?jsx("div",{className:"flex items-center justify-center py-6 text-sm text-neutral",children:r("predict.positions.empty")}):jsxs("div",{className:"flex flex-col",children:[jsxs("div",{className:"grid grid-cols-5 px-2 py-2.5 text-xs text-neutral",children:[jsx("span",{children:r("predict.positions.outcome")}),jsx("span",{className:"text-right",children:r("predict.positions.qty")}),jsx("span",{className:"text-right",children:r("predict.positions.avgCost")}),jsx("span",{className:"text-right",children:r("predict.positions.currentPrice")}),jsx("span",{className:"text-right",children:r("predict.positions.pnl")})]}),e.map(n=>{let s=n.position==="YES",a=s?"text-bullish":"text-bearish",o=r(s?"predict.market.yes":"predict.market.no"),i=n.avgCost!=null?`${Math.round(n.avgCost*100)}\xA2`:"\u2014",l=n.currentPrice!=null?`${Math.round(n.currentPrice*100)}\xA2`:"\u2014",c=n.pnl!=null&&n.pnlPercent!=null,u=c&&n.pnl>0?"text-bullish":c&&n.pnl<0?"text-bearish":"text-foreground";return jsxs("div",{className:"grid grid-cols-5 px-2 py-2.5 text-xs hover:bg-default-100 transition-colors",children:[jsx("span",{className:`font-medium ${a}`,children:o}),jsx("span",{className:"text-right font-mono text-foreground",children:rp(n.balance)}),jsx("span",{className:"text-right font-mono text-foreground",children:i}),jsx("span",{className:"text-right font-mono text-foreground",children:l}),jsx("span",{className:`text-right font-mono ${u}`,children:c?jsxs("span",{className:"flex flex-col items-end",children:[jsx("span",{children:np(n.pnl)}),jsxs("span",{className:"text-[10px] opacity-70",children:[n.pnlPercent>=0?"+":"",n.pnlPercent.toFixed(1),"%"]})]}):"\u2014"})]},n.mint)})]})}function op(e){let t=e/1e6;return t>=1e6?`${(t/1e6).toFixed(2)}M`:t>=1e3?`${(t/1e3).toFixed(2)}K`:t.toLocaleString(void 0,{maximumFractionDigits:2})}function ap(e){return e==null?"\u2014":`${Math.round(e*100)}\xA2`}function ip(e){let t=new Date(e*1e3),r=t.toLocaleString("default",{month:"short"}),n=t.getDate(),s=t.getHours().toString().padStart(2,"0"),a=t.getMinutes().toString().padStart(2,"0");return `${r} ${n} ${s}:${a}`}function lp({index:e}){let t=["60%","45%","75%","55%","65%"];return jsxs("div",{className:"grid grid-cols-4 gap-x-2 px-2 py-2.5",children:[jsx("div",{className:"h-4 animate-pulse rounded bg-default-100",style:{width:t[e%t.length]}}),jsx("div",{className:"h-4 animate-pulse rounded bg-default-100 ml-auto w-3/4"}),jsx("div",{className:"h-4 animate-pulse rounded bg-default-100 ml-auto w-3/4"}),jsx("div",{className:"h-4 animate-pulse rounded bg-default-100 ml-auto w-3/4"})]})}function xo({trades:e,isLoading:t=false}){let{t:r}=useTranslation();return t?jsx("div",{className:"flex flex-col",children:Array.from({length:6}).map((n,s)=>jsx(lp,{index:s},s))}):e.length===0?jsx("div",{className:"flex items-center justify-center py-6 text-sm text-neutral",children:r("predict.tradeHistory.empty")}):jsxs("div",{className:"flex flex-col",children:[jsxs("div",{className:"grid grid-cols-4 px-2 py-2.5 text-xs text-neutral",children:[jsx("span",{children:r("predict.tradeHistory.side")}),jsx("span",{className:"text-right",children:r("predict.tradeHistory.price")}),jsx("span",{className:"text-right",children:r("predict.tradeHistory.qty")}),jsx("span",{className:"text-right",children:r("predict.tradeHistory.time")})]}),e.map(n=>{let s=n.side==="yes",a=s?"text-bullish":"text-bearish",o=n.side?r(s?"predict.trade.yes":"predict.trade.no"):"\u2014";return jsxs("div",{className:"grid grid-cols-4 px-2 py-2.5 text-xs hover:bg-default-100 transition-colors",children:[jsx("span",{className:`font-medium ${a}`,children:o}),jsx("span",{className:"text-right font-mono text-foreground",children:ap(n.usdPricePerContract)}),jsx("span",{className:"text-right font-mono text-foreground",children:op(n.outputAmount)}),jsx("span",{className:"text-right text-default-500",children:ip(n.createdAt)})]},n.id)})]})}function Kt({market:e,onTradeAction:t}){let{t:r}=useTranslation(),[n,s]=useState("trade-yes"),[a,o]=useState(le),{orderbook:i,isOrderbookLoading:l}=co({marketTicker:e.ticker}),{candlesticks:c,isFetching:u}=oo({marketTicker:e.ticker,openTime:e.openTime,chartRange:a}),{positions:p,isLoading:d}=Qn(e),{status:y}=useAuth(),v=useWallets().find(O=>O.chainNamespace===ChainNamespace.SOLANA&&O.isConnected)?.address,{data:h,isLoading:b}=Nn({walletAddress:v??""},{enabled:(n==="trade-history"||n==="positions")&&y==="authenticated"&&!!v}),x=(h?.trades??[]).filter(O=>O.marketTicker===e.ticker),m=useMemo(()=>p.map(O=>{let R=x.filter(Ee=>Ee.outputMint===O.mint&&Ee.usdPricePerContract!=null&&Ee.contracts!=null&&Ee.contracts>0),C=yp(R),V=O.position==="YES"?ko(O.market?.yesAsk):ko(O.market?.noAsk),Q=null,Le=null;return C!=null&&V!=null&&(Q=(V-C)*O.balance,Le=C>0?(V-C)/C*100:null),{...O,avgCost:C,currentPrice:V,pnl:Q,pnlPercent:Le}}),[p,x]),P=useCallback((O,R)=>{t?.(e,"yes",R==="ask"?"buy":"sell");},[e,t]),w=useCallback((O,R)=>{t?.(e,"no",R==="ask"?"buy":"sell");},[e,t]);return jsxs("div",{className:"flex flex-col gap-y-3",children:[jsxs(Tabs,{variant:"underlined",selectedKey:n,onSelectionChange:O=>s(O),classNames:{tabList:"gap-x-4",tab:"px-0"},children:[jsx(Tab,{title:r("predict.market.tradeYes")},"trade-yes"),jsx(Tab,{title:r("predict.market.tradeNo")},"trade-no"),jsx(Tab,{title:r("predict.market.graph")},"graph"),jsx(Tab,{title:r("predict.positions.title")},"positions"),jsx(Tab,{title:r("predict.tradeHistory.title")},"trade-history")]}),jsxs("div",{className:"min-h-[120px]",children:[n==="trade-yes"&&jsx(qr,{bids:i?.yesBids??[],asks:i?.yesAsks??[],isLoading:l,onPriceClick:P}),n==="trade-no"&&jsx(qr,{bids:i?.noBids??[],asks:i?.noAsks??[],isLoading:l,onPriceClick:w}),n==="graph"&&jsx(lo,{candlesticks:c,isLoading:u,chartRange:a,onRangeChange:o}),n==="positions"&&jsx(vo,{positions:m,isLoading:d}),n==="trade-history"&&jsx(xo,{trades:x,isLoading:b})]})]})}function yp(e){if(e.length===0)return null;let t=0,r=0;for(let n of e)t+=n.contracts,r+=n.usdPricePerContract*n.contracts;return t>0?r/t:null}function ko(e){if(e==null)return null;let t=Number(e);return Number.isFinite(t)?t:null}var Kr=4;function vp(e){let t=e.yesAsk?Math.round(parseFloat(e.yesAsk)*100):null,r=e.noAsk?Math.round(parseFloat(e.noAsk)*100):null;return {yesCents:t,noCents:r}}function To({markets:e,renderMarketDetail:t,onTradeAction:r,marketHoldings:n}){let{t:s}=useTranslation(),[a,o]=useState(false),[i,l]=useState(null);if(e.length===0)return null;let c=e.length>Kr,u=a?e:e.slice(0,Kr),p=d=>{l(y=>y===d?null:d);};return jsxs("div",{className:"flex flex-col divide-y divide-default-200",children:[u.map(d=>{let{yesCents:y,noCents:f}=vp(d),g=i===d.ticker;return jsxs("div",{className:"flex flex-col",children:[jsxs("div",{className:"flex items-center gap-x-3 px-2 py-3 transition-colors hover:bg-content2 lg:gap-x-4 cursor-pointer",onClick:()=>p(d.ticker),role:"button",tabIndex:0,onKeyDown:v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),p(d.ticker));},children:[jsxs("div",{className:"flex flex-col gap-y-1 min-w-0 flex-1",children:[jsx("span",{className:"text-sm font-medium truncate lg:text-base",children:d.yesSubTitle}),(()=>{let v=n?.get(d.ticker);if(!v)return null;let{yesShares:h,noShares:b}=v;return h<=0&&b<=0?null:jsxs("div",{className:"flex items-center gap-x-1.5",children:[h>0&&jsx(Chip,{size:"sm",variant:"flat",color:"primary",classNames:{base:"h-5",content:"text-[10px] font-medium px-1"},children:s("predict.market.sharesYes",{shares:h%1===0?h:h.toFixed(2)})}),b>0&&jsx(Chip,{size:"sm",variant:"flat",color:"secondary",classNames:{base:"h-5",content:"text-[10px] font-medium px-1"},children:s("predict.market.sharesNo",{shares:b%1===0?b:b.toFixed(2)})})]})})()]}),(()=>{let v=y!=null,h=f!=null;return v&&!h&&y<=1?jsx("span",{className:"text-lg font-bold shrink-0 text-center text-default-400 lg:text-xl",children:"< 1%"}):h&&!v&&f<=1?jsx("span",{className:"text-lg font-bold shrink-0 text-center text-default-400 lg:text-xl",children:"> 99%"}):!v&&!h?jsx("span",{className:"text-lg font-bold shrink-0 text-center text-default-400 lg:text-xl",children:"0%"}):jsx("span",{className:"text-lg font-bold shrink-0 text-center lg:text-xl",children:`${y}%`})})(),jsxs("div",{className:"flex items-center gap-x-2 flex-1 justify-end",children:[jsx(Button,{size:"sm",color:"primary",className:"w-20 bg-primary-100 text-primary",onPress:()=>r?.(d,"yes","buy"),children:y!=null?s("predict.market.action.yes",{price:y}):s("predict.market.yes")}),jsx(Button,{size:"sm",color:"secondary",className:"w-20 bg-secondary-100 text-secondary",onPress:()=>r?.(d,"no","buy"),children:f!=null?s("predict.market.action.no",{price:f}):s("predict.market.no")})]}),g?jsx(ChevronUpIcon,{className:"h-4 w-4 shrink-0 text-default-400"}):jsx(ChevronDownIcon,{className:"h-4 w-4 shrink-0 text-default-400"})]}),g&&t&&jsx("div",{className:"max-h-100 overflow-y-auto px-2 pb-3",children:t(d)})]},d.ticker)}),c&&jsx("button",{type:"button",onClick:()=>o(d=>!d),className:"flex items-center justify-center gap-x-1.5 px-2 py-2.5 text-sm text-default-500 transition-colors cursor-pointer hover:text-primary",children:a?jsxs(Fragment,{children:[jsx("span",{children:s("predict.event.rules.collapse")}),jsx(ChevronUpIcon,{className:"h-4 w-4"})]}):jsxs(Fragment,{children:[jsx("span",{children:s("predict.event.moreMarkets",{count:e.length-Kr})}),jsx(ChevronDownIcon,{className:"h-4 w-4"})]})})]})}var Pp=new Set(["closed","determined","finalized"]);function $t(e){let t=new Date(e*1e3),r=t.toLocaleString("default",{month:"short"}),n=t.getDate(),s=t.getFullYear(),a=t.getHours().toString().padStart(2,"0"),o=t.getMinutes().toString().padStart(2,"0");return `${r} ${n}, ${s} ${a}:${o}`}function Sp({market:e}){let t=Pp.has(e.status),r=useMemo(()=>{let s={label:"Market Open",value:$t(e.openTime),isActive:true},a={label:"Market Closes",value:t?$t(e.closeTime):"After the outcome occurs",isActive:t},o={label:"Projected Payout",value:"30 minutes after closing",isActive:e.status==="finalized"};return [s,a,o]},[e.openTime,e.closeTime,e.status,t]),n=useMemo(()=>t?null:e.canCloseEarly&&e.earlyCloseCondition?`${e.earlyCloseCondition} Otherwise, it closes by ${$t(e.expirationTime)}.`:`This market closes by ${$t(e.expirationTime)}.`,[t,e.canCloseEarly,e.earlyCloseCondition,e.expirationTime]);return jsxs("div",{className:"flex flex-col",children:[r.map((s,a)=>jsxs("div",{className:"flex items-stretch gap-x-3",children:[jsxs("div",{className:"flex flex-col items-center w-3",children:[jsx("div",{className:`h-3 w-3 shrink-0 rounded-full border-2 mt-0.5 ${s.isActive?"border-primary bg-primary":"border-default-300 bg-transparent"}`}),a<r.length-1&&jsx("div",{className:"w-px flex-1 bg-default-200"})]}),jsxs("div",{className:`flex flex-col ${a<r.length-1?"pb-4":""}`,children:[jsx("span",{className:"text-xs font-medium text-foreground lg:text-sm",children:s.label}),jsx("span",{className:"text-xs text-default-500 lg:text-sm",children:s.value})]})]},s.label)),n&&jsx("p",{className:"text-xs text-default-500 mt-3 lg:text-sm",children:n})]})}function No({markets:e,event:t,series:r}){let{t:n}=useTranslation(),[s,a]=useState(null),o=e.filter(l=>l.rulesPrimary);if(o.length===0)return null;let i=o.find(l=>l.ticker===s)??o[0];return i?.rulesPrimary?jsxs("div",{className:"flex flex-col gap-y-2",children:[jsx("span",{className:"text-sm font-medium lg:text-base",children:n("predict.event.rules")}),o.length>1&&jsx(Select,{size:"sm","aria-label":"Select market rules",className:"max-w-48",classNames:{trigger:"min-h-8 h-8",value:"text-xs"},selectedKeys:new Set([i.ticker]),onSelectionChange:l=>{if(l==="all")return;let c=Array.from(l);c.length>0&&a(c[0]);},children:o.map(l=>jsx(SelectItem,{textValue:l.yesSubTitle,children:jsx("span",{className:"text-xs truncate",children:l.yesSubTitle})},l.ticker))}),jsx("div",{className:"text-xs text-foreground lg:text-sm",children:i.rulesPrimary}),jsx("span",{className:"text-xs font-medium text-default-500 mt-2 lg:text-sm",children:"Timeline and payout"}),jsx(Sp,{market:i}),jsxs("div",{className:"flex flex-wrap items-center gap-x-3 text-xxs text-default-400 mt-2 lg:text-xs",children:[r?.ticker&&jsxs("span",{children:[jsx("span",{className:"text-default-500",children:"Series:"})," ",jsx("span",{className:"text-foreground",children:r.ticker})]}),t.ticker&&jsxs("span",{children:[jsx("span",{className:"text-default-500",children:"Event:"})," ",jsx("span",{className:"text-foreground",children:t.ticker})]}),jsxs("span",{children:[jsx("span",{className:"text-default-500",children:"Market:"})," ",jsx("span",{className:"text-foreground",children:i.ticker})]})]})]}):null}var Ip=[{value:S.ONE_DAY,label:"1D"},{value:S.ONE_WEEK,label:"1W"},{value:S.ONE_MONTH,label:"1M"},{value:S.ALL,label:"ALL"}];function Io({event:e,series:t,candlesticks:r,chartRange:n=S.ONE_DAY,periodInterval:s,isCandlesticksLoading:a,onRangeChange:o,selectedMarketTickers:i,onMarketSelectionChange:l,onTradeAction:c}){let{t:u}=useTranslation(),[p,d]=useState(qt()),[y,f]=useState(false),g=useRef(null);useEffect(()=>{let m=g.current;if(!m)return;let P=false,w=0,O=()=>{let{bottom:C}=m.getBoundingClientRect(),V=P?C<0:C<-20;V!==P&&(P=V,f(V));},R=()=>{cancelAnimationFrame(w),w=requestAnimationFrame(O);};return window.addEventListener("scroll",R,{passive:true,capture:true}),O(),()=>{cancelAnimationFrame(w),window.removeEventListener("scroll",R,{capture:true});}},[]);let v=useMemo(()=>[...e.markets||[]].sort((m,P)=>Number(P.yesAsk??0)-Number(m.yesAsk??0)),[e.markets]),{holdings:h}=ro(v),b=useMemo(()=>formatAmountUSDCompact((e.volume??0)/100),[e.volume]),x=useMemo(()=>{if(!e.strikeDate)return null;let m=new Date(e.strikeDate*1e3),P=m.toLocaleString("default",{month:"short"}),w=m.getDate(),O=m.getFullYear();return `${P} ${w}, ${O}`},[e.strikeDate]);return jsxs("div",{className:"w-full flex flex-col gap-4 lg:gap-y-6 px-1 pb-8 lg:px-4 lg:pb-12 lg:max-w-3xl",children:[jsx("div",{ref:g,className:"h-0 w-0"}),jsxs("div",{className:`sticky top-0 z-30 flex items-center bg-background/80 backdrop-blur-md transition-all duration-300 ${y?"gap-x-2 py-2 px-1 lg:px-4 -mx-1 lg:-mx-4 shadow-sm":"gap-x-2 lg:gap-x-4"}`,children:[jsx(Avatar,{src:e.imageUrl||void 0,name:e.title||"Event",radius:"lg",className:`flex-shrink-0 transition-all duration-300 ${y?"!h-8 !w-8 lg:!h-10 lg:!w-10":"!h-14 !w-14 lg:!h-18 lg:!w-18"}`}),jsxs("div",{className:"flex flex-col min-w-0",children:[!y&&(t?.category||t?.tags&&t.tags.length>0)&&jsxs("span",{className:"text-xs text-default-500 lg:text-sm truncate",children:[t.category,t.category&&t.tags?.length>0&&" \xB7 ",t.tags?.join(", ")]}),jsx("span",{className:`font-semibold truncate transition-all duration-300 ${y?"text-sm lg:text-base":"text-lg lg:text-xl"}`,children:e.title})]})]}),jsx("div",{className:"flex flex-col gap-y-4",children:jsxs("div",{className:"flex flex-col",children:[p&&p.markets.length>0&&jsx("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2 text-xs lg:text-sm",children:p.markets.map(m=>jsxs("div",{className:"flex items-center gap-x-2",children:[jsx("div",{className:"h-3 w-3 shrink-0 rounded-full",style:{backgroundColor:m.color}}),jsx("span",{className:"text-default-600",children:m.label})]},m.id))}),jsx(Wt,{candlesticks:r,chartRange:n,markets:v,isLoading:a,onDataChange:m=>d(m)}),jsxs("div",{className:"flex flex-wrap items-center justify-between gap-x-4 gap-y-2 mt-2",children:[jsxs("div",{className:"flex items-center gap-x-3 text-xs text-default-500 lg:text-sm",children:[jsxs("span",{children:[b," ",u("predict.event.volume")]}),x&&jsxs(Fragment,{children:[jsx("span",{className:"text-default-300",children:"\xB7"}),jsx("span",{children:u("predict.event.endDate",{date:x})})]})]}),jsx("div",{className:"flex items-center gap-x-1",children:Ip.map(m=>jsx("button",{type:"button",onClick:()=>o?.(m.value),className:`px-2 lg:px-3 py-1 text-xs rounded-md transition-colors cursor-pointer ${n===m.value?"bg-primary text-primary-foreground":"bg-default-100 text-default-600 hover:bg-default-200"}`,children:m.label},m.value))}),v.length>1&&jsx(Select,{size:"sm",selectionMode:"multiple",placeholder:"Markets","aria-label":"Select markets",className:"min-w-28 max-w-48",classNames:{trigger:"min-h-8 h-8",value:"text-xs"},selectedKeys:i?new Set(i):void 0,onSelectionChange:m=>{if(m==="all")return;let P=Array.from(m);P.length<=4&&l?.(P);},children:jsx(SelectSection,{title:`Pick up to ${4} markets`,classNames:{heading:"text-xs text-default-400 px-2 py-1"},children:v.map(m=>jsx(SelectItem,{textValue:m.yesSubTitle,children:jsx("span",{className:"text-xs truncate",children:m.yesSubTitle})},m.ticker))})})]})]})}),jsx(To,{markets:v,onTradeAction:c,marketHoldings:h,renderMarketDetail:m=>jsx(Kt,{market:m,onTradeAction:c})}),jsx(No,{markets:v,event:e,series:t})]})}function Gr({eventId:e,initialMarketTickers:t,initialChartRange:r=le,onTradeAction:n}){let[s,a]=useState(r),[o,i]=useState(t),{event:l,isEventLoading:c,eventError:u,series:p,isSeriesLoading:d,periodInterval:y,candlesticks:f,isCandlesticksLoading:g,candlestickErrors:v}=to({eventId:e,candlestickMarketTickers:o,chartRange:s}),h=useRef(!!t);useEffect(()=>{if(l?.markets&&!h.current){h.current=true;let m=[...l.markets].sort((P,w)=>Number(w.yesAsk??0)-Number(P.yesAsk??0)).slice(0,4).map(P=>P.ticker);i(m);}},[l?.markets]);let b=useMemo(()=>m=>{a(m);},[]),x=useMemo(()=>m=>{i(m);},[]);return c||d?jsx(ge,{}):u||!l?jsx("div",{className:"flex w-full items-center justify-center py-20 text-danger",children:u?.message||"Event not found"}):jsx(Io,{event:l,series:p,candlesticks:f,chartRange:s,periodInterval:y,isCandlesticksLoading:g,candlestickErrors:v,onRangeChange:b,selectedMarketTickers:o,onMarketSelectionChange:x,onTradeAction:n})}function fS({eventId:e,chain:t,...r}){let{t:n}=useTranslation(),{isMobile:s}=useScreen(),{isOpen:a,onOpen:o,onClose:i}=useDisclosure(),{data:l,isLoading:c}=Tt({id:e,withNestedMarkets:true}),u=useMemo(()=>[...l?.markets||[]].sort((v,h)=>Number(h.yesAsk??0)-Number(v.yesAsk??0)),[l?.markets]),[p,d]=useState(null),y=useCallback((v,h,b)=>{d(x=>({market:v,outcome:h,side:b,version:(x?.version??0)+1})),s&&o();},[s,o]),f=p?.market??u[0];if(c)return s?jsx(ge,{}):jsxs("div",{className:"flex w-full max-w-6xl mx-auto gap-x-4 lg:gap-x-6",children:[jsx("div",{className:"min-w-0 flex-1 max-w-3xl",children:jsx(ge,{})}),jsx("aside",{className:"hidden lg:block w-[340px] xl:w-[380px] shrink-0",children:jsx("div",{className:"sticky top-4",children:jsx(Ut,{})})})]});let g=p?`${p.market.ticker}-${p.version}`:f?.ticker??"default";return s?jsxs(Fragment,{children:[jsx("div",{className:"w-full pb-20",children:jsx(Gr,{eventId:e,onTradeAction:y,...r})}),f&&jsx("div",{className:"fixed inset-x-0 bottom-0 z-40 flex justify-center p-3 bg-gradient-to-t from-background via-background/90 to-transparent",children:jsx(Button,{color:"primary",size:"lg",className:"w-full max-w-md font-semibold",onPress:o,children:n("predict.trade.action")})}),jsx(Drawer,{isOpen:a,onClose:i,placement:"bottom",size:"lg",hideCloseButton:true,classNames:{base:"max-h-[85dvh] rounded-t-2xl",body:"p-0"},children:jsx(DrawerContent,{children:jsx(DrawerBody,{children:f&&jsx(je,{event:l,market:f,initialSide:p?.side,initialOutcome:p?.outcome,chain:t},g)})})})]}):jsxs("div",{className:"flex w-full max-w-6xl mx-auto gap-x-4 lg:gap-x-6",children:[jsx("div",{className:"min-w-0 flex-1 max-w-3xl",children:jsx(Gr,{eventId:e,onTradeAction:y,...r})}),f&&jsx("aside",{className:"hidden lg:block w-[340px] xl:w-[380px] shrink-0",children:jsx("div",{className:"sticky top-4 flex flex-col gap-y-4",children:jsx(je,{event:l,market:f,initialSide:p?.side,initialOutcome:p?.outcome,chain:t},g)})})]})}function Gt(e){if(!e)return 0;let t=new Date(e).getTime();return Number.isFinite(t)?Math.floor(t/1e3):0}function zt(e){return e==null?null:String(Math.round(e*100))}var zp={pending:"initialized",open:"active",closed:"determined",voided:"finalized"};function Xe(e){let t=e.outcomes[0],r=e.outcomes[1];return {ticker:e.slug,eventTicker:e.event_slug,marketType:"binary",title:e.question,subtitle:e.description??e.question,yesSubTitle:e.question,noSubTitle:r?.label??"No",openTime:Gt(e.start_at),closeTime:Gt(e.end_at),expirationTime:Gt(e.expires_at??e.end_at),status:zp[e.status]??"active",volume:e.volume??0,result:e.result??"",openInterest:e.open_interest??0,canCloseEarly:false,rulesPrimary:e.rules?.[0]??"",accounts:{},yesAsk:zt(t?.best_ask??t?.price),yesBid:zt(t?.best_bid),noAsk:zt(r?.best_ask??r?.price),noBid:zt(r?.best_bid),rulesSecondary:e.rules?.slice(1).join(`
20
+ `)??null}}function Bo(e){return {ticker:e.slug,seriesTicker:"",title:e.title,subtitle:e.subtitle??"",imageUrl:e.image_url,liquidity:e.liquidity,openInterest:e.open_interest,volume:e.volume!=null?Math.round(e.volume*100):null,volume24h:e.volume_24h!=null?Math.round(e.volume_24h*100):null,strikeDate:Gt(e.end_at),settlementSources:e.settlement_sources?.map(t=>({name:t.name??"",url:t.url})),markets:e.markets?.map(Xe)}}function _o(e){return e.outcomes[0]?.best_ask??e.outcomes[0]?.price??0}function Yp(e){if(!e)return 0;let t=new Date(e).getTime();return Number.isFinite(t)?Math.floor(t/1e3):0}var Qo=e=>{let{candlestickMarketSlugs:t,chartRange:r=le,source:n}=e,s=He[r],a=Ke[r],o=useMemo(()=>Math.floor(Date.now()/1e3),[r]),i=k(),{data:l,isLoading:c,error:u}=wt({slug:e.eventSlug,source:n}),p=useMemo(()=>{if(a!=null)return o-a;let h=l?.markets;return h?.length?Math.min(...h.map(b=>Yp(b.start_at))):o},[o,a,l?.markets]),d=useMemo(()=>l?.markets?(t&&t.length>0?t.slice(0,4).map(b=>l.markets.find(x=>x.slug===b)).filter(b=>b!==void 0):[...l.markets].sort((b,x)=>_o(x)-_o(b)).slice(0,4)).map(b=>b.slug):[],[t,l?.markets]),y=useQueries({queries:d.map(h=>({queryKey:rt({ticker:h,startTs:p,endTs:o,periodInterval:s}),queryFn:()=>nt(i,{ticker:h,startTs:p,endTs:o,periodInterval:s}),enabled:d.length>0}))}),f=y.some(h=>h.isLoading),g=useMemo(()=>{let h=new Map;return d.forEach((b,x)=>{let m=y[x]?.error;m&&h.set(b,m);}),h},[d,y]),v=useMemo(()=>{let h=new Map;return d.forEach((b,x)=>{let m=y[x]?.data;m&&h.set(b,m);}),h},[d,y]);return {event:l,isEventLoading:c,eventError:u,periodInterval:s,candlesticks:v,isCandlesticksLoading:f,candlestickErrors:g}};function Xr(e){return e.outcomes[0]?.best_ask??e.outcomes[0]?.price??0}function tm(e){let t=Math.round(e*100);return t<=1&&e>0?"< 1%":t>=99&&e<1?"> 99%":`${t}%`}function rm(e){if(!e)return null;try{let t=new Date(e);return isNaN(t.getTime())?null:t.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}catch{return null}}function qo(e){switch(e){case "polymarket":return "Polymarket";case "dflow":return "Kalshi";default:return e}}var nm=[{value:S.ONE_DAY,label:"1D"},{value:S.ONE_WEEK,label:"1W"},{value:S.ONE_MONTH,label:"1M"},{value:S.ALL,label:"ALL"}];function Ho({event:e,candlesticks:t,chartRange:r=S.ONE_DAY,isCandlesticksLoading:n,onRangeChange:s,selectedMarketSlugs:a,onMarketSelectionChange:o,onTradeAction:i}){let{t:l}=useTranslation(),[c,u]=useState(qt()),[p,d]=useState(false),y=useRef(null);useEffect(()=>{let b=y.current;if(!b)return;let x=false,m=0,P=()=>{let{bottom:O}=b.getBoundingClientRect(),R=x?O<0:O<-20;R!==x&&(x=R,d(R));},w=()=>{cancelAnimationFrame(m),m=requestAnimationFrame(P);};return window.addEventListener("scroll",w,{passive:true,capture:true}),P(),()=>{cancelAnimationFrame(m),window.removeEventListener("scroll",w,{capture:true});}},[]);let f=useMemo(()=>[...e.markets||[]].sort((b,x)=>Xr(x)-Xr(b)),[e.markets]),g=useMemo(()=>formatAmountUSDCompact(e.volume??0),[e.volume]),v=useMemo(()=>rm(e.end_at),[e.end_at]),h=useMemo(()=>f.map(Xe),[f]);return jsxs("div",{className:"w-full flex flex-col gap-4 lg:gap-y-6 px-1 pb-8 lg:px-4 lg:pb-12 lg:max-w-3xl",children:[jsx("div",{ref:y,className:"h-0 w-0"}),jsxs("div",{className:`sticky top-0 z-30 flex items-center bg-background/80 backdrop-blur-md transition-all duration-300 ${p?"gap-x-2 py-2 px-1 lg:px-4 -mx-1 lg:-mx-4 shadow-sm":"gap-x-2 lg:gap-x-4"}`,children:[jsx(Avatar,{src:e.image_url||void 0,name:e.title||"Event",radius:"lg",className:`flex-shrink-0 transition-all duration-300 ${p?"!h-8 !w-8 lg:!h-10 lg:!w-10":"!h-14 !w-14 lg:!h-18 lg:!w-18"}`}),jsxs("div",{className:"flex flex-col min-w-0 flex-1",children:[!p&&jsxs("div",{className:"flex items-center gap-1.5",children:[jsx(am,{source:e.source}),e.tags?.slice(0,3).map(b=>jsx("span",{className:"text-xs text-default-500 truncate",children:b.label},b.slug))]}),jsx("span",{className:`font-semibold truncate transition-all duration-300 ${p?"text-sm lg:text-base":"text-lg lg:text-xl"}`,children:e.title})]})]}),jsx("div",{className:"flex flex-col gap-y-4",children:jsxs("div",{className:"flex flex-col",children:[c&&c.markets.length>0&&jsx("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-2 text-xs lg:text-sm",children:c.markets.map(b=>jsxs("div",{className:"flex items-center gap-x-2",children:[jsx("div",{className:"h-3 w-3 shrink-0 rounded-full",style:{backgroundColor:b.color}}),jsx("span",{className:"text-default-600",children:b.label})]},b.id))}),jsx(Wt,{candlesticks:t,chartRange:r,markets:h,isLoading:n,onDataChange:b=>u(b)}),jsxs("div",{className:"flex flex-wrap items-center justify-between gap-x-4 gap-y-2 mt-2",children:[jsxs("div",{className:"flex items-center gap-x-3 text-xs text-default-500 lg:text-sm",children:[jsxs("span",{children:[g," ",l("predict.event.volume")]}),v&&jsxs(Fragment,{children:[jsx("span",{className:"text-default-300",children:"\xB7"}),jsx("span",{children:l("predict.event.endDate",{date:v})})]})]}),jsx("div",{className:"flex items-center gap-x-1",children:nm.map(b=>jsx("button",{type:"button",onClick:()=>s?.(b.value),className:`px-2 lg:px-3 py-1 text-xs rounded-md transition-colors cursor-pointer ${r===b.value?"bg-primary text-primary-foreground":"bg-default-100 text-default-600 hover:bg-default-200"}`,children:b.label},b.value))}),f.length>1&&jsx(Select,{size:"sm",selectionMode:"multiple",placeholder:"Markets","aria-label":"Select markets",className:"min-w-28 max-w-48",classNames:{trigger:"min-h-8 h-8",value:"text-xs"},selectedKeys:a?new Set(a):void 0,onSelectionChange:b=>{if(b==="all")return;let x=Array.from(b);x.length<=4&&o?.(x);},children:jsx(SelectSection,{title:`Pick up to ${4} markets`,classNames:{heading:"text-xs text-default-400 px-2 py-1"},children:f.map(b=>jsx(SelectItem,{textValue:b.question,children:jsx("span",{className:"text-xs truncate",children:b.question})},b.slug))})})]})]})}),jsx(sm,{markets:f,onTradeAction:i}),jsx(om,{markets:f,event:e})]})}var jr=4;function sm({markets:e,onTradeAction:t}){let{t:r}=useTranslation(),[n,s]=useState(false),[a,o]=useState(null);if(e.length===0)return null;let i=e.length>jr,l=n?e:e.slice(0,jr),c=u=>{o(p=>p===u?null:u);};return jsxs("div",{className:"flex flex-col divide-y divide-default-200",children:[l.map(u=>{let p=Xr(u),d=u.outcomes[1]?.best_ask??u.outcomes[1]?.price,y=Math.round(p*100),f=d!=null?Math.round(d*100):null,g=a===u.slug;return jsxs("div",{className:"flex flex-col",children:[jsxs("div",{className:"flex items-center gap-x-3 px-2 py-3 transition-colors hover:bg-content2 lg:gap-x-4 cursor-pointer",onClick:()=>c(u.slug),role:"button",tabIndex:0,onKeyDown:v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),c(u.slug));},children:[jsx("div",{className:"flex flex-col gap-y-1 min-w-0 flex-1",children:jsx("span",{className:"text-sm font-medium truncate lg:text-base",children:u.question})}),jsx("span",{className:"text-lg font-bold shrink-0 text-center lg:text-xl",children:tm(p)}),jsxs("div",{className:"flex items-center gap-x-2 flex-1 justify-end",children:[jsx(Button,{size:"sm",color:"primary",className:"w-20 bg-primary-100 text-primary",onPress:()=>t?.(u,"yes","buy"),children:r("predict.market.action.yes",{price:y})}),jsx(Button,{size:"sm",color:"secondary",className:"w-20 bg-secondary-100 text-secondary",onPress:()=>t?.(u,"no","buy"),children:f!=null?r("predict.market.action.no",{price:f}):r("predict.market.no")})]})]}),g&&jsx("div",{className:"max-h-100 overflow-y-auto px-2 pb-3",children:jsx(Kt,{market:Xe(u),onTradeAction:t?(v,h,b)=>t(u,h,b):void 0})})]},u.slug)}),i&&jsx("button",{type:"button",onClick:()=>s(u=>!u),className:"flex items-center justify-center gap-x-1.5 px-2 py-2.5 text-sm text-default-500 transition-colors cursor-pointer hover:text-primary",children:n?r("predict.event.rules.collapse"):r("predict.event.moreMarkets",{count:e.length-jr})})]})}function Uo(e){if(!e)return "\u2014";let t=new Date(e);if(isNaN(t.getTime()))return "\u2014";let r=t.toLocaleString("default",{month:"short"}),n=t.getDate(),s=t.getFullYear(),a=t.getHours().toString().padStart(2,"0"),o=t.getMinutes().toString().padStart(2,"0");return `${r} ${n}, ${s} ${a}:${o}`}function om({markets:e,event:t}){let{t:r}=useTranslation(),[n,s]=useState(null),a=e.filter(i=>i.rules&&i.rules.length>0);if(a.length===0)return null;let o=a.find(i=>i.slug===n)??a[0];return o?.rules?.length?jsxs("div",{className:"flex flex-col gap-y-2",children:[jsx("span",{className:"text-sm font-medium lg:text-base",children:r("predict.event.rules")}),a.length>1&&jsx(Select,{size:"sm","aria-label":"Select market rules",className:"max-w-48",classNames:{trigger:"min-h-8 h-8",value:"text-xs"},selectedKeys:new Set([o.slug]),onSelectionChange:i=>{if(i==="all")return;let l=Array.from(i);l.length>0&&s(l[0]);},children:a.map(i=>jsx(SelectItem,{textValue:i.question,children:jsx("span",{className:"text-xs truncate",children:i.question})},i.slug))}),jsx("div",{className:"text-xs text-foreground lg:text-sm space-y-1",children:o.rules.map((i,l)=>jsx("p",{children:i},l))}),jsx("span",{className:"text-xs font-medium text-default-500 mt-2 lg:text-sm",children:"Timeline"}),jsx("div",{className:"flex flex-col",children:[{label:"Market Open",value:Uo(o.start_at),isActive:true},{label:"Market Closes",value:Uo(o.end_at),isActive:o.status==="closed"||o.status==="voided"}].map((i,l,c)=>jsxs("div",{className:"flex items-stretch gap-x-3",children:[jsxs("div",{className:"flex flex-col items-center w-3",children:[jsx("div",{className:`h-3 w-3 shrink-0 rounded-full border-2 mt-0.5 ${i.isActive?"border-primary bg-primary":"border-default-300 bg-transparent"}`}),l<c.length-1&&jsx("div",{className:"w-px flex-1 bg-default-200"})]}),jsxs("div",{className:`flex flex-col ${l<c.length-1?"pb-4":""}`,children:[jsx("span",{className:"text-xs font-medium text-foreground lg:text-sm",children:i.label}),jsx("span",{className:"text-xs text-default-500 lg:text-sm",children:i.value})]})]},i.label))}),jsxs("div",{className:"flex flex-wrap items-center gap-x-3 text-xxs text-default-400 mt-2 lg:text-xs",children:[jsxs("span",{children:[jsx("span",{className:"text-default-500",children:"Event:"})," ",jsx("span",{className:"text-foreground",children:t.slug})]}),jsxs("span",{children:[jsx("span",{className:"text-default-500",children:"Market:"})," ",jsx("span",{className:"text-foreground",children:o.slug})]}),jsxs("span",{children:[jsx("span",{className:"text-default-500",children:"Source:"})," ",jsx("span",{className:"text-foreground",children:qo(o.source)})]})]})]}):null}function am({source:e}){return jsxs("span",{className:cn("inline-flex items-center gap-x-1 rounded px-1.5 py-0.5","text-[10px] font-medium leading-none",e==="polymarket"?"bg-blue-500/15 text-blue-400":"bg-primary-500/15 text-primary"),children:[jsx("span",{className:cn("h-1.5 w-1.5 rounded-sm",e==="polymarket"?"bg-blue-400":"bg-primary")}),qo(e)]})}function zo(e){return e.outcomes[0]?.best_ask??e.outcomes[0]?.price??0}function en({eventSlug:e,source:t,initialMarketSlugs:r,initialChartRange:n=le,onTradeAction:s}){let[a,o]=useState(n),[i,l]=useState(r),{event:c,isEventLoading:u,eventError:p,periodInterval:d,candlesticks:y,isCandlesticksLoading:f,candlestickErrors:g}=Qo({eventSlug:e,source:t,candlestickMarketSlugs:i,chartRange:a}),v=useRef(!!r);useEffect(()=>{if(c?.markets&&!v.current){v.current=true;let x=[...c.markets].sort((m,P)=>zo(P)-zo(m)).slice(0,4).map(m=>m.slug);l(x);}},[c?.markets]);let h=useMemo(()=>x=>o(x),[]),b=useMemo(()=>x=>l(x),[]);return u?jsx(ge,{}):p||!c?jsx("div",{className:"flex w-full items-center justify-center py-20 text-danger",children:p?.message||"Event not found"}):jsx(Ho,{event:c,candlesticks:y,chartRange:a,periodInterval:d,isCandlesticksLoading:f,candlestickErrors:g,onRangeChange:h,selectedMarketSlugs:i,onMarketSelectionChange:b,onTradeAction:s})}function Go(e){return e.outcomes[0]?.best_ask??e.outcomes[0]?.price??0}function jS({eventSlug:e,source:t,chain:r,...n}){let{t:s}=useTranslation(),{isMobile:a}=useScreen(),{isOpen:o,onOpen:i,onClose:l}=useDisclosure(),{data:c,isLoading:u}=wt({slug:e,source:t}),p=useMemo(()=>[...c?.markets||[]].sort((x,m)=>Go(m)-Go(x)),[c?.markets]),[d,y]=useState(null),f=useCallback((x,m,P)=>{y(w=>({market:x,outcome:m,side:P,version:(w?.version??0)+1})),a&&i();},[a,i]),g=d?.market??p[0],v=useMemo(()=>c?Bo(c):void 0,[c]),h=useMemo(()=>g?Xe(g):void 0,[g]);if(u)return a?jsx(ge,{}):jsxs("div",{className:"flex w-full max-w-6xl mx-auto gap-x-4 lg:gap-x-6",children:[jsx("div",{className:"min-w-0 flex-1 max-w-3xl",children:jsx(ge,{})}),jsx("aside",{className:"hidden lg:block w-[340px] xl:w-[380px] shrink-0",children:jsx("div",{className:"sticky top-4",children:jsx(Ut,{})})})]});let b=d?`${d.market.slug}-${d.version}`:g?.slug??"default";return a?jsxs(Fragment,{children:[jsx("div",{className:"w-full pb-20",children:jsx(en,{eventSlug:e,source:t,onTradeAction:f,...n})}),h&&jsx("div",{className:"fixed inset-x-0 bottom-0 z-40 flex justify-center p-3 bg-gradient-to-t from-background via-background/90 to-transparent",children:jsx(Button,{color:"primary",size:"lg",className:"w-full max-w-md font-semibold",onPress:i,children:s("predict.trade.action")})}),jsx(Drawer,{isOpen:o,onClose:l,placement:"bottom",size:"lg",hideCloseButton:true,classNames:{base:"max-h-[85dvh] rounded-t-2xl",body:"p-0"},children:jsx(DrawerContent,{children:jsx(DrawerBody,{children:h&&jsx(je,{event:v,market:h,initialSide:d?.side,initialOutcome:d?.outcome,chain:r},b)})})})]}):jsxs("div",{className:"flex w-full max-w-6xl mx-auto gap-x-4 lg:gap-x-6",children:[jsx("div",{className:"min-w-0 flex-1 max-w-3xl",children:jsx(en,{eventSlug:e,source:t,onTradeAction:f,...n})}),h&&jsx("aside",{className:"hidden lg:block w-[340px] xl:w-[380px] shrink-0",children:jsx("div",{className:"sticky top-4 flex flex-col gap-y-4",children:jsx(je,{event:v,market:h,initialSide:d?.side,initialOutcome:d?.outcome,chain:r},b)})})]})}var jt=4,Yo=["#22d3ee","#a3e635","#f97316","#f472b6","#a78bfa"];function jo(e,t){let r=new Date(e);return t===S.ONE_DAY?r.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:false}):r.toLocaleDateString("en-US",{month:"short",day:"numeric"})}function Xo(e){return `${(e*100).toFixed(2)}%`}var Rm=[{range:S.ONE_DAY,label:"1D"},{range:S.ONE_WEEK,label:"1W"},{range:S.ONE_MONTH,label:"1M"},{range:S.ALL,label:"ALL"}];function Nm({value:e,onChange:t}){return jsx("div",{style:{display:"flex",alignItems:"center",gap:2},children:Rm.map(({range:r,label:n})=>{let s=r===e;return jsx("button",{onClick:()=>t(r),style:{padding:"2px 8px",border:"none",background:"transparent",color:s?"#f9fafb":"#6b7280",fontWeight:s?700:400,fontSize:12,cursor:"pointer",borderRadius:4,letterSpacing:"0.02em",transition:"color 0.15s",userSelect:"none"},children:n},r)})})}function Om({dots:e}){return jsx(Fragment,{children:e.map(({cx:t,cy:r,color:n},s)=>jsxs("g",{children:[jsxs("circle",{cx:t,cy:r,r:6,fill:n,opacity:.3,children:[jsx("animate",{attributeName:"r",values:"4;9;4",dur:"2s",repeatCount:"indefinite"}),jsx("animate",{attributeName:"opacity",values:"0.4;0.05;0.4",dur:"2s",repeatCount:"indefinite"})]}),jsx("circle",{cx:t,cy:r,r:3.5,fill:n})]},s))})}function Im(){let e=useRef(null),t=useRef(null),r=useCallback(s=>{let a=e.current,o=t.current;if(!a||!o)return;let i=a.getBoundingClientRect(),l=(s.clientX-i.left)/i.width*100;o.style.background=`linear-gradient(to right, transparent ${l}%, rgba(0,0,0,0.38) ${l}%)`,o.style.opacity="1";},[]),n=useCallback(()=>{t.current&&(t.current.style.opacity="0");},[]);return {wrapperRef:e,overlayRef:t,onMouseMove:r,onMouseLeave:n}}function Lm({active:e,payload:t,label:r,labelMap:n}){if(!e||!t?.length)return null;let s=[...t].filter(a=>a.value!=null).sort((a,o)=>(o.value??0)-(a.value??0));return jsxs("div",{style:{background:"rgba(10,10,10,0.92)",border:"1px solid rgba(255,255,255,0.1)",borderRadius:8,padding:"8px 12px",minWidth:180,backdropFilter:"blur(8px)",fontSize:12},children:[jsx("div",{style:{color:"#9ca3af",marginBottom:6,fontWeight:500},children:typeof r=="number"?jo(r):r}),s.map(a=>jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:3},children:[jsx("span",{style:{display:"inline-block",width:3,height:14,borderRadius:2,background:a.stroke??a.color,flexShrink:0}}),jsx("span",{style:{color:"#e5e7eb",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:120},children:n.get(a.dataKey)??a.dataKey}),jsx("span",{style:{color:"#f9fafb",fontWeight:700,fontVariantNumeric:"tabular-nums"},children:a.value!=null?Xo(a.value):"-"})]},a.dataKey))]})}function Vm({markets:e,selectedSlugs:t,colorMap:r,onToggle:n}){let[s,a]=useState(false),o=useRef(null);useEffect(()=>{if(!s)return;function c(u){o.current&&!o.current.contains(u.target)&&a(false);}return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[s]);let i=t.length>=jt,l=jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:0},children:[jsx("div",{style:{display:"flex",gap:3,flexShrink:0},children:t.map(c=>jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:r.get(c)??"#6b7280",display:"inline-block"}},c))}),jsx("span",{style:{color:"#e5e7eb",fontSize:12,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.length===1?e.find(c=>c.slug===t[0])?.question??"1 market":`${t.length} / ${e.length} markets`})]});return jsxs("div",{ref:o,style:{position:"relative",display:"inline-block",maxWidth:320},children:[jsxs("button",{onClick:()=>a(c=>!c),style:{display:"inline-flex",alignItems:"center",gap:6,padding:"5px 10px",borderRadius:8,border:"1px solid rgba(255,255,255,0.12)",background:"rgba(255,255,255,0.05)",cursor:"pointer",minWidth:160,maxWidth:320,userSelect:"none"},children:[l,jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",style:{flexShrink:0,transform:s?"rotate(180deg)":"rotate(0deg)",transition:"transform 0.15s",color:"#6b7280"},children:jsx("path",{d:"M2 4l4 4 4-4",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})]}),s&&jsxs("div",{style:{position:"absolute",top:"calc(100% + 4px)",left:0,zIndex:50,background:"#111827",border:"1px solid rgba(255,255,255,0.1)",borderRadius:10,boxShadow:"0 8px 24px rgba(0,0,0,0.5)",minWidth:260,maxWidth:360,maxHeight:320,overflowY:"auto",padding:"6px 0"},children:[jsxs("div",{style:{padding:"4px 12px 8px",fontSize:11,color:"#6b7280",borderBottom:"1px solid rgba(255,255,255,0.06)",marginBottom:4},children:["Select up to ",jt," markets"]}),e.map(c=>{let u=t.includes(c.slug),p=!u&&i,d=u&&t.length===1,y=r.get(c.slug)??"#6b7280",f=c.outcomes.find(v=>v.label.toLowerCase()==="yes")??c.outcomes[0],g=f?.price!=null?`${Math.round(f.price*100)}%`:null;return jsxs("button",{onClick:()=>{d||p||n(c.slug);},style:{display:"flex",alignItems:"center",gap:10,width:"100%",padding:"7px 12px",border:"none",background:u?"rgba(255,255,255,0.05)":"transparent",cursor:p||d?"not-allowed":"pointer",opacity:p?.35:1,textAlign:"left",transition:"background 0.1s"},onMouseEnter:v=>{!p&&!d&&(v.currentTarget.style.background="rgba(255,255,255,0.07)");},onMouseLeave:v=>{v.currentTarget.style.background=u?"rgba(255,255,255,0.05)":"transparent";},children:[jsx("span",{style:{width:16,height:16,borderRadius:4,border:u?`2px solid ${y}`:"2px solid rgba(255,255,255,0.2)",background:u?`${y}30`:"transparent",flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center"},children:u&&jsx("svg",{width:"9",height:"7",viewBox:"0 0 9 7",fill:"none",children:jsx("path",{d:"M1 3.5L3.5 6L8 1",stroke:y,strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})})}),jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:y,flexShrink:0}}),jsx("span",{style:{color:u?"#f9fafb":"#9ca3af",fontSize:12,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:c.question}),g&&jsx("span",{style:{color:y,fontWeight:700,fontSize:12,flexShrink:0},children:g})]},c.slug)})]})]})}function Bm({series:e,colorMap:t,currentValues:r}){return jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px 16px",padding:"0 2px"},children:e.map(n=>{let s=t.get(n.marketSlug)??"#6b7280",a=r.get(n.marketSlug);return jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:6,fontSize:12},children:[jsx("span",{style:{width:10,height:10,borderRadius:"50%",background:s,flexShrink:0}}),jsx("span",{style:{color:"#9ca3af"},children:n.label}),a!=null&&jsx("span",{style:{color:"#f9fafb",fontWeight:700},children:Xo(a)})]},n.marketSlug)})})}function _m(e){if(e.length===0)return [];let t=new Set;e.forEach(a=>a.data.forEach(o=>t.add(o.timestamp)));let r=Array.from(t).sort((a,o)=>a-o),n=e.map(a=>{let o=new Map;return a.data.forEach(i=>o.set(i.timestamp,i.price)),{slug:a.marketSlug,map:o}}),s=new Map;return r.map(a=>{let o={timestamp:a};return n.forEach(({slug:i,map:l})=>{let c=l.get(a);if(c!==void 0)s.set(i,c),o[i]=c;else {let u=s.get(i);u!==void 0&&(o[i]=u);}}),o})}function nC({event:e,isLoading:t}){let r=useMemo(()=>e.markets??[],[e.markets]),[n,s]=useState(()=>r.slice(0,jt).map(x=>x.slug)),[a,o]=useState(le),i=useMemo(()=>{let x=new Map;return r.forEach((m,P)=>{x.set(m.slug,Yo[P%Yo.length]);}),x},[r]),l=useMemo(()=>r.filter(x=>n.includes(x.slug)),[r,n]),{series:c}=Cn(l,a),u=useMemo(()=>_m(c),[c]),p=useMemo(()=>{if(u.length===0)return [0,1];let x=1/0,m=-1/0;if(n.forEach(w=>{u.forEach(O=>{let R=O[w];R!=null&&(R<x&&(x=R),R>m&&(m=R));});}),!isFinite(x))return [0,1];let P=Math.max((m-x)*.15,.05);return [Math.max(0,x-P),Math.min(1,m+P)]},[u,n]),d=useMemo(()=>{let x=new Map;return c.forEach(m=>{m.data.length>0&&x.set(m.marketSlug,m.data[m.data.length-1].price);}),x},[c]),y=useMemo(()=>{let x=new Map;return c.forEach(m=>x.set(m.marketSlug,m.label)),x},[c]),{wrapperRef:f,overlayRef:g,onMouseMove:v,onMouseLeave:h}=Im(),b=useCallback(x=>{s(m=>m.includes(x)?m.length<=1?m:m.filter(P=>P!==x):m.length>=jt?m:[...m,x]);},[]);return t?jsx("div",{style:{height:320,display:"flex",alignItems:"center",justifyContent:"center"},children:jsx("div",{style:{width:28,height:28,borderRadius:"50%",border:"2.5px solid #22d3ee",borderTopColor:"transparent",animation:"spin 0.7s linear infinite"}})}):u.length===0?jsx("div",{style:{height:320,display:"flex",alignItems:"center",justifyContent:"center",color:"#6b7280",fontSize:13},children:"No price history data"}):jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[r.length>1&&jsx(Vm,{markets:r,selectedSlugs:n,colorMap:i,onToggle:b}),jsx(Bm,{series:c,colorMap:i,currentValues:d}),jsxs("div",{style:{display:"flex",flexDirection:"column",gap:0},children:[jsxs("div",{ref:f,style:{height:300,width:"100%",userSelect:"none",position:"relative"},onMouseMove:v,onMouseLeave:h,children:[jsx("div",{ref:g,style:{position:"absolute",inset:0,opacity:0,pointerEvents:"none",zIndex:1}}),jsx(ResponsiveContainer,{width:"100%",height:"100%",children:jsxs(LineChart,{data:u,margin:{top:8,right:16,left:0,bottom:0},children:[jsx(CartesianGrid,{horizontal:true,vertical:false,strokeDasharray:"3 3",stroke:"#374151",opacity:.5}),jsx(XAxis,{dataKey:"timestamp",type:"number",scale:"time",domain:["dataMin","dataMax"],tickFormatter:x=>jo(x,a),axisLine:false,tickLine:false,tick:{fill:"#6b7280",fontSize:11},minTickGap:70}),jsx(YAxis,{domain:p,tickFormatter:x=>`${Math.round(x*100)}%`,axisLine:false,tickLine:false,tick:{fill:"#6b7280",fontSize:11},width:40,tickCount:6}),jsx(Tooltip,{content:x=>jsx(Lm,{...x,labelMap:y}),cursor:{stroke:"#4b5563",strokeWidth:1,strokeDasharray:"4 4"},isAnimationActive:false}),c.map(x=>{let m=i.get(x.marketSlug)??"#6b7280";return jsx(Line,{type:"stepAfter",dataKey:x.marketSlug,stroke:m,strokeWidth:2,dot:false,activeDot:{r:4.5,strokeWidth:2,stroke:"rgba(10,10,10,0.8)",fill:m},connectNulls:true,isAnimationActive:false},x.marketSlug)}),jsx(Customized,{component:x=>{let m=x.xAxisMap?Object.values(x.xAxisMap)[0]?.scale:null,P=x.yAxisMap?Object.values(x.yAxisMap)[0]?.scale:null,w=[];if(m&&P&&u.length>0){let O=u[u.length-1];c.forEach(R=>{let C=O[R.marketSlug];if(C==null)return;let V=m(O.timestamp),Q=P(C);V==null||Q==null||w.push({cx:V,cy:Q,color:i.get(R.marketSlug)??"#6b7280"});});}return jsx(Om,{dots:w})}})]})})]}),jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",paddingRight:4,marginTop:2},children:jsx(Nm,{value:a,onChange:o})})]})]})}function Zo(e,t){if(!e)return [];let r=e.slice(0,t),n=0,s=r.map(o=>(n+=o.quantity,{...o,cumulative:n,depth:0})),a=s[s.length-1]?.cumulative??1;for(let o of s)o.depth=o.cumulative/a;return s}function Jo({marketTicker:e,maxLevels:t=10,refetchInterval:r=5e3,outcome:n="yes"}){let{data:s,isLoading:a,isFetching:o}=ze(e,{refetchInterval:r||void 0}),i=useMemo(()=>n==="yes"?s?.yesBids:s?.noBids,[s,n]),l=useMemo(()=>n==="yes"?s?.yesAsks:s?.noAsks,[s,n]),c=useMemo(()=>Zo(i,t),[i,t]),u=useMemo(()=>Zo(l,t),[l,t]),p=useMemo(()=>c.length===0||u.length===0?null:u[0].price-c[0].price,[c,u]),d=useMemo(()=>c.length===0||u.length===0?null:(c[0].price+u[0].price)/2,[c,u]),y=useMemo(()=>p===null||d===null||d===0?null:Math.round(p/d*1e4)/100,[p,d]);return {bids:c,asks:u,spread:p,spreadPercent:y,midpoint:d,isLoading:a,isFetching:o}}function ea({row:e,side:t,onClick:r}){let n=t==="bid",s=n?"bg-primary/10":"bg-danger/10",a=n?"text-primary":"text-danger";return jsxs("button",{type:"button",className:"relative flex w-full items-center justify-between px-3 py-1 text-xs hover:bg-default-100 cursor-pointer",onClick:()=>r?.(e.price),children:[jsx("div",{className:`absolute inset-y-0 ${n?"right-0":"left-0"} ${s}`,style:{width:`${e.depth*100}%`}}),jsxs("span",{className:`relative z-10 font-medium ${a}`,children:[e.price,"\xA2"]}),jsx("span",{className:"relative z-10 text-default-600",children:e.quantity}),jsx("span",{className:"relative z-10 text-default-400",children:e.cumulative})]})}function ta(){return jsx("div",{className:"flex flex-col gap-y-1 py-2",children:Array.from({length:5}).map((e,t)=>jsx("div",{className:"mx-3 h-4 animate-pulse rounded bg-default-100"},t))})}function ra({bids:e,asks:t,spread:r,spreadPercent:n,isLoading:s,onPriceClick:a}){let{t:o}=useTranslation();if(s)return jsxs("div",{className:"flex w-full flex-col rounded-xl border border-default-200 bg-content1",children:[jsx("div",{className:"border-b border-default-200 px-3 py-2 text-sm font-medium",children:o("predict.orderBook.title")}),jsx(ta,{}),jsx(ta,{})]});let i=e.length===0&&t.length===0;return jsxs("div",{className:"flex w-full flex-col rounded-xl border border-default-200 bg-content1",children:[jsx("div",{className:"flex items-center justify-between border-b border-default-200 px-3 py-2",children:jsx("span",{className:"text-sm font-medium",children:o("predict.orderBook.title")})}),i?jsx("div",{className:"flex items-center justify-center py-8 text-xs text-default-400",children:o("predict.orderBook.empty")}):jsxs(Fragment,{children:[jsxs("div",{className:"flex items-center justify-between px-3 py-1 text-xxs text-default-400",children:[jsx("span",{children:o("predict.orderBook.price")}),jsx("span",{children:o("predict.orderBook.qty")}),jsx("span",{children:o("predict.orderBook.total")})]}),jsx("div",{className:"flex flex-col-reverse",children:t.map(l=>jsx(ea,{row:l,side:"ask",onClick:a},l.price))}),r!==null&&jsxs("div",{className:"flex items-center justify-center gap-x-2 border-y border-default-200 py-1.5 text-xs text-default-500",children:[jsxs("span",{children:[o("predict.orderBook.spread"),": ",r,"\xA2"]}),n!==null&&jsxs("span",{className:"text-default-400",children:["(",n,"%)"]})]}),jsx("div",{className:"flex flex-col",children:e.map(l=>jsx(ea,{row:l,side:"bid",onClick:a},l.price))})]})]})}function NC({marketTicker:e,maxLevels:t,refetchInterval:r,onPriceClick:n,outcome:s}){let{bids:a,asks:o,spread:i,spreadPercent:l,isLoading:c}=Jo({marketTicker:e,maxLevels:t,refetchInterval:r,outcome:s});return jsx(ra,{bids:a,asks:o,spread:i,spreadPercent:l,isLoading:c,onPriceClick:n})}function sa(e={}){let[t,r]=useState(null),[n]=useState(null),s=useCallback(a=>{r(null);},[]);return {orders:[],isLoading:false,isFetching:false,cancellingOrderId:t,cancelOrder:s,cancelError:n}}function Ym(e){return new Date(e).toLocaleString("default",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function oa({orders:e,isLoading:t,cancellingOrderId:r,onCancel:n}){let{t:s}=useTranslation(),a=useMemo(()=>e.map(o=>({key:o.id,side:o.side,outcome:o.outcome,type:o.type,price:o.price,filled:`${o.filledQuantity}/${o.quantity}`,status:o.status,createdAt:Ym(o.createdAt),isCancelling:o.id===r,id:o.id})),[e,r]);return t?jsxs("div",{className:"flex w-full flex-col rounded-xl border border-default-200 bg-content1",children:[jsx("div",{className:"border-b border-default-200 px-3 py-2 text-sm font-medium",children:s("predict.openOrders.title")}),jsx("div",{className:"flex flex-col gap-y-2 p-3",children:Array.from({length:3}).map((o,i)=>jsx("div",{className:"h-8 animate-pulse rounded bg-default-100"},i))})]}):jsxs("div",{className:"flex w-full flex-col rounded-xl border border-default-200 bg-content1",children:[jsxs("div",{className:"border-b border-default-200 px-3 py-2 text-sm font-medium",children:[s("predict.openOrders.title"),e.length>0&&jsxs("span",{className:"ml-1 text-default-400",children:["(",e.length,")"]})]}),e.length===0?jsx("div",{className:"flex items-center justify-center py-8 text-xs text-default-400",children:s("predict.openOrders.empty")}):jsx("div",{className:"w-full overflow-x-auto",children:jsxs(StyledTable,{radius:"none","aria-label":"Open orders",className:"min-w-[600px]",children:[jsxs(TableHeader,{children:[jsx(TableColumn,{textValue:"Side",width:60,children:s("predict.openOrders.side")}),jsx(TableColumn,{textValue:"Outcome",width:60,children:s("predict.openOrders.outcome")}),jsx(TableColumn,{textValue:"Type",width:60,children:s("predict.openOrders.type")}),jsx(TableColumn,{textValue:"Price",width:60,children:s("predict.openOrders.price")}),jsx(TableColumn,{textValue:"Filled",width:80,children:s("predict.openOrders.filled")}),jsx(TableColumn,{textValue:"Status",width:70,children:s("predict.openOrders.status")}),jsx(TableColumn,{textValue:"Time",width:120,children:s("predict.openOrders.time")}),jsx(TableColumn,{textValue:"Action",width:80,align:"end",children:" "})]}),jsx(TableBody,{children:a.map(o=>jsxs(TableRow,{children:[jsx(TableCell,{children:jsx("span",{className:`text-xs font-medium ${o.side==="buy"?"text-primary":"text-danger"}`,children:o.side==="buy"?s("predict.trade.buy"):s("predict.trade.sell")})}),jsx(TableCell,{children:jsx("span",{className:`text-xs ${o.outcome==="yes"?"text-primary":"text-secondary"}`,children:o.outcome==="yes"?s("predict.trade.yes"):s("predict.trade.no")})}),jsx(TableCell,{children:jsx("span",{className:"text-xs capitalize",children:o.type})}),jsx(TableCell,{children:jsxs("span",{className:"text-xs",children:[o.price,"\xA2"]})}),jsx(TableCell,{children:jsx("span",{className:"text-xs",children:o.filled})}),jsx(TableCell,{children:jsx("span",{className:"text-xs capitalize",children:o.status})}),jsx(TableCell,{children:jsx("span",{className:"text-xs text-default-500",children:o.createdAt})}),jsx(TableCell,{className:"text-right",children:jsx(Button,{size:"sm",variant:"flat",color:"danger",isLoading:o.isCancelling,onPress:()=>n(o.id),children:s("predict.openOrders.cancel")})})]},o.key))})]})})]})}function $C({refetchInterval:e}={}){let{orders:t,isLoading:r,cancellingOrderId:n,cancelOrder:s}=sa({});return jsx(oa,{orders:t,isLoading:r,cancellingOrderId:n,onCancel:s})}function ia({ticker:e,pageSize:t=48}={}){let[r,n]=useState(1),[s,a]=useState([void 0]),o=s[r-1],i=useMemo(()=>({...e?{ticker:e}:{},limit:t,...o?{cursor:o}:{}}),[e,t,o]),{data:l,isLoading:c,isFetching:u}=Rn(i),p=l,d=p?.trades??[],y=!!p?.cursor,f=r>1,g=useCallback(b=>{b>=1&&b<=s.length&&n(b);},[s.length]),v=useCallback(()=>{y&&p?.cursor&&(a(b=>{let x=[...b];return x.length===r&&x.push(p.cursor),x}),n(b=>b+1));},[y,p?.cursor,r]),h=useCallback(()=>{f&&n(b=>b-1);},[f]);return {trades:d,isLoading:c,isFetching:u,page:r,pageSize:t,hasNextPage:y,hasPrevPage:f,goToPage:g,nextPage:v,prevPage:h}}function af(e){return new Date(e*1e3).toLocaleString("default",{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function ca({trades:e,isLoading:t,isFetching:r,page:n,hasNextPage:s,hasPrevPage:a,onNextPage:o,onPrevPage:i}){let{t:l}=useTranslation(),c=useMemo(()=>e.map(u=>({key:u.tradeId,ticker:u.ticker,takerSide:u.takerSide,price:u.price,yesPrice:u.yesPrice,noPrice:u.noPrice,count:u.count,createdAt:af(u.createdTime)})),[e]);return t?jsxs("div",{className:"flex w-full flex-col rounded-xl border border-default-200 bg-content1",children:[jsx("div",{className:"border-b border-default-200 px-3 py-2 text-sm font-medium",children:l("predict.tradeHistory.title")}),jsx("div",{className:"flex flex-col gap-y-2 p-3",children:Array.from({length:3}).map((u,p)=>jsx("div",{className:"h-8 animate-pulse rounded bg-default-100"},p))})]}):jsxs("div",{className:"flex w-full flex-col rounded-xl border border-default-200 bg-content1",children:[jsx("div",{className:"border-b border-default-200 px-3 py-2 text-sm font-medium",children:l("predict.tradeHistory.title")}),e.length===0?jsx("div",{className:"flex items-center justify-center py-8 text-xs text-default-400",children:l("predict.tradeHistory.empty")}):jsxs(Fragment,{children:[jsx("div",{className:`w-full overflow-x-auto ${r?"opacity-60":""}`,children:jsxs(StyledTable,{radius:"none","aria-label":"Trade history",className:"min-w-[480px]",children:[jsxs(TableHeader,{children:[jsx(TableColumn,{textValue:"Side",width:60,children:l("predict.tradeHistory.side")}),jsx(TableColumn,{textValue:"Price",width:80,children:l("predict.tradeHistory.price")}),jsx(TableColumn,{textValue:"Yes",width:60,children:l("predict.trade.yes")}),jsx(TableColumn,{textValue:"No",width:60,children:l("predict.trade.no")}),jsx(TableColumn,{textValue:"Qty",width:60,children:l("predict.tradeHistory.qty")}),jsx(TableColumn,{textValue:"Time",width:120,children:l("predict.tradeHistory.time")})]}),jsx(TableBody,{children:c.map(u=>jsxs(TableRow,{children:[jsx(TableCell,{children:jsx("span",{className:`text-xs font-medium ${u.takerSide==="yes"?"text-primary":"text-secondary"}`,children:u.takerSide==="yes"?l("predict.trade.yes"):l("predict.trade.no")})}),jsx(TableCell,{children:jsxs("span",{className:"text-xs",children:[u.price,"\xA2"]})}),jsx(TableCell,{children:jsxs("span",{className:"text-xs text-primary",children:[u.yesPrice,"\xA2"]})}),jsx(TableCell,{children:jsxs("span",{className:"text-xs text-secondary",children:[u.noPrice,"\xA2"]})}),jsx(TableCell,{children:jsx("span",{className:"text-xs",children:u.count})}),jsx(TableCell,{children:jsx("span",{className:"text-xs text-default-500",children:u.createdAt})})]},u.key))})]})}),(a||s)&&jsxs("div",{className:"flex items-center justify-between border-t border-default-200 px-3 py-2",children:[jsx(Button,{size:"sm",variant:"flat",isDisabled:!a,onPress:i,startContent:jsx(ChevronLeftIcon,{className:"h-3 w-3"}),children:l("predict.pagination.prev")}),jsx("span",{className:"text-xs text-default-500",children:l("predict.pagination.page",{page:n})}),jsx(Button,{size:"sm",variant:"flat",isDisabled:!s,onPress:o,endContent:jsx(ChevronRightIcon,{className:"h-3 w-3"}),children:l("predict.pagination.next")})]})]})]})}function uE({ticker:e,pageSize:t}={}){let{trades:r,isLoading:n,isFetching:s,page:a,hasNextPage:o,hasPrevPage:i,nextPage:l,prevPage:c}=ia({ticker:e,pageSize:t});return jsx(ca,{trades:r,isLoading:n,isFetching:s,page:a,hasNextPage:o,hasPrevPage:i,onNextPage:l,onPrevPage:c})}function ua(e={}){let t=useMemo(()=>({totalValue:0,totalUnrealizedPnl:0,totalRealizedPnl:0,count:0}),[]);return {positions:[],isLoading:false,isFetching:false,summary:t}}var Xt=e=>formatAmountUSDCompact(e/100);function ln({value:e}){if(e===0)return jsx("span",{className:"text-default-500",children:Xt(0)});let t=e>0;return jsxs("span",{className:t?"text-success":"text-danger",children:[t?"+":"",Xt(e)]})}function da({positions:e,isLoading:t,summary:r,onSell:n}){let{t:s}=useTranslation(),a=useMemo(()=>e.map(o=>({key:`${o.marketId}-${o.outcome}`,marketTitle:o.marketTitle,outcome:o.outcome,quantity:o.quantity,avgCost:o.avgCostBasis,currentPrice:o.currentPrice,value:o.currentPrice*o.quantity,unrealizedPnl:o.unrealizedPnl,position:o})),[e]);return t?jsxs("div",{className:"flex w-full flex-col rounded-xl border border-default-200 bg-content1",children:[jsx("div",{className:"border-b border-default-200 px-3 py-2 text-sm font-medium",children:s("predict.positions.title")}),jsx("div",{className:"flex flex-col gap-y-2 p-3",children:Array.from({length:3}).map((o,i)=>jsx("div",{className:"h-8 animate-pulse rounded bg-default-100"},i))})]}):jsxs("div",{className:"flex w-full flex-col rounded-xl border border-default-200 bg-content1",children:[jsx("div",{className:"flex items-center justify-between border-b border-default-200 px-3 py-2",children:jsxs("span",{className:"text-sm font-medium",children:[s("predict.positions.title"),e.length>0&&jsxs("span",{className:"ml-1 text-default-400",children:["(",e.length,")"]})]})}),e.length===0?jsx("div",{className:"flex items-center justify-center py-8 text-xs text-default-400",children:s("predict.positions.empty")}):jsxs(Fragment,{children:[jsx("div",{className:"w-full overflow-x-auto",children:jsxs(StyledTable,{radius:"none","aria-label":"Positions",className:"min-w-[640px]",children:[jsxs(TableHeader,{children:[jsx(TableColumn,{textValue:"Market",width:200,children:s("predict.positions.market")}),jsx(TableColumn,{textValue:"Outcome",width:60,children:s("predict.positions.outcome")}),jsx(TableColumn,{textValue:"Qty",width:50,children:s("predict.positions.qty")}),jsx(TableColumn,{textValue:"Avg Cost",width:70,children:s("predict.positions.avgCost")}),jsx(TableColumn,{textValue:"Price",width:60,children:s("predict.positions.currentPrice")}),jsx(TableColumn,{textValue:"Value",width:80,children:s("predict.positions.value")}),jsx(TableColumn,{textValue:"PnL",width:80,children:s("predict.positions.pnl")})]}),jsx(TableBody,{children:a.map(o=>jsxs(TableRow,{className:n?"cursor-pointer hover:bg-default-50":"",onClick:()=>n?.(o.position),children:[jsx(TableCell,{children:jsx("span",{className:"text-xs font-medium line-clamp-1",children:o.marketTitle})}),jsx(TableCell,{children:jsx("span",{className:`text-xs font-medium ${o.outcome==="yes"?"text-primary":"text-secondary"}`,children:o.outcome==="yes"?s("predict.trade.yes"):s("predict.trade.no")})}),jsx(TableCell,{children:jsx("span",{className:"text-xs",children:o.quantity})}),jsx(TableCell,{children:jsxs("span",{className:"text-xs",children:[o.avgCost,"\xA2"]})}),jsx(TableCell,{children:jsxs("span",{className:"text-xs",children:[o.currentPrice,"\xA2"]})}),jsx(TableCell,{children:jsx("span",{className:"text-xs",children:Xt(o.value)})}),jsx(TableCell,{children:jsx("span",{className:"text-xs",children:jsx(ln,{value:o.unrealizedPnl})})})]},o.key))})]})}),jsxs("div",{className:"flex items-center justify-between border-t border-default-200 px-3 py-2 text-xs",children:[jsx("div",{className:"flex items-center gap-x-4",children:jsxs("span",{className:"text-default-500",children:[s("predict.positions.totalValue"),":"," ",jsx("span",{className:"font-medium text-foreground",children:Xt(r.totalValue)})]})}),jsxs("div",{className:"flex items-center gap-x-4",children:[jsxs("span",{className:"text-default-500",children:[s("predict.positions.unrealizedPnl"),":"," ",jsx(ln,{value:r.totalUnrealizedPnl})]}),jsxs("span",{className:"text-default-500",children:[s("predict.positions.realizedPnl"),":"," ",jsx(ln,{value:r.totalRealizedPnl})]})]})]})]})]})}function wE({refetchInterval:e,onSell:t}={}){let{positions:r,isLoading:n,summary:s}=ua({});return jsx(da,{positions:r,isLoading:n,summary:s,onSell:t})}var Pf=10,Sf=atomWithStorage("liberfi:predict_search_histories",[],void 0,{getOnInit:true});function Zt(){let[e,t]=useAtom(Sf),r=useCallback(s=>{let a=s.trim();a&&t(o=>{let i=o.filter(l=>l!==a);return [a,...i].slice(0,Pf)});},[t]),n=useCallback(()=>{t([]);},[t]);return {histories:e,addHistory:r,clearHistories:n}}function ya({histories:e,onSelect:t,onClear:r,className:n}){let{t:s}=useTranslation();return e.length===0?null:jsxs("div",{className:cn("px-4 pb-4",n),children:[jsxs("div",{className:"flex items-center justify-between",children:[jsx("span",{className:"text-sm font-medium",children:s("predict.search.history")}),jsx(Button,{isIconOnly:true,size:"sm",className:"bg-transparent min-w-6 w-6 h-6 text-neutral",onPress:r,children:jsx(TrashIcon,{width:20,height:20})})]}),jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:e.map(a=>jsx(Chip,{size:"sm",variant:"bordered",className:cn("text-neutral","border-border border-1","cursor-pointer","hover:opacity-hover"),onClick:()=>t?.(a),children:a},a))})]})}function ga({onSelect:e,className:t}){let{histories:r,clearHistories:n}=Zt();return jsx(ya,{className:cn(t),histories:r,onSelect:e,onClear:n})}function va({value:e,onValueChange:t,onClear:r,onEscape:n,className:s}){let{t:a}=useTranslation();return jsx("div",{className:s,children:jsx(StyledInput,{autoFocus:true,variant:"flat",radius:"full",value:e,onValueChange:t,placeholder:a("predict.search.placeholder"),startContent:jsx(SearchIcon,{width:20,height:20,className:"text-neutral"}),endContent:e?jsx(Button,{isIconOnly:true,className:"bg-transparent min-w-6 w-6 h-6 text-neutral",onPress:r,children:jsx(XCloseIcon,{width:20,height:20})}):jsx(Kbd,{className:"min-w-8 justify-center text-xs text-neutral bg-transparent border border-border rounded-full cursor-pointer select-none",onMouseDown:o=>{o.preventDefault(),n?.();},children:"Esc"})})})}function ba({event:e,href:t,LinkComponent:r,onSelect:n,onHover:s,className:a}){let o=e.tags?.[0];return jsxs(Linkable,{href:t,LinkComponent:r,className:cn("w-full h-full px-3 flex items-center gap-3","hover:cursor-pointer hover:bg-content2 rounded-lg","transition-colors duration-150",a),onClick:i=>{t&&n&&i.preventDefault(),n?.(e);},onMouseEnter:()=>s?.(e),children:[jsx(Avatar,{src:e.image_url||void 0,name:e.title||"Event",radius:"full",className:"h-10 w-10 flex-shrink-0"}),jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2.5",children:[jsx("span",{className:"min-w-0 text-sm font-medium truncate",children:e.title}),o&&jsx("span",{className:cn("flex-shrink-0 inline-flex items-center","rounded-full px-2.5 py-1.5","text-[11px] font-semibold leading-none uppercase","bg-primary/15 text-primary"),children:o.label})]})]})}function ka({keyword:e="",limit:t,source:r}){let{data:n,isLoading:s,isFetchingNextPage:a,hasNextPage:o,fetchNextPage:i}=Sn({keyword:e,limit:t,source:r},{enabled:true});return {events:useMemo(()=>n?.pages.flatMap(c=>c.items).filter(c=>c!=null)??[],[n]),isLoading:s,isFetchingNextPage:a,hasNextPage:o??false,fetchNextPage:i}}var Kf=56;function Ea({onSelect:e,getEventHref:t,LinkComponent:r,onHover:n,className:s,...a}){let{events:o,isLoading:i,isFetchingNextPage:l,hasNextPage:c,fetchNextPage:u}=ka(a),p=useRef(null),{height:d}=useResizeObserver({ref:p}),y=useCallback(h=>h<o.length,[o]),f=useCallback(async()=>{c&&!l&&await u();},[c,l,u]),g=useMemo(()=>c?o.length+1:o.length,[o,c]),v=useInfiniteLoader({isRowLoaded:y,loadMoreRows:f,rowCount:g,threshold:5});return i?jsx(zf,{className:s}):o.length===0?jsx(Gf,{className:s}):jsx("div",{className:cn("w-full h-full flex flex-col",s),children:jsx("div",{className:"flex-auto min-h-0",ref:p,children:jsx(List,{style:{height:d},onRowsRendered:v,rowComponent:$f,rowCount:g,rowHeight:Kf,rowProps:{events:o,onSelect:e,getEventHref:t,LinkComponent:r,onHover:n},overscanCount:5})})})}function $f({index:e,style:t,events:r,onSelect:n,getEventHref:s,LinkComponent:a,onHover:o}){let i=r[e];return i?jsx("div",{style:t,children:jsx(ba,{event:i,href:s?.(i),LinkComponent:a,onSelect:n,onHover:o})}):jsx("div",{style:t,className:"flex items-center justify-center",children:jsx(Spinner,{size:"sm"})})}function zf({className:e}){let{t}=useTranslation();return jsxs("div",{className:cn("flex items-center justify-center gap-2 py-16",e),children:[jsx(Spinner,{size:"sm"}),jsx("span",{className:"text-sm text-neutral",children:t("predict.search.loading")})]})}function Gf({className:e}){let{t}=useTranslation();return jsxs("div",{className:cn("flex flex-col items-center justify-center py-16",e),children:[jsx(EmptyIcon,{width:28,height:28,className:"text-neutral"}),jsx("p",{className:"mt-2 text-sm text-neutral",children:t("predict.search.noResults")})]})}function Ra({onKeywordChange:e}){let[t,r]=useState(""),[n,s]=useState(""),{addHistory:a}=Zt(),o=useCallbackRef(e),i=useCallbackRef(a),l=useMemo(()=>debounce(d=>{s(d),o(d),d&&i(d);},500),[o,i]),c=useCallback(d=>{r(d),l(d);},[l]),u=useCallback(d=>{l.cancel(),r(d),s(d),o(d),d&&i(d);},[l,o,i]),p=useCallback(()=>u(""),[u]);return {text:t,keyword:n,setText:c,setKeyword:u,clearKeyword:p}}function Na({onKeywordChange:e,onSelectEvent:t,getEventHref:r,LinkComponent:n,onHover:s,onEscape:a,source:o}){let{text:i,keyword:l,setText:c,setKeyword:u,clearKeyword:p}=Ra({onKeywordChange:e});return jsxs("div",{className:"w-full h-full flex flex-col gap-3",children:[jsx(va,{value:i,onValueChange:c,onClear:p,onEscape:a}),!l&&jsx(ga,{onSelect:u}),jsx(Ea,{className:"flex-auto min-h-0",keyword:l,onSelect:t,getEventHref:r,LinkComponent:n,onHover:s,source:o})]})}var mn="predict-search";function _2({id:e=mn}){return jsx(AsyncModal,{id:e,children:t=>jsx(iy,{...t})})}function iy({params:e,isOpen:t,onOpenChange:r,onResult:n}){let{t:s}=useTranslation(),{isMobile:a}=useScreen(),o=useCallback(l=>{n(l);},[n]),i=useCallback(()=>{r(false);},[r]);return jsx(StyledModal,{isOpen:t,onOpenChange:r,size:a?"full":"lg",hideCloseButton:true,backdrop:"blur",radius:"lg",children:jsxs(ModalContent,{className:"w-full h-full",children:[jsxs(ModalHeader,{className:"sm:hidden flex items-center justify-between pt-4 pb-2",children:[jsx("span",{className:"text-base font-semibold",children:s("predict.search.title")}),jsx(Button,{isIconOnly:true,onPress:()=>r(false),size:"sm",className:"bg-transparent min-w-6 w-6 h-6",children:jsx(XCloseIcon,{width:20,height:20})})]}),jsx(ModalBody,{className:"p-4",children:jsx(Na,{getEventHref:e?.getEventHref,LinkComponent:e?.LinkComponent,onHover:e?.onHover,source:e?.source,onSelectEvent:o,onEscape:i})})]})})}function K2({onSelectEvent:e,modalParams:t,className:r}){let{t:n}=useTranslation(),{isDesktop:s,isMobile:a}=useScreen(),{onOpen:o,onClose:i}=useAsyncModal(mn),l=useCallbackRef(e),c=useCallbackRef(async()=>{let p=await o({params:t});p&&l(p);}),u=useCallbackRef(()=>{i();});return useEffect(()=>{let p=d=>{let y=document.activeElement,f=!!y&&(y.tagName==="INPUT"||y.tagName==="TEXTAREA"||y.getAttribute("contenteditable")==="true");d.key==="/"&&!f&&(d.preventDefault(),c()),d.key==="Escape"&&(d.preventDefault(),u());};return window.addEventListener("keydown",p),()=>{window.removeEventListener("keydown",p);}},[c,u]),jsx(Button,{size:"sm",radius:"full",isIconOnly:!s,onPress:c,variant:a?"flat":"bordered",startContent:s?jsx(SearchIcon,{className:"text-neutral"}):void 0,endContent:s?jsx(Kbd,{className:"ml-auto min-w-6 justify-center text-xs bg-transparent border border-border rounded-full",children:"/"}):void 0,className:cn(s&&"min-w-56 justify-start pl-3 pr-1.5 text-neutral",r),children:s?n("predict.search.placeholder"):jsx(SearchIcon,{className:"text-neutral"})})}function xM({client:e,wsClient:t=null,children:r}){let n=useMemo(()=>({client:e,wsClient:t}),[e,t]);return jsx($e.Provider,{value:n,children:r})}var xy=3e4;function CM({walletAddress:e,pollingInterval:t=xy,enabled:r=true,children:n}){let{data:s,isLoading:a,error:o,refetch:i}=_n({walletAddress:e},{enabled:r&&!!e,refetchInterval:t}),l=useMemo(()=>({positions:s?.positions??[],usdcBalance:s?.usdcBalance??0,isLoading:a,error:o??null,refetch:i}),[s?.positions,s?.usdcBalance,a,o,i]);return jsx(Me.Provider,{value:l,children:n})}function RM({client:e,children:t}){let r=useMemo(()=>({client:e}),[e]);return jsx(Ct.Provider,{value:r,children:t})}function Va(e,t){let r=new URLSearchParams;t&&r.set("provider",t);for(let[s,a]of Object.entries(e))a!=null&&(typeof a=="object"?r.set(s,JSON.stringify(a)):r.set(s,String(a)));let n=r.toString();return n?`?${n}`:""}function Ba(e){return e}var vt=class{constructor(t,r){this.endpoint=t;this.provider=r;}buildUrl(t,r){let n=Va(r??{},this.provider);return `${this.endpoint}${t}${n}`}async fetch(t,r){let n=this.buildUrl(t,r);return await httpGet(n)}async postRequest(t,r,n){let s=this.buildUrl(t,n);return await httpPost(s,r)}};function er(e,t){if(!e)return [];let r=Object.entries(e).map(([n,s])=>({price:parseFloat(n),quantity:s}));return r.sort((n,s)=>t==="desc"?s.price-n.price:n.price-s.price),r}function _a(e){return {yesBids:er(e.yes_bids,"desc"),yesAsks:er(e.yes_asks,"asc"),noBids:er(e.no_bids,"desc"),noAsks:er(e.no_asks,"asc"),sequence:e.sequence}}var tr=class extends vt{constructor(t){super(t,"dflow");}async getEvents(t){return await this.fetch("/v2/event",t??{})}async getEventById(t,r){return await this.fetch(`/v2/event/${t}`,{withNestedMarkets:r})}async getEventCandlesticks(t,r){return await this.fetch(`/v2/event/${t}/candlesticks`,r)}async getEventForecastPercentileHistory(t){let{seriesTicker:r,eventId:n,...s}=t;return await this.fetch(`/v2/event/${r}/${n}/forecast_percentile_history`,s)}async getEventForecastPercentileHistoryByMint(t){let{mintAddress:r,...n}=t;return await this.fetch(`/v2/event/by-mint/${r}/forecast_percentile_history`,n)}async getMarkets(t){return await this.fetch("/v2/market",t??{})}async getMarketById(t){return await this.fetch(`/v2/market/${t}`)}async getMarketByMint(t){return await this.fetch(`/v2/market/by-mint/${t}`)}async getMarketsBatch(t){return await this.postRequest("/v2/market/batch",t)}async getMarketCandlesticks(t,r){return await this.fetch(`/v2/market/${t}/candlesticks`,r)}async getMarketCandlesticksByMint(t,r){return await this.fetch(`/v2/market/by-mint/${t}/candlesticks`,r)}async getOrderbook(t){let r=await this.fetch(`/v2/orderbook/${t}`);return _a(r)}async getOrderbookByMint(t){let r=await this.fetch(`/v2/orderbook/by-mint/${t}`);return _a(r)}async getTrades(t){return await this.fetch("/v2/trades",t??{})}async getTradesByMint(t){let{mintAddress:r,...n}=t;return await this.fetch(`/v2/trades/by-mint/${r}`,n)}async getOnchainTradesByWallet(t){let{walletAddress:r,...n}=t;return await this.fetch(`/v2/trades/onchain/by-wallet/${r}`,n)}async getOnchainTradesByEvent(t){let{eventTicker:r,...n}=t;return await this.fetch(`/v2/trades/onchain/by-event/${r}`,n)}async getOnchainTradesByMarket(t){let{marketTicker:r,...n}=t;return await this.fetch(`/v2/trades/onchain/by-market/${r}`,n)}async getLiveData(t){return await this.fetch("/v2/live",{milestoneIds:t.milestoneIds.join(",")})}async getLiveDataByEvent(t){let{eventTicker:r,...n}=t;return await this.fetch(`/v2/live/event/${r}`,n)}async getLiveDataByMint(t){let{mintAddress:r,...n}=t;return await this.fetch(`/v2/live/by-mint/${r}`,n)}async getSeries(t){return await this.fetch("/v2/series",t??{})}async getSeriesByTicker(t){return await this.fetch(`/v2/series/${t}`)}async getTagsByCategories(){return await this.fetch("/v2/tags/by_categories")}async getFiltersBySports(){return await this.fetch("/v2/sports/filters")}async search(t){return await this.fetch("/v2/search",t)}async getPositionsByWallet(t){let{walletAddress:r}=t;return await this.fetch(`/v2/positions/by-wallet/${r}`)}async getOutcomeMints(t){return await this.fetch("/v2/outcome_mints",t??{})}async filterOutcomeMints(t){return await this.postRequest("/v2/filter_outcome_mints",t)}async getQuote(t){return await this.fetch("/v2/swap/quote",t)}async createSwap(t){return await this.postRequest("/v2/swap",t)}async createSwapInstructions(t){return await this.postRequest("/v2/swap/instructions",t)}async getOrder(t){return await this.fetch("/v2/order",t)}async getOrderStatus(t){try{return await this.fetch("/v2/order/status",t)}catch(r){if(r instanceof Error&&/\b404\b/.test(r.message))return {status:"pending",inAmount:"0",outAmount:"0"};throw r}}async getIntentQuote(t){return await this.fetch("/v2/intent/quote",t)}async submitIntentSwap(t){return await this.postRequest("/v2/intent/swap",t)}async initPredictionMarket(t){return await this.fetch("/v2/prediction-market/init",t)}async getTokens(){return await this.fetch("/v2/tokens")}async getTokensWithDecimals(){return await this.fetch("/v2/tokens/decimals")}async getVenues(){return await this.fetch("/v2/venues")}};function gn(e){let t=new URLSearchParams;for(let[n,s]of Object.entries(e))s!=null&&t.set(n,String(s));let r=t.toString();return r?`?${r}`:""}var xt=class{constructor(t){this.endpoint=t;}async listEvents(t){let r=gn(t??{}),n=`${this.endpoint}/api/v1/events${r}`;return await httpGet(n)}async getEvent(t,r){let n=r?gn({source:r}):"",s=`${this.endpoint}/api/v1/events/${encodeURIComponent(t)}${n}`;return await httpGet(s)}async getMarket(t,r){let n=r?gn({source:r}):"",s=`${this.endpoint}/api/v1/markets/${encodeURIComponent(t)}${n}`;return await httpGet(s)}};function Qa(e){return new xt(e)}export{vt as BasePredictClient,Mr as CATEGORIES_V2,Ke as CHART_RANGE_DURATION,He as CHART_RANGE_PERIOD,Mt as CHART_RANGE_SAMPLE_INTERVAL,Et as CandlestickPeriod,It as CategoriesSkeleton,Ot as CategoriesUI,ss as CategoriesWidget,xs as CategoriesWidgetV2,S as ChartRange,le as DEFAULT_CHART_RANGE,wr as DEFAULT_FILTER_STATE,de as DEFAULT_PAGE_SIZE,Fy as DEFAULT_PRICE_HISTORY_INTERVAL,tr as DflowPredictClient,st as DflowPredictWsClient,fS as EventDetailPage,jS as EventDetailPageV2,ge as EventDetailSkeleton,Io as EventDetailUI,Ho as EventDetailV2UI,Gr as EventDetailWidget,en as EventDetailWidgetV2,vc as EventItemSkeleton,cs as EventItemUI,As as EventItemV2UI,Kt as EventMarketDetailWidget,nC as EventPriceChartV2,bs as EventsFilterV2UI,Kb as EventsPage,gb as EventsPageSkeleton,D0 as EventsPageV2,ot as EventsSkeleton,Es as EventsToolbarV2UI,ps as EventsUI,Hs as EventsV2UI,fs as EventsWidget,$s as EventsWidgetV2,J as MAX_PRICE_HISTORY_MARKETS,Uy as ORDER_MAX_PRICE,Dy as ORDER_MIN_PRICE,ar as ORDER_MIN_QUANTITY,Ay as ORDER_PRICE_STEP,oa as OpenOrdersUI,$C as OpenOrdersWidget,ra as OrderBookUI,NC as OrderBookWidget,mn as PREDICT_SEARCH_MODAL_ID,Wy as PRICE_HISTORY_SAMPLE_INTERVAL,da as PositionsUI,wE as PositionsWidget,tr as PredictClient,xt as PredictClientV2,$e as PredictContext,xM as PredictProvider,_2 as PredictSearchModal,Ct as PredictV2Context,RM as PredictV2Provider,st as PredictWsClient,qe as PriceHistoryInterval,Cs as SORT_PRESETS,K2 as SearchEventsButton,ya as SearchHistoryUI,ga as SearchHistoryWidget,va as SearchInputUI,ba as SearchResultItemUI,Ea as SearchResultListWidget,Na as SearchWidget,Ut as TradeFormSkeleton,eo as TradeFormUI,je as TradeFormWidget,ca as TradeHistoryUI,uE as TradeHistoryWidget,Me as UserPredictContext,CM as UserPredictProvider,Va as buildQuery,Tr as countActiveFilters,Rt as createDflowPredictWsClient,Qa as createPredictClientV2,Rt as createPredictWsClient,Vl as createSwap,Bl as createSwapInstructions,ki as eventByIdQueryKey,Yi as eventCandlesticksQueryKey,ur as eventV2QueryKey,hi as eventsInfiniteQueryKey,vi as eventsQueryKey,lr as eventsV2InfiniteQueryKey,ei as eventsV2QueryKey,Pi as fetchEventById,ji as fetchEventCandlesticks,dr as fetchEventV2,pr as fetchEvents,ti as fetchEventsV2,cr as fetchEventsV2Page,gl as fetchFiltersBySports,el as fetchForecastPercentileHistory,rl as fetchForecastPercentileHistoryByMint,ql as fetchIntentQuote,sl as fetchLiveData,al as fetchLiveDataByEvent,ll as fetchLiveDataByMint,Ti as fetchMarketById,Oi as fetchMarketByMint,nt as fetchMarketCandlesticks,Zi as fetchMarketCandlesticksByMint,ci as fetchMarketV2,Ei as fetchMarkets,Vi as fetchMarketsBatch,yr as fetchOnchainTradesByEvent,gr as fetchOnchainTradesByMarket,fr as fetchOnchainTradesByWallet,Ql as fetchOrder,_i as fetchOrderBook,Ai as fetchOrderBookByMint,Dl as fetchOrderStatus,Rl as fetchOutcomeMints,Pl as fetchPositionsByWallet,Ll as fetchQuote,hl as fetchSearch,ul as fetchSeries,pl as fetchSeriesByTicker,fl as fetchTagsByCategories,Gl as fetchTokens,jl as fetchTokensWithDecimals,Ui as fetchTrades,Wi as fetchTradesByMint,Jl as fetchVenues,Nl as filterOutcomeMints,yl as filtersBySportsQueryKey,tl as forecastPercentileHistoryByMintQueryKey,Ji as forecastPercentileHistoryQueryKey,$l as initPredictionMarket,Wl as intentQuoteQueryKey,ol as liveDataByEventQueryKey,il as liveDataByMintQueryKey,nl as liveDataQueryKey,wi as marketByIdQueryKey,Ni as marketByMintQueryKey,Xi as marketCandlesticksByMintQueryKey,rt as marketCandlesticksQueryKey,li as marketV2QueryKey,Li as marketsBatchQueryKey,Ci as marketsQueryKey,zi as onchainTradesByEventInfiniteQueryKey,Hi as onchainTradesByEventQueryKey,Gi as onchainTradesByMarketInfiniteQueryKey,Ki as onchainTradesByMarketQueryKey,$i as onchainTradesByWalletInfiniteQueryKey,qi as onchainTradesByWalletQueryKey,Qi as orderBookByMintQueryKey,Bi as orderBookQueryKey,_l as orderQueryKey,Al as orderStatusQueryKey,Tl as outcomeMintsQueryKey,kl as positionsByWalletQueryKey,Il as quoteQueryKey,ir as resolveEventsV2Params,kn as resolveTagSlug,xl as searchQueryKey,dl as seriesByTickerQueryKey,cl as seriesQueryKey,Hl as submitIntentSwap,ml as tagsByCategoriesQueryKey,Ba as toRecord,zl as tokensQueryKey,Yl as tokensWithDecimalsQueryKey,Fi as tradesByMintQueryKey,Di as tradesQueryKey,Xv as useCategoriesQuery,Ex as useCreateSwapInstructionsMutation,Cx as useCreateSwapMutation,Tt as useEventByIdQuery,Nv as useEventCandlesticksQuery,to as useEventDetail,Qo as useEventDetailV2,wt as useEventV2Query,os as useEvents,Zn as useEventsCategories,Mn as useEventsInfiniteQuery,Qg as useEventsQuery,Ts as useEventsV2,Pn as useEventsV2InfiniteQuery,_y as useEventsV2Query,gx as useFilterOutcomeMintsMutation,jv as useFiltersBySportsQuery,Qv as useForecastPercentileHistoryByMintQuery,_v as useForecastPercentileHistoryQuery,Qx as useInitPredictionMarketMutation,Ix as useIntentQuoteQuery,Wv as useLiveDataByEventQuery,qv as useLiveDataByMintQuery,Fv as useLiveDataQuery,Zg as useMarketByIdQuery,rv as useMarketByMintQuery,Ov as useMarketCandlesticksByMintQuery,br as useMarketCandlesticksQuery,Cn as useMarketHistoryV2,Qn as useMarketPositions,lg as useMarketV2Query,av as useMarketsBatchQuery,Gg as useMarketsQuery,Ev as useOnchainTradesByEventInfiniteQuery,xv as useOnchainTradesByEventQuery,Mv as useOnchainTradesByMarketInfiniteQuery,hv as useOnchainTradesByMarketQuery,Cv as useOnchainTradesByWalletInfiniteQuery,Nn as useOnchainTradesByWalletQuery,sa as useOpenOrders,Jo as useOrderBook,uv as useOrderBookByMintQuery,ze as useOrderBookQuery,Un as useOrderQuery,Fn as useOrderStatusQuery,dh as useOrderbookSubscription,yx as useOutcomeMintsQuery,ua as usePositions,_n as usePositionsByWalletQuery,k as usePredictClient,En as usePredictContext,Zt as usePredictSearchHistory,fe as usePredictV2Client,bn as usePredictV2Context,Iv as usePriceHistoryQuery,oh as usePricesSubscription,bx as useQuoteQuery,Sn as useSearchEventsInfiniteQuery,tx as useSearchQuery,ka as useSearchResultListScript,Ra as useSearchScript,Vn as useSeriesByTickerQuery,Ln as useSeriesQuery,Lx as useSubmitIntentSwapMutation,Pr as useTagsByCategoriesQuery,Fx as useTokensQuery,Wx as useTokensWithDecimalsQuery,js as useTradeForm,ia as useTradeHistory,fv as useTradesByMintQuery,Rn as useTradesQuery,lh as useTradesSubscription,lx as useUserPredictContext,$x as useVenuesQuery,rh as useWsClient,Zx as useWsConnection,Zl as venuesQueryKey,ja as version};//# sourceMappingURL=index.mjs.map
21
21
  //# sourceMappingURL=index.mjs.map