PageSourceSearch

https://www.openpoly.ai/_next/static/chunks/dc7a485ce89ad3ed.js

js openpoly.ai collected 2026-10-02 01:12:22 UTC 1,164,602 bytes, 11 lines download raw bytes

1(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,89364,e=>{"use strict";var t,a,s,r,n,l,i,o,c,d,u,h,p,m,x,g,f,b=e.i(48277),_=e.i(30668);let v={1:"radar",2:"worldcup",3:"sports",4:"strategy",5:"pattern",6:"aggregator",7:"wallet",8:"trader",9:"synthesizer",0:"hunt"};var y=e.i(30697),j=e.i(32890),w=e.i(35884);let N=(0,w.default)("user",[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]]),k=(0,w.default)("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);var S=e.i(46141);function $({onSelect:e}){let[t,a]=(0,_.useState)(""),[s,r]=(0,_.useState)(!1),{results:n,searching:l,search:i,clear:o}=function(){let[e,t]=(0,_.useState)([]),[a,s]=(0,_.useState)(!1),r=(0,_.useRef)(null);return{results:e,searching:a,search:(0,_.useCallback)(async e=>{if(r.current&&r.current.abort(),(e=e.trim()).length<2)return void t([]);s(!0);let a=new AbortController;r.current=a;try{let s=await fetch(`${y.API_BASE}/api/vault/search-profiles?q=${encodeURIComponent(e)}`,{signal:a.signal});if(!s.ok)throw Error(`${s.status}`);let r=await s.json();t(r.data||[])}catch(e){"AbortError"!==e.name&&t([])}finally{s(!1)}},[]),clear:(0,_.useCallback)(()=>{r.current&&r.current.abort(),t([])},[])}}(),c=(0,_.useRef)(null),d=(0,_.useRef)(null);(0,_.useEffect)(()=>{if(c.current&&clearTimeout(c.current),!t.trim()){o(),r(!1);return}if(/^0x[a-fA-F0-9]{40}$/.test(t.trim())){e(t.trim()),r(!1);return}return c.current=setTimeout(()=>{i(t),r(!0)},300),()=>{c.current&&clearTimeout(c.current)}},[t,i,o,e]),(0,_.useEffect)(()=>{function e(e){d.current&&!d.current.contains(e.target)&&r(!1)}return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[]);let u=(0,_.useCallback)(t=>{a(t.name||t.pseudonym||t.proxyWallet),r(!1),e(t.proxyWallet,t)},[e]),h=(0,_.useCallback)(()=>{a(""),o(),r(!1)},[o]);return(0,b.jsxs)("div",{className:"trader-search",ref:d,children:[(0,b.jsxs)("div",{className:"trader-search-input-wrap",children:[(0,b.jsx)(j.Search,{size:14,className:"trader-search-icon"}),(0,b.jsx)("input",{type:"text",className:"trader-search-input",placeholder:"Search trader or paste 0x address...",value:t,onChange:e=>a(e.target.value),onFocus:()=>n.length>0&&r(!0)}),t&&(0,b.jsx)("button",{className:"trader-search-clear",onClick:h,children:(0,b.jsx)(k,{size:12})}),l&&(0,b.jsx)("span",{className:"trader-search-spinner"})]}),s&&n.length>0&&(0,b.jsx)("div",{className:"trader-search-dropdown",children:n.map(e=>(0,b.jsxs)("button",{className:"trader-search-result",onClick:()=>u(e),children:[(0,b.jsx)("div",{className:"trader-search-result-avatar",children:e.profileImage?(0,b.jsx)("img",{src:e.profileImage,alt:"",width:24,height:24}):(0,b.jsx)(N,{size:14})}),(0,b.jsxs)("div",{className:"trader-search-result-info",children:[(0,b.jsx)("span",{className:"trader-search-result-name",children:e.displayUsernamePublic?e.name||e.pseudonym:e.pseudonym||e.proxyWallet.slice(0,10)+"..."}),(0,b.jsxs)("span",{className:"trader-search-result-wallet",children:[e.proxyWallet.slice(0,6),"...",e.proxyWallet.slice(-4)]})]}),(0,b.jsxs)("div",{className:"trader-search-result-stats",children:[(0,b.jsxs)("span",{children:["Vol: ",(0,b.jsx)("span",{className:"trader-search-vol",children:(0,S.fmtUsd)(e.volume,0)})]}),(0,b.jsxs)("span",{children:["PnL: ",(0,b.jsxs)("span",{className:`trader-search-pnl ${e.pnl>=0?"up":"down"}`,children:[e.pnl>=0?"+":"",(0,S.fmtUsd)(e.pnl,0)]})]})]})]},e.proxyWallet))})]})}function C({data:e}){if(!e||e.length<2)return null;let t=e.map(e=>e.equity),a=Math.min(...t),s=Math.max(...t),r=Math.max(s-a,.01),n=t.map((e,a)=>{let n=2+a/(t.length-1)*196;return`${n.toFixed(1)},${(2+(s-e)/r*56).toFixed(1)}`}).join(" "),l=t[t.length-1],i=t[0];return(0,b.jsx)("svg",{viewBox:"0 0 200 60",className:"trader-sidebar-equity-svg",children:(0,b.jsx)("polyline",{points:n,fill:"none",stroke:l>=i?"var(--color-long)":"var(--color-short)",strokeWidth:"1.5",strokeLinejoin:"round"})})}function M({badge:e}){return(0,b.jsx)("span",{className:"trader-sidebar-badge",style:{borderColor:e.color,color:e.color},children:e.label})}function E({wallet:e,profile:t,classification:a,stats:s,patterns:r,equityCurve:n,topMarkets:l,onMarketClick:i,loading:o}
1){let c=t?.displayUsernamePublic?t.name||t.pseudonym:t?.pseudonym||(e?`${e.slice(0,6)}...${e.slice(-4)}`:"—");return(0,b.jsxs)("aside",{className:"trader-sidebar",children:[(0,b.jsxs)("div",{className:"trader-sidebar-header",children:[(0,b.jsx)("div",{className:"trader-sidebar-avatar",children:t?.profileImage?(0,b.jsx)("img",{src:t.profileImage,alt:"",width:36,height:36}):(0,b.jsx)(N,{size:20})}),(0,b.jsxs)("div",{children:[(0,b.jsx)("div",{className:"trader-sidebar-name",children:c}),e&&(0,b.jsxs)("div",{className:"trader-sidebar-wallet",children:[e.slice(0,8),"...",e.slice(-6)]})]})]}),a&&(0,b.jsxs)("div",{className:"trader-sidebar-classification",children:[(0,b.jsx)("span",{className:`trader-sidebar-class-badge ${"market_maker"===a.classification?"mm":"dir"}`,children:"market_maker"===a.classification?"Market Maker":"Directional"}),(0,b.jsxs)("span",{className:"trader-sidebar-class-score",children:[(0,S.fmtPct)(100*a.classification_score,0)," confidence"]})]}),r?.badges&&r.badges.length>0&&(0,b.jsx)("div",{className:"trader-sidebar-badges",children:r.badges.map(e=>(0,b.jsx)(M,{badge:e},e.key))}),n&&n.length>1&&(0,b.jsxs)("div",{className:"trader-sidebar-equity",children:[(0,b.jsx)("div",{className:"trader-sidebar-section-title",children:"Equity Curve"}),(0,b.jsx)(C,{data:n})]}),s&&(0,b.jsxs)("div",{className:"trader-sidebar-stats",children:[(0,b.jsx)("div",{className:"trader-sidebar-section-title",children:"Performance"}),(0,b.jsxs)("div",{className:"trader-sidebar-stats-grid",children:[(0,b.jsxs)("div",{className:"trader-sidebar-stat",children:[(0,b.jsx)("span",{className:"label",children:"Total PnL"}),(0,b.jsx)("span",{className:s.total_pnl_usdc>=0?"up":"down",children:(0,S.fmtUsd)(s.total_pnl_usdc,0)})]}),(0,b.jsxs)("div",{className:"trader-sidebar-stat",children:[(0,b.jsx)("span",{className:"label",children:"Win Rate"}),(0,b.jsx)("span",{children:(0,S.fmtPct)(s.win_rate_pct,1)})]}),(0,b.jsxs)("div",{className:"trader-sidebar-stat",children:[(0,b.jsx)("span",{className:"label",children:"Max DD"}),(0,b.jsx)("span",{className:"down",children:(0,S.fmtPct)(s.max_drawdown_pct,1)})]}),(0,b.jsxs)("div",{className:"trader-sidebar-stat",children:[(0,b.jsx)("span",{className:"label",children:"Markets"}),(0,b.jsx)("span",{children:(0,S.fmtNum)(s.unique_markets)})]}),(0,b.jsxs)("div",{className:"trader-sidebar-stat",children:[(0,b.jsx)("span",{className:"label",children:"Trades"}),(0,b.jsx)("span",{children:(0,S.fmtNum)(s.total_trades)})]}),(0,b.jsxs)("div",{className:"trader-sidebar-stat",children:[(0,b.jsx)("span",{className:"label",children:"Avg Size"}),(0,b.jsx)("span",{children:(0,S.fmtUsd)(s.avg_position_size_usdc,0)})]}),(0,b.jsxs)("div",{className:"trader-sidebar-stat",children:[(0,b.jsx)("span",{className:"label",children:"Period"}),(0,b.jsxs)("span",{children:[s.period_days,"d"]})]}),(0,b.jsxs)("div",{className:"trader-sidebar-stat",children:[(0,b.jsx)("span",{className:"label",children:"Avg Hold"}),(0,b.jsx)("span",{children:function(e){if(!e||e<=0)return"—";if(e<1)return`${Math.round(60*e)}m`;if(e<24)return`${e.toFixed(1)}h`;let t=e/24;return t<30?`${t.toFixed(1)}d`:`${(t/30).toFixed(1)}mo`}(s.avg_hold_hours)})]}),(0,b.jsxs)("div",{className:"trader-sidebar-stat",children:[(0,b.jsx)("span",{className:"label",children:"Balance"}),(0,b.jsx)("span",{children:(0,S.fmtUsd)(s.current_balance_usdc,0)})]})]})]}),l&&l.length>0&&(0,b.jsxs)("div",{className:"trader-sidebar-markets",children:[(0,b.jsx)("div",{className:"trader-sidebar-section-title",children:"Top Markets"}),(0,b.jsx)("div",{className:"trader-sidebar-market-list",children:l.slice(0,15).map(e=>(0,b.jsxs)("button",{className:"trader-sidebar-market-item",onClick:()=>i?.(e.market),children:[(0,b.jsx)("span",{className:"trader-sidebar-market-slug",children:e.market}),(0,b.jsxs)("span",{className:"trader-sidebar-market-meta",children:[null!=e.pnl&&0!==e.pnl&&(0,b.jsxs)("span",{className:e.pnl>=0?"up":"down",children:[e.pnl>=0?"+":"",(0,S.fmtUsd)(e.pnl,0)]}),(0,b.jsxs)("span",{className:"trader-sidebar-market-count",children:[e.trades,"t"]})]})]},e.market))})]}),o&&!s&&(0,b.jsx)("div",{className:"trader-sidebar-loading",children:"Analyzing..."}),!o&&!e&&(0,b.jsx)("div",{className:"trader-sidebar-empty",children:"Search for a trader to view their profile"})]})}var A=e.i(46430),T=e.i(2880);let F={BTC:"BTCUSDT",ETH:"ETHUSDT",SOL:"SOLUSDT",XRP:"XRPUSDT"},P={"5m":"5m","15m":"15m","1h":"1h","4h":"4h","1d":"1d"};async function R(e,t,a=null){let s=F[e]||`${e}USDT`,r=P[t]||"5m",n=`/api/binance/klines?symbol=${s}&interval=${r}&limit=500`;a&&(n+=`&endTime=${a}`);let l=await fetch(n);if(!l.ok)throw Error(`Binance ${l.status}`);return(await l.json()).map(e=>({time:Math.floor(e[0]/1e3),open:parseFloat(e[1]),high:parseFloat(e[2]),low:parseFloat(e[3]),close:parseFloat(e[4]),volume:parseFloat(e[5]),openTimeMs:e[0]}))}function O(e){let t=new Set;return e.filter(e=>!t.has(e.time)&&(t.add(e.time),!0))}function L(e="BTC",t="5m",a=3e4){let[s,r]=(0,_.useState)([]),[n,l]=(0,_.useState)(null),[i,o]=(0,_.useState)(""),c=(0,_.useRef)(!1),d=(0,_.useRef)(null),u=(0,_.useRef)([]),h=(0,_.useRef)(`${e}:${t}`),p=(0,_.useCallback)(async()=>{let a=`${e}:${t}`;try{let s=await R(e,t);if(h.current!==a)return;r(e=>{if(0===e.length)return s;let t=[...e];for(let e of s){let a=t.findIndex(t=>t.time===e.time);a>=0?t[a]=e:t.push(e)}return t.sort((e,t)=>
1e.time-t.time),O(t)}),o("")}catch(e){if(h.current!==a)return;o(e instanceof Error?e.message:"Failed to load klines")}},[e,t]);(0,_.useEffect)(()=>{u.current=s},[s]);let m=(0,_.useCallback)(async()=>{if(c.current)return;let a=u.current;if(!a.length)return;let s=a[0].openTimeMs;if(!s)return;c.current=!0;let n=`${e}:${t}`;try{let a=await R(e,t,s-1);if(!a.length||h.current!==n)return;r(e=>{let t=[...a,...e];return t.sort((e,t)=>e.time-t.time),O(t)})}catch{}finally{c.current=!1}},[e,t]);return(0,_.useEffect)(()=>{h.current=`${e}:${t}`,c.current=!1,r([]),l(null),p()},[p,e,t]),(0,_.useEffect)(()=>{let a,s,n=`${e}:${t}`,i=(F[e]||`${e}USDT`).toLowerCase(),o=P[t]||"5m",c=`wss://stream.binance.com:9443/ws/${i}@kline_${o}`,u=null,m=!0,x=0;function g(){u||(u=setInterval(()=>{m&&p()},5e3))}function f(){u&&(clearInterval(u),u=null)}return!function e(){if(m){if(x>=3)return void g();d.current=a=new WebSocket(c),a.onopen=()=>{x=0,f()},a.onmessage=e=>{try{if(h.current!==n)return;let t=JSON.parse(e.data);if("kline"!==t.e)return;let a=t.k,s={time:Math.floor(a.t/1e3),open:parseFloat(a.o),high:parseFloat(a.h),low:parseFloat(a.l),close:parseFloat(a.c),volume:parseFloat(a.v),openTimeMs:a.t};l(s),a.x&&r(e=>{let t=[...e],a=t.findIndex(e=>e.time===s.time);return a>=0?t[a]=s:t.push(s),t})}catch{}},a.onclose=()=>{m&&(++x>=3?g():s=setTimeout(e,3e3))},a.onerror=()=>{a.close()}}}(),()=>{m=!1,clearTimeout(s),f(),d.current&&(d.current.close(),d.current=null)}},[e,t,p]),(0,_.useEffect)(()=>{let a=`${e}:${t}`;async function s(){if("u"<typeof document||!document.hidden)try{let s=F[e]||`${e}USDT`,n=P[t]||"5m",l=`/api/binance/klines?symbol=${s}&interval=${n}&limit=5&_t=${Date.now()}`,i=await fetch(l,{cache:"no-store"});if(!i.ok)return;let o=await i.json();if(!Array.isArray(o)||!o.length||h.current!==a)return;let c=o.map(e=>({time:Math.floor(e[0]/1e3),open:parseFloat(e[1]),high:parseFloat(e[2]),low:parseFloat(e[3]),close:parseFloat(e[4]),volume:parseFloat(e[5]),openTimeMs:e[0]}));r(e=>{if(!e.length)return c;let t=[...e];for(let e of c){let a=t.findIndex(t=>t.time===e.time);a>=0?t[a]=e:t.push(e)}return t.sort((e,t)=>e.time-t.time),O(t)})}catch{}}s();let n=setInterval(s,2e4),l=()=>{document.hidden||s()};return document.addEventListener("visibilitychange",l),()=>{clearInterval(n),document.removeEventListener("visibilitychange",l)}},[e,t]),{candles:s,realtimeCandle:n,error:i,reload:p,loadMore:m,loadBulk:(0,_.useCallback)(async(a=5)=>{let s=`${e}:${t}`,n=u.current;for(let r=0;r<a&&n.length;r++){let a=n[0].openTimeMs;if(!a)break;try{let r=await R(e,t,a-1);if(!r.length||h.current!==s)break;let l=[...r,...n];l.sort((e,t)=>e.time-t.time),n=O(l)}catch{break}}return h.current===s&&n.length>u.current.length&&r(n),n.length},[e,t])}}let I=["BTC","ETH","SOL"],D=["5m","15m","1h"],z={"5m":300,"15m":900,"1h":3600};function B(e,t){let a=z[t]||300;return Math.floor(e/a)*a}function W(e){let t=e.side?.toUpperCase()==="BUY",a=(e.outcome||"").toLowerCase(),s="down"===a||"no"===a;return s&&t||!s&&!t?{bullish:!1}:{bullish:t}}function U({trades:e,selectedMarket:t,highlightTradeId:a,onTradeHover:s}){let r=(0,_.useRef)(null),n=(0,_.useRef)(null),l=(0,_.useRef)(null),i=(0,_.useRef)(null),o=(0,_.useRef)(null),c=(0,_.useRef)(!1),[d,u]=(0,_.useState)(null),[h,p]=(0,_.useState)(null),m=(0,_.useMemo)(()=>{let e,a,s;return e=(t||"").toLowerCase(),a="BTC",e.includes("eth")||e.includes("ethereum")?a="ETH":(e.includes("sol")||e.includes("solana"))&&(a="SOL"),s="5m",e.includes("15m")||e.includes("-15m-")?s="15m":(e.includes("1h")||e.includes("up-or-down"))&&(s="1h"),{asset:a,tf:s}},[t]),[x,g]=(0,_.useState)(m.asset),[f,v]=(0,_.useState)(m.tf);(0,_.useEffect)(()=>{g(m.asset),v(m.tf),c.current=!1},[m.asset,m.tf]);let{candles:y,realtimeCandle:j,loadMore:w}=L(x,f),N=(0,_.useMemo)(()=>(function(e,t,a){let s=a?e.filter(e=>e.market_slug===a||e.condition_id===a):e,r=new Map;for(let e of s){if(!e.timestamp||e.timestamp<1e6)continue;let a=B(e.timestamp,t),s=r.get(a);s||(s={up:0,down:0},r.set(a,s));let{bullish:n}=W(e);n?s.up++:s.down++}let n=[];for(let[e,t]of r){let a=t.up>t.down,s=[];t.up>0&&s.push(`${t.up}↑`),t.down>0&&s.push(`${t.down}↓`);let r=s.join(" ");n.push({time:e,position:a?"belowBar":"aboveBar",color:a?"#00d4aa":"#ff4976",shape:a?"arrowUp":"arrowDown",text:r})}return n.sort((e,t)=>
1Number(e.time)-Number(t.time)),n})(e,f,t),[e,f,t]),k=(0,_.useMemo)(()=>{let a=new Map;for(let s of t?e.filter(e=>e.market_slug===t||e.condition_id===t):e){if(!s.timestamp||s.timestamp<1e6)continue;let e=B(s.timestamp,f),t=a.get(e);t||(t=[],a.set(e,t)),t.push(s)}return a},[e,f,t]),$=(0,_.useRef)(k);$.current=k;let C=(0,_.useRef)(N);C.current=N;let M=`${x}/USDT ${f}`;(0,_.useEffect)(()=>{if(!r.current)return;let e=(0,A.createChart)(r.current,{...(0,T.makeChartOptions)(400),autoSize:!0,handleScroll:!0,handleScale:!0}),t=e.addSeries(A.CandlestickSeries,{upColor:T.CHART_COLORS.candleUp,downColor:T.CHART_COLORS.candleDown,wickUpColor:T.CHART_COLORS.candleUp,wickDownColor:T.CHART_COLORS.candleDown,borderVisible:!1,priceLineVisible:!1}),a=e.addSeries(A.AreaSeries,{lineColor:T.CHART_COLORS.areaLine,topColor:T.CHART_COLORS.areaTop,bottomColor:T.CHART_COLORS.areaBottom,lineWidth:1,priceLineVisible:!1,lastValueVisible:!1});n.current=e,l.current=t,i.current=a,e.subscribeCrosshairMove(e=>{e?.time&&e.seriesData?u(e.seriesData.get(t)||null):u(null)}),e.subscribeClick(e=>{if(!e?.time||!e.point)return void p(null);let t=Number(e.time),a=$.current.get(t);a&&0!==a.length?p({x:e.point.x,y:e.point.y,trades:a}):p(null)});let s=new ResizeObserver(()=>{e.applyOptions({width:r.current.clientWidth})});return s.observe(r.current),()=>{s.disconnect(),e.remove(),n.current=null,l.current=null,i.current=null,o.current=null,c.current=!1}},[]),(0,_.useEffect)(()=>{if(!n.current)return;let e=n.current.timeScale(),t=e=>{e&&e.from<10&&w()};return e.subscribeVisibleLogicalRangeChange(t),()=>e.unsubscribeVisibleLogicalRangeChange(t)},[w]),(0,_.useEffect)(()=>{if(!l.current||!i.current||0===y.length)return;l.current.setData(y);let e=y.map(e=>({time:e.time,value:e.close}));i.current.setData(e);let t=C.current;t.length>0?o.current?o.current.setMarkers(t):o.current=(0,A.createSeriesMarkers)(l.current,t):o.current&&o.current.setMarkers([]),n.current&&!c.current&&(n.current.timeScale().fitContent(),c.current=!0)},[y]),(0,_.useEffect)(()=>{l.current&&(N.length>0?o.current?o.current.setMarkers(N):o.current=(0,A.createSeriesMarkers)(l.current,N):o.current&&o.current.setMarkers([]))},[N]),(0,_.useEffect)(()=>{j&&l.current&&i.current&&(l.current.update(j),i.current.update({time:j.time,value:j.close}))},[j]);let E=j||(y.length?y[y.length-1]:null),F=d||E;return(0,b.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%"},children:[(0,b.jsxs)("div",{className:"primary-chart-head",children:[(0,b.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,b.jsx)("span",{className:"primary-chart-title",children:M}),(0,b.jsxs)("div",{className:"trader-chart-pills",children:[I.map(e=>(0,b.jsx)("button",{className:`trader-chart-pill${x===e?" active":""}`,onClick:()=>{g(e),c.current=!1,p(null)},children:e},e)),(0,b.jsx)("span",{className:"trader-chart-pill-sep"}),D.map(e=>(0,b.jsx)("button",{className:`trader-chart-pill${f===e?" active":""}`,onClick:()=>{v(e),c.current=!1,p(null)},children:e},e))]}),(0,b.jsxs)("span",{style:{fontSize:"var(--fs-xs)",color:"var(--text-tertiary)"},children:[N.length," trades overlaid"]})]}),F&&(0,b.jsxs)("div",{className:"primary-chart-ohlc",children:[(0,b.jsxs)("span",{children:[(0,b.jsx)("span",{children:"O"})," ",(0,S.fmtFloat)(F?.open,F?.open>=100?2:4)]}),(0,b.jsxs)("span",{children:[(0,b.jsx)("span",{children:"H"})," ",(0,S.fmtFloat)(F?.high,F?.high>=100?2:4)]}),(0,b.jsxs)("span",{children:[(0,b.jsx)("span",{children:"L"})," ",(0,S.fmtFloat)(F?.low,F?.low>=100?2:4)]}),(0,b.jsxs)("span",{children:[(0,b.jsx)("span",{children:"C"})," ",(0,S.fmtFloat)(F?.close,F?.close>=100?2:4)]})]})]}),(0,b.jsxs)("div",{style:{position:"relative",flex:1},children:[(0,b.jsx)("div",{ref:r,className:"primary-chart-container"}),h&&(0,b.jsxs)("div",{className:"trader-chart-popup",style:{left:Math.min(h.x,(r.current?.clientWidth||400)-260),top:Math.max(0,h.y-20)},children:[(0,b.jsxs)("div",{className:"trader-chart-popup-head",children:[(0,b.jsxs)("span",{children:[h.trades.length," trade",h.trades.length>1?"s":""," on this candle"]}),(0,b.jsx)("button",{onClick:()=>p(null),children:"×"})]}),(0,b.jsx)("div",{className:"trader-chart-popup-body",children:h.trades.map((e,t)=>{let{bullish:a}=W(e),s=e.size||0,r=e.price||0,n=new Date(1e3*e.timestamp).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"}),l=e.resolved&&null!=e.pnl,i=e.pnl||0;return(0,b.jsxs)("div",{className:"trader-chart-popup-trade",children:[(0,b.jsxs)("div",{className:"trader-chart-popup-row",children:[(0,b.jsxs)("span",{className:"trader-chart-popup-dir",style:{color:a?"#00d4aa":"#ff4976"},children:[a?"▲":"▼"," ",a?"Up":"Down"]}),(0,b.jsxs)("span",{className:"trader-chart-popup-label",children:[(0,S.fmtFloat)(s,1)," shares @ ",(0,S.fmtFloat)(r,2)]}),(0,b.jsx)("span",{className:"trader-chart-popup-time",children:n})]}),(0,b.jsxs)("div",{className:"trader-chart-popup-pnl-row",children:[(0,b.jsxs)("span",{className:"trader-chart-popup-cost",children:["Cost ",(0,S.fmtUsd)(s*r)]}),l?(0,b.jsxs)("span",{className:`trader-chart-popup-pnl ${i>=0?"win":"loss"}`,children:["PnL ",i>=0?"+":"",(0,S.fmtUsd)(i)]}):(0,b.jsx)("span",{className:"trader-chart-popup-pnl open",children:"Open"})]})]},e.trade_id||t)})})]})]})]})}function H({trades:e,total:t,loading:a,highlightTradeId:s,onTradeClick:r}){return(0,b.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%"},children:[(0,b.jsxs)("div",{className:"panel-header",children:[(0,b.jsx)("span",{className:"panel-title",children:"Trade Journal"}),(0,b.jsxs)("span",{className:"panel-subtitle",children:[e.length,t>e.length?` / ${t}`:""," trades",a&&" ..."]})]}),0===e.length?(0,b.jsx)("div",{className:"empty-state",children:a?"Loading trades...":"No trades found"}):(0,b.jsx)("div",{className:"data-table-wrap",children:(0,b.jsxs)("table",{className:"data-table",children:[(0,b.jsx)("thead",{children:(0,b.jsxs)("tr",{children:[(0,b.jsx)("th",{style:{width:130},children:"Time"}),(0,b.jsx)("th",{style:{width:140},children:"Market"}),(0,b.jsx)("th",{style:{width:60},children:"Outcome"}),(0,b.jsx)("th",{style:{width:45},children:"Side"}),(0,b.jsx)("th",{style:{width:70},children:"Size"}),(0,b.jsx)("th",{style:{width:60},children:"Price"}),(0,b.jsx)("th",{style:{width:80},children:"PnL"})]})}),(0,b.jsx)("tbody",{children:e.map((e,t)=>{let a=e.side?.toUpperCase()==="BUY",n=s===e.trade_id;return(0,b.jsxs)("tr",{className:`${n?"highlighted":""} clickable`,onClick:()=>r?.(e),children:[(0,b.jsx)("td",{children:function(e){if(!e||e<1e6)return"-";let t=new Date(1e3*e),a=String(t.getUTCMonth()+1).padStart(2,"0"),s=String(t.getUTCDate()).padStart(2,"0"),r=String(t.getUTCHours()).padStart(2,"0"),n=String(t.getUTCMinutes()).padStart(2,"0"),l=String(t.getUTCSeconds()).padStart(2,"0");return`${a}/${s} ${r}:${n}:${l}`}(e.timestamp)}),(0,b.jsx)("td",{title:e.market_slug,children:function(e){if(!e)return"-";let t=e.toLowerCase(),a="";if(t.includes("btc")||t.includes("bitcoin")?a="BTC":t.includes("eth")||t.includes("ethereum")?a="ETH":(t.includes("sol")||t.includes("solana"))&&(a="SOL"),a){let e="";if(t.includes("15m")?e="15m":t.includes("5m")?e="5m":(t.includes("1h")||t.includes("up-or-down"))&&(e="1h"),e)return`${a} ${e}`}return e.length>20?e.slice(0,18)+"...":e}(e.market_slug||e.condition_id)}),(0,b.jsx)("td",{children:e.outcome||"-"}),(0,b.jsx)("td",{className:a?"up":"down",children:e.side?.toUpperCase()||"-"}),(0,b.jsx)("td",{children:(0,S.fmtUsd)(e.size,2)}),(0,b.jsx)("td",{children:(0,S.fmtFloat)(e.price,4)}),(0,b.jsx)("td",{className:null!=e.pnl?e.pnl>=0?"up":"down":"",children:null!=e.pnl?`${e.pnl>=0?"+":""}${(0,S.fmtUsd)(e.pnl)}`:e.resolved?"$0.00":"-"})]},e.trade_id||t)})})]})})]})}let q=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],V=Array.from({length:24},(e,t)=>t.toString().padStart(2,"0"));function G({heatmap:e}){let t=Math.max(1,...e.flat());return(0,b.jsxs)("div",{className:"pattern-heatmap",children:[(0,b.jsxs)("div",{className:"pattern-heatmap-header",children:[(0,b.jsx)("span",{className:"pattern-heatmap-corner"}),V.filter((e,t)=>
1t%3==0).map(e=>(0,b.jsx)("span",{className:"pattern-heatmap-hour",children:e},e))]}),e.map((e,a)=>(0,b.jsxs)("div",{className:"pattern-heatmap-row",children:[(0,b.jsx)("span",{className:"pattern-heatmap-day",children:q[a]}),e.map((e,s)=>(0,b.jsx)("span",{className:"pattern-heatmap-cell",style:{backgroundColor:`rgba(59, 130, 246, ${e/t*.8+.05})`},title:`${q[a]} ${V[s]}:00 — ${e} trades`},s))]},a))]})}function J({buckets:e}){let t=Math.max(1,...e.map(e=>e.count));return(0,b.jsx)("div",{className:"pattern-histogram",children:e.map((e,a)=>(0,b.jsxs)("div",{className:"pattern-histogram-bar-wrap",children:[(0,b.jsx)("div",{className:"pattern-histogram-bar",style:{height:`${Math.max(2,e.count/t*100)}%`}}),(0,b.jsxs)("span",{className:"pattern-histogram-label",children:["$",(0,S.fmtFloat)(e.range_lo,0)]})]},a))})}function Y({buckets:e}){let t=Math.max(1,...e.map(e=>e.count));return(0,b.jsx)("div",{className:"pattern-histogram",children:e.map((e,a)=>(0,b.jsxs)("div",{className:"pattern-histogram-bar-wrap",children:[(0,b.jsx)("div",{className:"pattern-histogram-bar entry",style:{height:`${Math.max(2,e.count/t*100)}%`}}),(0,b.jsx)("span",{className:"pattern-histogram-label",children:(0,S.fmtFloat)(e.range_lo,1)})]},a))})}function K({patterns:e,loading:t}){if(!e&&!t)return(0,b.jsxs)("div",{className:"pattern-summary",children:[(0,b.jsx)("div",{className:"panel-header",children:(0,b.jsx)("span",{className:"panel-title",children:"Pattern Analysis"})}),(0,b.jsx)("div",{className:"empty-state",children:"Analyze a trader to see patterns"})]});if(t&&!e)return(0,b.jsxs)("div",{className:"pattern-summary",children:[(0,b.jsx)("div",{className:"panel-header",children:(0,b.jsx)("span",{className:"panel-title",children:"Pattern Analysis"})}),(0,b.jsx)("div",{className:"empty-state",children:"Detecting patterns..."})]});if(!e)return null;let{timing:a,sizing:s,entry_exit:r,reaction_speed:n}=e;return(0,b.jsxs)("div",{className:"pattern-summary",children:[(0,b.jsx)("div",{className:"panel-header",children:(0,b.jsx)("span",{className:"panel-title",children:"Pattern Analysis"})}),(0,b.jsxs)("div",{className:"pattern-summary-content",children:[(0,b.jsxs)("div",{className:"pattern-section",children:[(0,b.jsxs)("div",{className:"pattern-section-title",children:["Trading Activity (UTC)",(0,b.jsxs)("span",{className:"pattern-section-detail",children:["Peak: ",a.peak_day," ",a.peak_hour,":00"]})]}),(0,b.jsx)(G,{heatmap:a.heatmap})]}),s.size_buckets.length>0&&(0,b.jsxs)("div",{className:"pattern-section",children:[(0,b.jsxs)("div",{className:"pattern-section-title",children:["Position Sizing",(0,b.jsxs)("span",{className:"pattern-section-detail",children:[s.fixed_size?"Fixed":"Variable"," | Avg $",(0,S.fmtFloat)(s.mean_size,0)," | CV ",(0,S.fmtFloat)(s.cv,2)]})]}),(0,b.jsx)(J,{buckets:s.size_buckets})]}),r.entry_price_buckets.length>0&&(0,b.jsxs)("div",{className:"pattern-section",children:[(0,b.jsxs)("div",{className:"pattern-section-title",children:["Entry Prices",(0,b.jsxs)("span",{className:"pattern-section-detail",children:["Avg ",(0,S.fmtFloat)(r.avg_entry_price,3)," |"," ",r.is_contrarian?"Contrarian":"Momentum"," |"," ","Hold-to-Res ",(0,S.fmtPct)(100*r.hold_to_resolution_ratio,0)]})]}),(0,b.jsx)(Y,{buckets:r.entry_price_buckets})]}),(0,b.jsx)("div",{className:"pattern-section",children:(0,b.jsxs)("div",{className:"pattern-quick-stats",children:[(0,b.jsxs)("div",{className:"pattern-quick-stat",children:[(0,b.jsx)("span",{className:"label",children:"Buys"}),(0,b.jsx)("span",{className:"up",children:r.buy_count})]}),(0,b.jsxs)("div",{className:"pattern-quick-stat",children:[(0,b.jsx)("span",{className:"label",children:"Sells"}),(0,b.jsx)("span",{className:"down",children:r.sell_count})]}),(0,b.jsxs)("div",{className:"pattern-quick-stat",children:[(0,b.jsx)("span",{className:"label",children:"Avg Fill"}),(0,b.jsxs)("span",{children:[(0,S.fmtFloat)(n.avg_fill_interval_sec,0),"s"]})]}),(0,b.jsxs)("div",{className:"pattern-quick-stat",children:[(0,b.jsx)("span",{className:"label",children:"Multi-Leg"}),(0,b.jsx)("span",{children:n.multi_leg_fills})]}),(0,b.jsxs)("div",{className:"pattern-quick-stat",children:[(0,b.jsx)("span",{className:"label",children:"Bursts"}),(0,b.jsx)("span",{children:a.burst_count})]})]})})]})]})}function X({indicator:e}){let t=Math.min(Math.abs(e.effect_size),3),a="higher"===e.direction;return(0,b.jsxs)("div",{className:"re-indicator-row",children:[(0,b.jsx)("div",{className:"re-indicator-name",title:e.indicator,children:e.indicator}),(0,b.jsx)("div",{className:"re-indicator-bar-wrap",children:(0,b.jsx)("div",{className:`re-indicator-bar ${a?"re-bar-bullish":"re-bar-bearish"}`,style:{width:`${Math.max(t/3*100,8)}%`}})}),(0,b.jsxs)("div",{className:"re-indicator-stats",children:[(0,b.jsxs)("span",{className:"re-indicator-pval",children:["p=",e.p_value<.001?"<.001":e.p_value.toFixed(3)]}),(0,b.jsxs)("span",{className:`re-indicator-effect ${a?"text-long":"text-short"}`,children:["d=",(0,S.fmtFloat)(e.effect_size,2)]})]})]})}function Z({match:e,rank:t}){let a=Math.round(100*e.confidence);return(0,b.jsxs)("div",{className:`re-strategy-card ${0===t?"re-strategy-best":""}`,children:[(0,b.jsxs)("div",{className:"re-strategy-header",children:[(0,b.jsxs)("span",{className:"re-strategy-rank",children:["#",t+1]}),(0,b.jsx)("span",{className:"re-strategy-name",children:e.strategy_name}),(0,b.jsx)("span",{className:"re-strategy-category",children:e.category}),(0,b.jsxs)("span",{className:"re-strategy-confidence",children:[a,"%"]})]}),(0,b.jsx)("div",{className:"re-strategy-desc",children:e.description}),(0,b.jsxs)("div",{className:"re-strategy-meta",children:[(0,b.jsxs)("span",{children:["Coverage: ",(0,S.fmtPct)(100*e.indicator_coverage)]}),(0,b.jsxs)("span",{children:["Fire rate: ",(0,S.fmtPct)(100*e.signal_fire_rate)]}),(0,b.jsxs)("span",{children:["Effect: ",(0,S.fmtFloat)(e.avg_effect_size,2)]})]}),e.present_indicators.length>0&&(0,b.jsxs)("div",{className:"re-strategy-indicators",children:[e.present_indicators.map(e=>(0,b.jsx)("span",{className:"re-indicator-tag re-tag-present",children:e},e)),e.missing_indicators.map(e=>(0,b.jsx)("span",{className:"re-indicator-tag re-tag-missing",children:e},e))]})]})}function Q({result:e}){return(0,b.jsxs)("div",{className:"re-fitted-card",children:[(0,b.jsxs)("div",{className:"re-fitted-header",children:[(0,b.jsx)("span",{className:"re-fitted-name",children:e.strategy_name}),(0,b.jsxs)("span",{className:"re-fitted-f1",children:["F1=",(0,S.fmtFloat)(e.f1,3)]})]}),(0,b.jsx)("div",{className:"re-fitted-params",children:Object.entries(e.fitted_params).map(([e,t])=>(0,b.jsxs)("span",{className:"re-param-chip",children:[e,"=","number"==typeof t?(0,S.fmtFloat)(t,1):t]},e))}),(0,b.jsxs)("div",{className:"re-fitted-metrics",children:[(0,b.jsxs)("span",{children:["Pre
1cision: ",(0,S.fmtPct)(100*e.precision)]}),(0,b.jsxs)("span",{children:["Recall: ",(0,S.fmtPct)(100*e.recall)]}),(0,b.jsxs)("span",{children:["Hits: ",e.true_positives,"/",e.total_actual_trades]})]})]})}function ee({validation:e}){let t=Math.round(100*e.explanation_rate),a=2*Math.PI*40,s=a*(1-e.explanation_rate);return(0,b.jsxs)("div",{className:"re-validation",children:[(0,b.jsx)("div",{className:"re-gauge-wrap",children:(0,b.jsxs)("svg",{viewBox:"0 0 100 100",className:"re-gauge-svg",children:[(0,b.jsx)("circle",{cx:"50",cy:"50",r:"40",fill:"none",stroke:"var(--border-subtle)",strokeWidth:"8"}),(0,b.jsx)("circle",{cx:"50",cy:"50",r:"40",fill:"none",stroke:t>=70?"var(--color-long)":t>=40?"var(--color-warning, #f59e0b)":"var(--color-short)",strokeWidth:"8",strokeDasharray:a,strokeDashoffset:s,strokeLinecap:"round",transform:"rotate(-90 50 50)"}),(0,b.jsxs)("text",{x:"50",y:"50",textAnchor:"middle",dominantBaseline:"central",className:"re-gauge-text",children:[t,"%"]})]})}),(0,b.jsxs)("div",{className:"re-validation-stats",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{className:"re-val-label",children:"Explained"}),(0,b.jsxs)("span",{className:"re-val-value",children:[e.matched,"/",e.total_actual]})]}),(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{className:"re-val-label",children:"Precision"}),(0,b.jsx)("span",{className:"re-val-value",children:(0,S.fmtPct)(100*e.precision)})]}),(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{className:"re-val-label",children:"Recall"}),(0,b.jsx)("span",{className:"re-val-value",children:(0,S.fmtPct)(100*e.recall)})]}),(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{className:"re-val-label",children:"F1 Score"}),(0,b.jsx)("span",{className:"re-val-value",children:(0,S.fmtFloat)(e.f1,3)})]})]})]})}function et({stage:e,significantIndicators:t,strategies:a,fitted:s,validation:r,summary:n,loading:l,error:i,onAnalyze:o}){return t.length>0||a||n||l||i?(0,b.jsxs)("div",{className:"re-panel",children:[l&&e&&(0,b.jsxs)("div",{className:"re-stage",children:[(0,b.jsx)("span",{className:"re-stage-dot"}),e.message]}),i&&(0,b.jsx)("div",{className:"re-error",children:i}),t.length>0&&(0,b.jsxs)("div",{className:"re-section",children:[(0,b.jsxs)("div",{className:"re-section-title",children:["Significant Indicators",(0,b.jsx)("span",{className:"re-section-count",children:t.length})]}),(0,b.jsx)("div",{className:"re-indicator-list",children:t.slice(0,15).map(e=>(0,b.jsx)(X,{indicator:e},e.indicator))})]}),a&&a.length>0&&(0,b.jsxs)("div",{className:"re-section",children:[(0,b.jsx)("div",{className:"re-section-title",children:"Strategy Match"}),(0,b.jsx)("div",{className:"re-strategy-list",children:a.slice(0,5).map((e,t)=>(0,b.jsx)(Z,{match:e,rank:t},e.strategy_key))})]}),s&&s.length>0&&(0,b.jsxs)("div",{className:"re-section",children:[(0,b.jsx)("div",{className:"re-section-title",children:"Fitted Parameters"}),s.map(e=>(0,b.jsx)(Q,{result:e},e.strategy_key))]}),r&&(0,b.jsxs)("div",{className:"re-section",children:[(0,b.jsx)("div",{className:"re-section-title",children:"Validation Score"}),(0,b.jsx)(ee,{validation:r})]}),n&&(0,b.jsxs)("div",{className:"re-section",children:[(0,b.jsx)("div",{className:"re-section-title",children:"AI Summary"}),(0,b.jsx)("div",{className:"re-summary",children:n})]}),!l&&o&&(0,b.jsx)("button",{className:"re-analyze-btn re-reanalyze",onClick:()=>o("BTC","15m"),children:"Re-analyze"})]}):(0,b.jsxs)("div",{className:"re-panel re-empty",children:[(0,b.jsx)("div",{className:"re-empty-title",children:"Strategy Reverse Engineering"}),(0,b.jsx)("div",{className:"re-empty-desc",children:"Analyze which indicators and strategies explain this trader's behavior. Tests 130+ technical indicators against trade entry times."}),o&&(0,b.jsx)("button",{className:"re-analyze-btn",onClick:()=>o("BTC","15m"),children:"Reverse Engineer Strategy"})]})}function ea(){let[e,t]=(0,_.useState)(""),[a,s]=(0,_.useState)(null),[r,n]=(0,_.useState)(""),[l,i]=(0,_.useState)(null),{stage:o,tradeInfo:c,classification:d,stats:u,equityCurveTrader:h,patterns:p,loading:m,error:x,analyze:g,clear:f}=function(){let[e,t]=(0,_.useState)(null),[a,s]=(0,_.useState)(null),[r,n]=(0,_.useState)(null),[l,i]=(0,_.useState)(null),[o,c]=(0,_.useState)(null),[d,u]=(0,_.useState)(null),[h,p]=(0,_.useState)(null),[m,x]=(0,_.useState)(null),[g,f]=(0,_.useState)(null),[b,v]=(0,_.useState)(!1),[j,w]=(0,_.useState)(null),N=(0,_.useRef)(null);return{stage:e,tradeInfo:a,classification:r,stats:l,simulations:o,recommended:d,meta:h,equityCurveTrader:m,patterns:g,loading:b,error:j,analyze:(0,_.useCallback)(async(e,a=1e4)=>{if(!e)return;N.current&&N.current.abort(),v(!0),w(null),t(null),s(null),n(null),i(null),c(null),u(null),p(null),x(null),f(null);let r=new AbortController;N.current=r;
1try{let l=`${y.API_BASE}/api/vault/analyze-trader?user=${encodeURIComponent(e)}&tvl=${a}`,o=await fetch(l,{signal:r.signal});if(!o.ok){let e=await o.text();throw Error(`${o.status}: ${e}`)}let d=o.body.getReader(),h=new TextDecoder,m="",g=e=>{let a;if(!e.startsWith("data: "))return!1;let r=e.slice(6).trim();if(!r)return!1;try{a=JSON.parse(r)}catch{return!1}switch(a.type){case"stage":t({stage:a.stage,message:a.message});break;case"trades_fetched":s({trade_count:a.trade_count,market_count:a.market_count,period_days:a.period_days,data_from_ts:a.data_from_ts??0,data_to_ts:a.data_to_ts??0});break;case"classification":n({classification:a.classification,classification_score:a.classification_score});break;case"stats":i(a.stats);break;case"simulations":c(a.simulations),u(a.recommended),p(a.meta),x(a.equity_curve_trader);break;case"patterns":f({timing:a.timing,sizing:a.sizing,market_selection:a.market_selection,entry_exit:a.entry_exit,reaction_speed:a.reaction_speed,badges:a.badges||[]});break;case"done":return!0}return!1},b=!1;for(;!b;){let{done:e,value:t}=await d.read();if(e)break;let a=(m+=h.decode(t,{stream:!0})).split("\n");for(let e of(m=a.pop()||"",a))if(g(e)){b=!0;break}}if(!b&&m.trim()){for(let e of m.split("\n"))if(g(e))break}}catch(e){"AbortError"!==e.name&&w(e.message)}finally{v(!1),N.current=null}},[]),clear:(0,_.useCallback)(()=>{N.current&&N.current.abort(),t(null),s(null),n(null),i(null),c(null),u(null),p(null),x(null),f(null),w(null),v(!1)},[])}}(),{trades:v,total:j,loading:w,fetchTrades:N}=function(){let[e,t]=(0,_.useState)([]),[a,s]=(0,_.useState)(0),[r,n]=(0,_.useState)(!1);return{trades:e,total:a,loading:r,fetchTrades:(0,_.useCallback)(async(e,a=500,r=0)=>{if(e){n(!0);try{let n=await fetch(`${y.API_BASE}/api/trader/${encodeURIComponent(e)}/trades?limit=${a}&offset=${r}`);if(!n.ok)throw Error(`${n.status}`);let l=await n.json();t(l.trades||[]),s(l.total||0)}catch{}finally{n(!1)}}},[])}}(),k=function(){let[e,t]=(0,_.useState)(null),[a,s]=(0,_.useState)([]),[r,n]=(0,_.useState)(null),[l,i]=(0,_.useState)(null),[o,c]=(0,_.useState)(null),[d,u]=(0,_.useState)(null),[h,p]=(0,_.useState)(!1),[m,x]=(0,_.useState)(null),g=(0,_.useRef)(null);return{stage:e,significantIndicators:a,strategies:r,fitted:l,validation:o,summary:d,loading:h,error:m,analyze:(0,_.useCallback)(async(e,a="BTC",r="15m")=>{if(!e)return;g.current&&g.current.abort(),p(!0),x(null),t(null),s([]),n(null),i(null),c(null),u(null);let l=new AbortController;g.current=l;try{let o=`${y.API_BASE}/api/trader/${encodeURIComponent(e)}/reverse-engineer?asset=${a}&tf=${r}`,d=await fetch(o,{signal:l.signal});if(!d.ok){let e=await d.text();throw Error(`${d.status}: ${e}`)}let h=d.body.getReader(),p=new TextDecoder,m="",g=[],f=e=>{let a;if(!e.startsWith("data: "))return!1;let r=e.slice(6).trim();if(!r)return!1;try{a=JSON.parse(r)}catch{return!1}switch(a.type){case"re_stage":t({stage:a.stage,message:a.message}),"error"===a.stage&&x(a.message);break;case"re_significant":g.push(a),s([...g]);break;case"re_strategies":n(a.strategies);break;case"re_fitted":i(a.fitted);break;case"re_validation":c(a);break;case"re_summary":u(a.summary);break;case"done":return!0}return!1},b=!1;for(;!b;){let{done:e,value:t}=await h.read();if(e)break;let a=(m+=p.decode(t,{stream:!0})).split("\n");for(let e of(m=a.pop()||"",a))if(f(e)){b=!0;break}}if(!b&&m.trim()){for(let e of m.split("\n"))if(f(e))break}}catch(e){"AbortError"!==e.name&&x(e.message)}finally{p(!1),g.current=null}},[]),clear:(0,_.useCallback)(()=>{g.current&&g.current.abort(),t(null),s([]),n(null),i(null),c(null),u(null),x(null),p(!1)},[])}}(),S=(0,_.useCallback)((t,a)=>{e&&k.analyze(e,t,a)},[e,k.analyze]),C=(0,_.useCallback)((e,a)=>{f(),k.clear(),t(e),s(a||null),n(""),i(null),g(e),N(e)},[g,N,f,k.clear]),M=(0,_.useCallback)(e=>{n(e)},[]),A=(0,_.useCallback)(e=>{i(e.trade_id);let t=e.market_slug||e.condition_id;t&&n(t)},[]),T=p?.market_selection?.top_markets||null;return(0,b.jsxs)("div",{className:"trader-intel-view",children:[(0,b.jsxs)("div",{className:"trader-intel-topbar",children:[(0,b.jsx)($,{onSelect:C}),m&&o&&(0,b.jsxs)("div",{className:"trader-intel-stage",children:[(0,b.jsx)("span",{className:"trader-intel-stage-dot"}),o.message]}),x&&(0,b.jsx)("div",{className:"trader-intel-error",children:x})]}),(0,b.jsxs)("div",{className:"trader-intel-body",children:[(0,b.jsxs)("div",{className:"trader-intel-main",children:[(0,b.jsx)("div",{className:"trader-intel-chart",children:(0,b.jsx)(U,{trades:v,selectedMarket:r,highlightTradeId:l})}),(0,b.jsxs)("div",{className:"trader-intel-bottom",children:[(0,b.jsx)("div",{className:"trader-intel-journal",children:(0,b.jsx)(H,{trades:v,total:j,loading:w,highlightTradeId:l,onTradeClick:A})}),(0,b.jsx)("div",{className:"trader-intel-patterns",children:(0,b.jsx)(K,{patterns:p,loading:m})}),(0,b.jsx)("div",{className:"trader-intel-reverse",children:(0,b.jsx)(et,{stage:k.stage,significantIndicators:k.significantIndicators,strategies:k.strategies,fitted:k.fitted,validation:k.validation,summary:k.summary,loading:k.loading,error:k.error,onAnalyze:e?S:void 0})})]})]}),(0,b.jsx)("div",{className:"trader-intel-sidebar",children:(0,b.jsx)(E,{wallet:e,profile:a,classification:d,stats:u,patterns:p,equityCurve:h,topMarkets:T,onMarketClick:M,loading:m})})]})]})}var es=e.i(83055),er=e.i(767);let en={asset:"ETH",tf:"15m",hourset:[],streak:4,exact:!1,trigger_mode:"both",multipliers:[1,1,2,4],base_usd:50,initial_equity:2e3,entry_price:.55,confidence_min_score:null,strategy_name:"",use_clob:!1,clob_entry_mode:"open",max_spread:null,min_depth:null};function el({sessions:e,activeId:t,loading:a,onSelect:s,onCreate:r,onRename:n,onDelete:l}){let[i,o]=(0,_.useState)(null),[c,d]=(0,_.useState)(""),u=(0,_.useRef)(null),h=(0,_.useCallback)((e,t)=>{o(e),d(t),setTimeout(()=>u.current?.select(),0)},[]),p=(0,_.useCallback)(()=>{i&&c.trim()&&n(i,c.trim()),o(null)},[i,c,n]),m=(0,_.useCallback)((e,t)=>{e.stopPropagation(),confirm("Delete this algo session?")&&l(t)},[l]);return(0,b.jsxs)("div",{className:"algo-sidebar",children:[(0,b.jsxs)("div",{className:"algo-sidebar-header",children:[(0,b.jsx)("span",{className:"algo-sidebar-title",children:"Algos"}),(0,b.jsx)("button",{className:"algo-sidebar-new-btn",onClick:r,children:"+ New"})]}),(0,b.jsx)("div",{className:"algo-sidebar-list",children:a?(0,b.jsx)("div",{className:"algo-sidebar-skeleton",children:[0,1,2].map(e=>(0,b.jsxs)("div",{className:"algo-sidebar-skeleton-item",children:[(0,b.jsx)("div",{className:"algo-sidebar-skeleton-line",style:{width:"70%"}}),(0,b.jsx)("div",{className:"algo-sidebar-skeleton-line",style:{width:"50%"}})]},e))}):0===e.length?(0,b.jsxs)("div",{className:"algo-sidebar-empty",children:[(0,b.jsx)("p",{children:"No algos yet"}),(0,b.jsx)("p",{className:"algo-sidebar-empty-hint",children:'Click "+ New" to create your first algo'})]}):e.map(e=>{var a;return(0,b.jsxs)("div",{className:`algo-sidebar-item ${e.id===t?"active":""}`,onClick:()=>s(e.id),children:[(0,b.jsxs)("div",{className:"algo-sidebar-item-top",children:[(0,b.jsx)("span",{className:`algo-status-dot ${(a=e.status).includes("running")?"running":a.includes("stopped")?"stopped":"draft"}`}),i===e.id?(0,b.jsx)("input",{ref:u,className:"algo-sidebar-rename-input",value:c,onChange:e=>d(e.target.value),onBlur:p,onKeyDown:e=>{"Enter"===e.key&&p(),"Escape"===e.key&&o(null)},onClick:e=>e.stopPropagation()}):(0,b.jsx)("span",{className:"algo-sidebar-item-name",onDoubleClick:t=>{t.stopPropagation(),h(e.id,e.name)},children:e.name})]}),(e.market_question||e.strategy_name)&&(0,b.jsx)("div",{className:"algo-sidebar-item-meta",children:e.market_question||e.strategy_name}),(0,b.jsxs)("div",{className:"algo-sidebar-item-bottom",children:[(0,b.jsx)("span",{className:"algo-sidebar-item-time",children:function(e){let t=Math.floor((Date.now()-new Date(e).getTime())/6e4);if(t<1)return"just now";if(t<60)return`${t}m ago`;let a=Math.floor(t/60);if(a<24)return`${a}h ago`;let s=Math.floor(a/24);return s<7?`${s}d ago`:new Date(e).toLocaleDateString()}(e.updated_at)}),(0,b.jsxs)("div",{className:"algo-sidebar-item-actions",children:[(0,b.jsx)("button",{onClick:t=>{t.stopPropagation(),h(e.id,e.name)},title:"Rename",children:"✎"}),(0,b.jsx)("button",{onClick:t=>m(t,e.id),title:"Delete",children:"✕"})]})]})]},e.id)})})]})}var ei=e.i(34728),eo=e.i(97610),ec=e.i(83573),ed=e.i(30789),eu=e.i(73511),eh=e.i(67171);function ep({isRunning:e,mode:t,onModeChange:a,onPlay:s,onStop:r,disabled:n=!1}){let[l,i]=(0,_.useState)(!1),o=(0,_.useCallback)(()=>{e||("paper"===t?i(!0):a("paper"))},[t,e,a]),c=(0,_.useCallback)(()=>{a("live"),i(!1)},[a]);return(0,b.jsxs)("div",{className:"play-stop-control",children:[(0,b.jsxs)("div",{className:"play-stop-mode-toggle",children:[(0,b.jsx)("button",{className:`play-stop-mode-btn ${"paper"===t?"active":""}`,onClick:()=>!e&&a("paper"),disabled:e,children:"Paper"}),(0,b.jsx)("button",{className:`play-stop-mode-btn ${"live"===t?"active":""}`,onClick:o,disabled:e,children:"Live"})]}),(0,b.jsxs)("button",{className:`play-stop-btn ${e?"stop":"play"}`,onClick:e?r:s,disabled:n,children:[e?(0,b.jsx)(eh.Square,{size:14}):(0,b.jsx)(eu.Play,{size:14}),e?"Stop":"Play"]}),l&&(0,b.jsx)("div",{className:"play-stop-confirm-overlay",children:(0,b.jsxs)("div",{className:"play-stop-confirm",children:[(0,b.jsx)("p",{children:"Switch to Live mode? This will execute real trades with real money on Polymarket."}),(0,b.jsxs)("div",{className:"play-stop-confirm-actions",children:[(0,b.jsx)("button",{onClick:()=>i(!1),children:"Cancel"}),(0,b.jsx)("button",{className:"play-stop-confirm-yes",onClick:c,children:"Confirm Live"})]})]})})]})}var em=e.i(11376),ex=e.i(41627),eg=e.i(8034),ef=e.i(4435),eb=e.i(28609),e_=e.i(64575);function ev({message:e}){return(0,b.jsxs)("div",{className:"research-card vault-deployed-card",children:[(0,b.jsx)("div",{className:"research-card-header",children:(0,b.jsxs)("span",{className:"research-card-title",children:[(0,b.jsx)(e_.Box,{size:14}),"Vault Deployed"]})}),(0,b.jsx)("div",{className:"research-card-body",children:(0,b.jsx)("p",{className:"vault-deployed-msg",children:e})})]})}function ey({blocks:e,onSend:t}){return e&&0!==e.length?e.map((e,a)=>{switch(e.type){case"text":return(0,b.jsx)(ei.default,{content:e.content??""},a);case"tool":return(0,b.jsx)(ec.default,{tool:e},a);case"indicator":return(0,b.jsx)(ed.default,{indicator:e.indicator},a);case"market":return(0,b.jsx)(ej,{market:e.market},a);case"signal":return(0,b.jsx)(ew,{signal:e.signal},a);case"stage":default:return null;case"hourset_results":return(0,b.jsx)(em.default,{topResults:e.top_results,topPnl:e.top_pnl,qualifiedTotal:e.qualified_total},a);case"policy_results":return(0,b.jsx)(ex.default,{policies:e.policies},a);case"threshold_results":return(0,b.jsx)(eg.default,{results:e.results},a);case"campaign_results":return(0,b.jsx)(ef.default,{totalPnl:e.total_pnl,finalEquity:e.final_equity,maxDrawdown:e.max_drawdown,winCount:e.win_count,lossCount:e.loss_count,blown:e.blown,campaigns:e.campaigns},a);case"cnl_generated":return(0,b.jsx)(eb.default,{cnlText:e.cnl_text,onSend:t},a);case"vault_deployed":return(0,b.jsx)(ev,{message:e.message},a)}}):null}function ej({market:e}){return(0,b.jsxs)("div",{className:"chat-market-block",children:[(0,b.jsx)("div",{className:"chat-market-question",children:e.question||e.slug}
1),e.outcomes&&(0,b.jsx)("div",{className:"chat-market-outcomes",children:e.outcomes.map((t,a)=>{let s=e.prices?.[t];return(0,b.jsxs)("span",{className:"chat-market-outcome",children:[t,": ",null!=s?`${(100*s).toFixed(1)}%`:"—"]},a)})})]})}function ew({signal:e}){let t="BUY"===e.action;return(0,b.jsxs)("div",{className:`chat-signal-block ${t?"buy":"sell"}`,children:[(0,b.jsx)("span",{className:"chat-signal-action",children:e.action}),(0,b.jsx)("span",{className:"chat-signal-outcome",children:e.outcome}),(0,b.jsxs)("span",{className:"chat-signal-price",children:["@ ",e.price.toFixed(4)]})]})}function eN({messages:e,streaming:t,onSend:a,isRunning:s,mode:r,onModeChange:n,onPlay:l,onStop:i,playDisabled:o=!1,sessionName:c}){let d=(0,_.useRef)(null);(0,_.useEffect)(()=>{d.current&&(d.current.scrollTop=d.current.scrollHeight)},[e]);let u="Thinking...";if(t&&e.length>0){let t=e[e.length-1];if("assistant"===t.role&&t.blocks){let e=function(e){for(let t=e.length-1;t>=0;t--)if("stage"===e[t].type)return e[t].message;return null}(t.blocks);e&&(u=e)}}return(0,b.jsxs)("div",{className:"synth-chat-panel",children:[0===e.length?(0,b.jsxs)("div",{className:"synth-chat-empty",children:[(0,b.jsx)("h3",{children:c||"Strategy Synthesizer"}),(0,b.jsx)("p",{children:"Research, backtest, and deploy trading strategies with AI"}),(0,b.jsxs)("div",{className:"synth-suggestion-grid",children:[(0,b.jsxs)("button",{className:"synth-suggestion-card",onClick:()=>a("Research the best trading hours for ETH 15m streak-4"),children:[(0,b.jsx)("span",{className:"synth-suggestion-icon",children:"⏱"}),(0,b.jsx)("span",{children:"Research ETH hoursets"})]}),(0,b.jsxs)("button",{className:"synth-suggestion-card",onClick:()=>a("Optimize a BTC 15m trading strategy with full pipeline"),children:[(0,b.jsx)("span",{className:"synth-suggestion-icon",children:"⚙"}),(0,b.jsx)("span",{children:"Optimize BTC strategy"})]}),(0,b.jsxs)("button",{className:"synth-suggestion-card",onClick:()=>a("Run the full synthesis pipeline for SOL 15m"),children:[(0,b.jsx)("span",{className:"synth-suggestion-icon",children:"⚡"}),(0,b.jsx)("span",{children:"Full pipeline: SOL"})]}),(0,b.jsxs)("button",{className:"synth-suggestion-card",onClick:()=>a("Deploy my best strategy to a vault"),children:[(0,b.jsx)("span",{className:"synth-suggestion-icon",children:"📦"}),(0,b.jsx)("span",{children:"Deploy to vault"})]}),(0,b.jsxs)("button",{className:"synth-suggestion-card",onClick:()=>a("Start paper trading my latest strategy"),children:[(0,b.jsx)("span",{className:"synth-suggestion-icon",children:"▶"}),(0,b.jsx)("span",{children:"Paper trade"})]}),(0,b.jsxs)("button",{className:"synth-suggestion-card",onClick:()=>a("Explain how the synthesis strategies work"),children:[(0,b.jsx)("span",{className:"synth-suggestion-icon",children:"📚"}),(0,b.jsx)("span",{children:"Explain strategies"})]})]})]}):(0,b.jsxs)("div",{className:"synth-chat-messages",ref:d,children:[e.map((e,t)=>(0,b.jsxs)("div",{className:`chat-msg-row ${e.role}`,children:[(0,b.jsx)("span",{className:"chat-msg-role",children:"user"===e.role?"You":"Synth"}),"user"===e.role?(0,b.jsx)("div",{className:"chat-msg-user-text",children:e.content}):(0,b.jsx)(ey,{blocks:e.blocks??[],onSend:a})]},t)),t&&(0,b.jsxs)("div",{className:"chat-stage-indicator",children:[(0,b.jsx)("span",{className:"chat-streaming-dot"}),u]})]}),(0,b.jsxs)("div",{className:"synth-chat-footer",children:[(0,b.jsx)(ep,{isRunning:s,mode:r,onModeChange:n,onPlay:l,onStop:i,disabled:o}),(0,b.jsx)(eo.default,{onSend:a,disabled:t})]})]})}function ek({market:e}){if(!e)return(0,b.jsxs)("div",{className:"market-card market-card-empty",children:[(0,b.jsx)("span",{className:"market-card-empty-text",children:"No market selected"}),(0,b.jsx)("span",{className:"market-card-empty-hint",children:"Ask the agent to search for a market"})]});let t=e.outcomes||[],a=e.prices||{},s=e.volume?Number(e.volume).toLocaleString("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}):"N/A";return(0,b.jsxs)("div",{className:"market-card",children:[(0,b.jsx)("div",{className:"market-card-question",children:e.question}),(0,b.jsx)("div",{className:"market-card-outcomes",children:t.map((e,t)=>{let s=a[e],r=null!=s?(100*s).toFixed(1):"—",n=null!=s?`${Math.max(100*s,2)}%`:"0%";return(0,b.jsxs)("div",{className:"market-card-outcome",children:[(0,b.jsxs)("div",{className:"market-card-outcome-header",children:[(0,b.jsx)("span",{className:"market-card-outcome-name",children:e}),(0,b.jsxs)("span",{className:"market-card-outcome-price",children:[r,"%"]})]}),(0,b.jsx)("div",{className:"market-card-outcome-bar-bg",children:(0,b.jsx)("div",{className:`market-card-outcome-bar ${0===t?"yes":"no"}`,style:{width:n}})})]},t)})}),(0,b.jsxs)("div",{className:"market-card-meta",children:[(0,b.jsxs)("span",{children:["Vol: ",s]}),e.endDate&&(0,b.jsxs)("span",{children:["Ends: ",new Date(e.endDate).toLocaleDateString()]})]})]})}function eS({data:e}){if(e.length<2)return(0,b.jsx)("div",{className:"paper-equity-empty",children:"Collecting data..."});let t=e.map(e=>e.equity),a=Math.min(...t),s=Math.max(...t)-a||1,r=t.map((e,r)=>{let n=2+r/(t.length-1)*276;return`${n},${58-(e-a)/s*56}`}),n=t[t.length-1],l=t[0];return(0,b.jsx)("svg",{className:"paper-equity-chart",viewBox:"0 0 28
10 60",preserveAspectRatio:"none",children:(0,b.jsx)("polyline",{points:r.join(" "),fill:"none",stroke:n>=l?"var(--color-long)":"var(--color-short)",strokeWidth:"1.5"})})}function e$({balance:e,realizedPnl:t,unrealizedPnl:a,equity:s,positions:r,trades:n,equityHistory:l,leaderboard:i=[],forwardMetrics:o=null,riskState:c=null,decayAlert:d=null,onRefreshLeaderboard:u,compactOnly:h=!1}){let p=r.filter(e=>"open"===e.status),m=i.slice(0,6),x=d?.type==="decay_recovered"?"ok":"warn",g=d?.type==="risk_downgrade"?"Risk Downgrade":d?.type==="risk_kill_switch"?"Risk Kill-Switch":d?.type==="decay_alert"?"Decay Alert":"Decay Recovered";return(0,b.jsxs)("div",{className:"paper-dashboard",children:[!h&&(0,b.jsxs)("div",{className:"paper-stats-grid",children:[(0,b.jsxs)("div",{className:"paper-stat",children:[(0,b.jsx)("span",{className:"paper-stat-label",children:"Balance"}),(0,b.jsxs)("span",{className:"paper-stat-value",children:["$",e.toLocaleString("en-US",{minimumFractionDigits:2})]})]}),(0,b.jsxs)("div",{className:"paper-stat",children:[(0,b.jsx)("span",{className:"paper-stat-label",children:"Equity"}),(0,b.jsxs)("span",{className:"paper-stat-value",children:["$",s.toLocaleString("en-US",{minimumFractionDigits:2})]})]}),(0,b.jsxs)("div",{className:"paper-stat",children:[(0,b.jsx)("span",{className:"paper-stat-label",children:"Realized P&L"}),(0,b.jsxs)("span",{className:`paper-stat-value ${t>=0?"long":"short"}`,children:[t>=0?"+":"",t.toFixed(4)]})]}),(0,b.jsxs)("div",{className:"paper-stat",children:[(0,b.jsx)("span",{className:"paper-stat-label",children:"Unrealized P&L"}),(0,b.jsxs)("span",{className:`paper-stat-value ${a>=0?"long":"short"}`,children:[a>=0?"+":"",a.toFixed(4)]})]})]}),!h&&(0,b.jsxs)("div",{className:"paper-section",children:[(0,b.jsx)("h4",{className:"paper-section-title",children:"Equity"}),(0,b.jsx)(eS,{data:l})]}),m.length>0&&(0,b.jsxs)("div",{className:"paper-section",children:[(0,b.jsxs)("div",{className:"paper-section-title-row",children:[(0,b.jsx)("h4",{className:"paper-section-title",children:"Forward Leaderboard"}),u&&(0,b.jsx)("button",{className:"paper-lb-refresh",onClick:u,children:"Refresh"})]}),(0,b.jsx)("div",{className:"paper-lb-list",children:m.map(e=>(0,b.jsxs)("div",{className:"paper-lb-row",children:[(0,b.jsxs)("div",{className:"paper-lb-rank",children:["#",e.rank]}),(0,b.jsxs)("div",{className:"paper-lb-main",children:[(0,b.jsx)("div",{className:"paper-lb-name",children:e.strategy_name||"Unnamed strategy"}),(0,b.jsx)("div",{className:"paper-lb-sub",children:e.market_slug||"unknown market"})]}),(0,b.jsxs)("div",{className:`paper-lb-metric ${e.total_return_pct>=0?"long":"short"}`,children:[e.total_return_pct>=0?"+":"",e.total_return_pct.toFixed(2),"%"]}),(0,b.jsxs)("div",{className:"paper-lb-metric",children:["DD ",e.max_drawdown_pct.toFixed(1),"%"]}),(0,b.jsxs)("div",{className:`paper-lb-metric ${e.decayed?"warn":""}`,children:["Decay ",e.edge_decay_pct.toFixed(0),"%"]}),(0,b.jsxs)("div",{className:"paper-lb-metric",children:["HL ",null!=e.half_life_hours?`${e.half_life_hours.toFixed(1)}h`:"—"]})]},e.session_id))})]}),d&&(0,b.jsxs)("div",{className:`paper-decay-alert ${x}`,children:[(0,b.jsx)("div",{className:"paper-decay-title",children:g}),(0,b.jsx)("div",{className:"paper-decay-msg",children:d.message||"Forward edge status updated."})]}),c&&(0,b.jsxs)("div",{className:`paper-risk-strip ${c.mode}`,children:[(0,b.jsxs)("div",{className:"paper-risk-chip",children:["Mode: ",String(c.mode||"normal").toUpperCase()]}),(0,b.jsxs)("div",{className:"paper-risk-chip",children:["Size: ",(100*Number(c.position_pct||0)).toFixed(2),"%"]}),(0,b.jsxs)("div",{className:"paper-risk-chip",children:["Decay Hits: ",Math.max(0,Number(c.consecutive_decay_hits||0)),c.kill_after?` / ${c.kill_after}`:""]}),"number"==typeof c.half_life_max_hours&&"number"==typeof c.min_edge_decay_pct&&(0,b.jsxs)("div",{className:"paper-risk-chip paper-risk-chip-soft",children:["Trigger: HL≤",c.half_life_max_hours.toFixed(1),"h & Decay≥",c.min_edge_decay_pct.toFixed(0),"%"]})]}),o&&(0,b.jsxs)("div",{className:"paper-section",children:[(0,b.jsx)("h4",{className:"paper-section-title",children:"Forward Metrics"}),(0,b.jsxs)("div",{className:"paper-forward-grid",children:[(0,b.jsxs)("div",{className:"paper-forward-item",children:[(0,b.jsx)("span",{children:"Score"}),(0,b.jsx)("strong",{children:o.leaderboard_score.toFixed(2)})]}),(0,b.jsxs)("div",{className:"paper-forward-item",children:[(0,b.jsx)("span",{children:"Decay"}),(0,b.jsxs)("strong",{children:[o.edge_decay_pct.toFixed(1),"%"]})]}),(0,b.jsxs)("div",{className:"paper-forward-item",children:[(0,b.jsx)("span",{children:"Half-Life"}),(0,b.jsx)("strong",{children:null!=o.half_life_hours?`${o.half_life_hours.toFixed(1)}h`:"—"})]}),(0,b.jsxs)("div",{className:"paper-forward-item",children:[(0,b.jsx)("span",{children:"24h Return"}),(0,b.jsxs)("strong",{className:o.recent_return_24h_pct>=0?"long":"short",children:[o.recent_return_24h_pct>=0?"+":"",o.recent_return_24h_pct.toFixed(2),"%"]})]})]})]}),!h&&p.length>0&&(0,b.jsxs)("div",{className:"paper-section",children:[(0,b.jsxs)("h4",{className:"paper-section-title",children:["Open Positions (",p.length,")"]}),(0,b.jsxs)("table",{className:"paper-positions-table",children:[(0,b.jsx)("thead",{children:(0,b.jsxs)("tr",{children:[(0,b.jsx)("th",{children:"Outcome"}),(0,b.jsx)("th",{children:"Shares"}),(0,b.jsx)("th",{children:"Entry"}),(0,b.jsx)("th",{children:"Current"}),(0,b.jsx)("th",{children:"P&L"})]})}),(0,b.jsx)("tbody",{children:p.map(e=>(0,b.jsxs)("tr",{children:[(0,b.jsx)("td",{children:e.outcome}),(0,b.jsx)("td",{children:e.shares.toFixed(2)}),(0,b.jsx)("td",{children:e.entry_price.toFixed(4)}),(0,b.jsx)("td",{children:e.current_price?.toFixed(4)??"—"}),(0,b.jsxs)("td",{className:e.unrealized_pnl>=0?"long":"short",children:[e.unrealized_pnl>=0?"+":"",e.unrealized_pnl.toFixed(4)]})]},e.id))})]})]}),!h&&n.length>0&&(0,b.jsxs)("div",{className:"paper-section",children:[(0,b.jsxs)("h4",{className:"paper-section-title",children:["Recent Trades (",n.length,")"]}
1),(0,b.jsx)("div",{className:"paper-trades-list",children:n.slice(0,10).map(e=>(0,b.jsxs)("div",{className:`paper-trade-item ${e.action.toLowerCase()}`,children:[(0,b.jsx)("span",{className:"paper-trade-action",children:e.action}),(0,b.jsx)("span",{className:"paper-trade-outcome",children:e.outcome}),(0,b.jsxs)("span",{className:"paper-trade-price",children:[e.shares.toFixed(2)," @ ",e.price.toFixed(4)]}),(0,b.jsxs)("span",{className:"paper-trade-size",children:["$",e.size_usd.toFixed(2)]})]},e.id))})]})]})}function eC(e,t){if(e.length<=t||t<=1)return e;let a=[],s=(e.length-1)/(t-1),r=new Set;for(let n=0;n<t;n+=1){let t=Math.max(0,Math.min(e.length-1,Math.round(n*s)));r.has(t)||(r.add(t),a.push(e[t]))}return r.has(e.length-1)||a.push(e[e.length-1]),a.sort((e,t)=>e.idx-t.idx)}function eM(e){let t=Math.abs(e);return t>=1e9?`$${(e/1e9).toFixed(2)}B`:t>=1e6?`$${(e/1e6).toFixed(2)}M`:t>=1e3?`$${(e/1e3).toFixed(1)}K`:`$${e.toFixed(0)}`}function eE({equityCurve:e,equityCurvesByTf:t,activeTfs:a,height:s=300,compact:r,selectionMode:n=!1,onSelectionChange:l}){let i=(0,_.useRef)(null),o=(0,_.useRef)(null),c=(0,_.useRef)(null),d=(0,_.useRef)({}),[u,h]=(0,_.useState)(null),p=(0,_.useRef)(null),m=(0,_.useRef)(!1),[x,g]=(0,_.useState)(null),f=e=>Number(e).toLocaleString(void 0,{maximumFractionDigits:2}),v=e=>{let t=new Date(1e3*e),a=t.getUTCFullYear(),s=String(t.getUTCMonth()+1).padStart(2,"0"),r=String(t.getUTCDate()).padStart(2,"0"),n=String(t.getUTCHours()).padStart(2,"0"),l=String(t.getUTCMinutes()).padStart(2,"0");return`${a}-${s}-${r} ${n}:${l} UTC`},y=(0,_.useMemo)(()=>{if(!Array.isArray(e))return[];let t=e.filter(e=>{if(Array.isArray(e))return Number.isFinite(Number(e?.[0]))&&Number.isFinite(Number(e?.[1]));let t=Number.isFinite(Number(e?.ts_ms))&&Number.isFinite(Number(e?.equity_usd)),a=Number.isFinite(Number(e?.ts))&&Number.isFinite(Number(e?.equity)),s=Number.isFinite(Number(e?.time))&&Number.isFinite(Number(e?.value));return t||a||s}).map(e=>{let t,a;return Array.isArray(e)?(t=Number(e[0]),a=Number(e[1])):e?.ts_ms!=null&&e?.equity_usd!=null?(t=Math.floor(Number(e.ts_ms)/1e3),a=Number(e.equity_usd)):e?.ts!=null&&e?.equity!=null?(t=Number(e.ts),a=Number(e.equity)):(t=Number(e.time),a=Number(e.value)),t>1e12&&(t=Math.floor(t/1e3)),{time:t,value:a}});t.sort((e,t)=>e.time-t.time);let a=[],s=-1;for(let e of t)e.time<=s||(a.push(e),s=e.time);return a},[e]),j=(0,_.useMemo)(()=>{if(!t||!a||0===a.length)return{};let e=e=>{let t=(Array.isArray(e)?e:[]).filter(e=>{if(Array.isArray(e))return Number.isFinite(Number(e?.[0]))&&Number.isFinite(Number(e?.[1]));let t=Number.isFinite(Number(e?.ts_ms))&&Number.isFinite(Number(e?.equity_usd)),a=Number.isFinite(Number(e?.ts))&&Number.isFinite(Number(e?.equity)),s=Number.isFinite(Number(e?.time))&&Number.isFinite(Number(e?.value));return t||a||s}).map(e=>{let t,a;return Array.isArray(e)?(t=Number(e[0]),a=Number(e[1])):e?.ts_ms!=null&&e?.equity_usd!=null?(t=Math.floor(Number(e.ts_ms)/1e3),a=Number(e.equity_usd)):e?.ts!=null&&e?.equity!=null?(t=Number(e.ts),a=Number(e.equity)):(t=Number(e.time),a=Number(e.value)),t>1e12&&(t=Math.floor(t/1e3)),{time:t,value:a}});t.sort((e,t)=>e.time-t.time);let a=[],s=-1;for(let e of t)e.time<=s||(a.push(e),s=e.time);return a},s={};for(let r of a){let a=t[r];if(!Array.isArray(a)||0===a.length)continue;let n=e(a);n.length>0&&(s[r]=n)}return s},[t,a]),w=(0,_.useMemo)(()=>{if(0===y.length)return null;let e={},t=[],a=[],s=-1/0,r=0;for(let n=0;n<y.length;n+=1){let l=y[n],i=Number(l.value),o=Number(l.time);i>s&&(s=i,t.push({idx:n,ts:o,value:i,peak:s,drawdown:0}));let c=Number.isFinite(s)&&Math.abs(s)>1e-12?Math.max(0,(s-i)/s):0;c>r+1e-12&&(r=c,a.push({idx:n,ts:o,value:i,peak:s,drawdown:c})),e[o]={peak:s,drawdown:c}}return{byTs:e,peakMilestones:eC(t,8),drawdownMilestones:eC(a,8)}},[y]);(0,_.useEffect)(()=>{if(!l)return;if(!u||y.length<2)return void l(null);let e=Math.max(0,Math.min(u.a,u.b)),t=Math.max(0,Math.max(u.a,u.b));if(t<=e||e>=y.length||t>=y.length)return void l(null);let a=y[e],s=y[t];if(!a||!s)return void l(null);let r=Number(a.value),n=Number(s.value),i=n-r,o=Math.abs(r)>1e-12?i/r*100:0;l({start_ts:Number(a.time),end_ts:Number(s.time),start_equity:r,end_equity:n,pnl_usd:i,return_pct:o,points:t-e+1})},[u,y,l]),(0,_.useEffect)(()=>{n||(h(null),m.current=!1,p.current=null)},[n]),(0,_.useEffect)(()=>
1{if(!n)return;let e=()=>{m.current=!1,p.current=null};return window.addEventListener("mouseup",e),()=>window.removeEventListener("mouseup",e)},[n]);let N=(0,_.useMemo)(()=>{if(!r||0===y.length)return null;let e=Math.max(120,Math.floor(s)),t=Math.max(1,Math.ceil(y.length/2e3)),a=y.map((e,t)=>({...e,dataIndex:t})).filter((e,a)=>a===y.length-1||a%t==0),n=y.map(e=>Number(e.value)),l=Math.min(...n),i=Math.max(...n),o=Math.max(1e-9,i-l),c=Math.max(1,e-20),d=a.map((e,t)=>({x:10+t/Math.max(1,a.length-1)*980,y:10+(i-Number(e.value))/o*c})),u={};for(let e=0;e<a.length;e+=1){let t=Number(a[e]?.dataIndex??-1),s=d[e];t>=0&&s&&(u[t]=s)}let h=d.map((e,t)=>`${0===t?"M":"L"}${e.x.toFixed(2)},${e.y.toFixed(2)}`).join(" ");return{viewW:1e3,viewH:e,minV:l,maxV:i,areaPath:`${h} L990.00,${(10+c).toFixed(2)} L10.00,${(10+c).toFixed(2)} Z`,linePath:h,points:a,coords:d,coordByDataIndex:u,padX:10,padY:10,plotW:980,plotH:c}},[r,y,s]);if((0,_.useEffect)(()=>{if(!i.current)return;let e=(0,A.createChart)(i.current,{...(0,T.makeChartOptions)(s),autoSize:!0}),t=e.addSeries(A.AreaSeries,{lineColor:T.CHART_COLORS.equityLine,topColor:T.CHART_COLORS.equityTop,bottomColor:T.CHART_COLORS.equityBottom,lineWidth:2,priceLineVisible:!1,lastValueVisible:!0});o.current=e,c.current=t;let a=e=>{if(!i.current||!c.current)return;if(!e?.point||!e?.time)return void g(null);let t=e.point,a=i.current.clientWidth,s=i.current.clientHeight;if(t.x<0||t.y<0||t.x>a||t.y>s)return void g(null);let r=e.seriesData?.get(c.current),n=Number(r?.value??r?.close??r?.price);if(!Number.isFinite(n))return void g(null);let l=Number(e.time);Number.isFinite(l)?g({x:t.x+12,y:t.y+12,ts:l,value:n}):g(null)};e.subscribeCrosshairMove(a);let r=new ResizeObserver(()=>{e.applyOptions({width:i.current.clientWidth}),e.timeScale().fitContent()});return r.observe(i.current),()=>{e.unsubscribeCrosshairMove(a),r.disconnect(),d.current={},e.remove(),o.current=null,c.current=null,g(null)}},[s]),(0,_.useEffect)(()=>{c.current&&(c.current.setData(y),o.current&&o.current.timeScale().fitContent())},[y]),(0,_.useEffect)(()=>{if(!o.current||!c.current)return;let e=o.current,t={"5m":{line:"#22d3ee",top:"rgba(34,211,238,0.28)",bottom:"rgba(34,211,238,0.03)"},"15m":{line:"#a78bfa",top:"rgba(167,139,250,0.26)",bottom:"rgba(167,139,250,0.03)"},"1h":{line:"#34d399",top:"rgba(52,211,153,0.25)",bottom:"rgba(52,211,153,0.03)"},"4h":{line:"#f59e0b",top:"rgba(245,158,11,0.24)",bottom:"rgba(245,158,11,0.03)"},"1d":{line:"#f43f5e",top:"rgba(244,63,94,0.24)",bottom:"rgba(244,63,94,0.03)"}},s=a&&a.length>0?a[0]:null,r=s?j[s]:null;if(r&&r.length>0){c.current.setData(r);let e=t[s]||t["5m"];c.current.applyOptions({lineColor:e.line,topColor:e.top,bottomColor:e.bottom})}else c.current.setData(y),c.current.applyOptions({lineColor:T.CHART_COLORS.equityLine,topColor:T.CHART_COLORS.equityTop,bottomColor:T.CHART_COLORS.equityBottom});let n=new Set(Object.keys(j));for(let[t,a]of Object.entries(d.current))n.has(t)&&t!==s||(e.removeSeries(a),delete d.current[t]);for(let[a,r]of Object.entries(j)){if(a===s)continue;let n=d.current[a],l=t[a]||t["15m"];n?n.applyOptions({lineColor:l.line,topColor:l.top,bottomColor:l.bottom}):(n=e.addSeries(A.AreaSeries,{lineColor:l.line,topColor:l.top,bottomColor:l.bottom,lineWidth:2,priceLineVisible:!1,lastValueVisible:!0}),d.current[a]=n),n.setData(r)}e.timeScale().fitContent()},[j,a,y]),!e||0===e.length||0===y.length)return(0,b.jsx)("div",{className:"empty-state",children:"Run a backtest to see equity curve"});let k=x?w?.byTs[x.ts]:null;if(r){if(N){let e=(()=>{if(!n||!u)return null;let e=Math.max(0,Math.min(u.a,u.b)),t=Math.max(0,Math.max(u.a,u.b)),a=N.coordByDataIndex[e],s=N.coordByDataIndex[t];return a&&s?{x:Math.min(a.x,s.x),w:Math.max(1,Math.abs(s.x-a.x))}:null})(),t=e=>N.padX+e/Math.max(1,y.length-1)*N.plotW,a=e=>N.padY+(N.maxV-e)/Math.max(1e-9,N.maxV-N.minV)*N.plotH,r=(e,t,a,s,r,n)=>{let l=Math.max(0,n?.lane??0),i=n?.above??!0,o=Math.max(40,6.25*s.length+10),c="peak"===r?"#22d3ee":"#f43f5e",d=Math.max(2,Math.min(N.viewW-o-2,t+6)),u=Math.max(2,Math.min(N.viewH-16-2,i?a-(22+16*l):a+(8+16*l))),h=i?u+16:u;return(0,b.jsxs)("g",{children:[(0,b.jsx)("line",{x1:t,y1:a,x2:d+3,y2:h,stroke:c,strokeWidth:"0.8",opacity:"0.75"}),(0,b.jsx)("rect",{x:d,y:u,width:o,height:16,rx:"4",fill:"rgba(8, 10, 14, 0.72)",stroke:c,strokeWidth:"0.8"}),(0,b.jsx)("text",{x:d+5,y:u+16-3-1,fill:"peak"===r?"#67e8f9":"#fb7185",fontSize:"10",fontFamily:"var(--font-mono)",children:s})]},e)};return(0,b.jsxs)("div",{className:"equity-chart-container",style:{height:s,position:"relative"},children:[(0,b.jsxs)("svg",{width:"100%",height:"100%",viewBox:`0 0 ${N.viewW} ${N.viewH}`,preserveAspectRatio:"none",role:"img","aria-label":"Equity curve",onMouseMove:e=>{let t=e.currentTarget.getBoundingClientRect(),a=Math.round(Math.max(0,Math.min(1,((e.clientX-t.left)/Math.max(1,t.width)*N.viewW-N.padX)/Math.max(1e-9,N.plotW)))*Math.max(0,N.points.length-1)),s=Math.max(0,Math.min(N.points.length-1,a)),r=N.points[s],l=N.coords[s];if(n&&m.current&&null!=p.current){let e=Number(N.points[s]?.dataIndex??0);h({a:p.current,b:e})}r&&l?g({x:l.x/N.viewW*t.width+12,y:l.y/N.viewH*t.height+12,ts:Number(r.time),value:Number(r.value)}):g(null)},onMouseDown:e=>{if(!n)return;let t=e.currentTarget.getBoundingClientRect(),a=Math.round(Math.max(0,Math.min(1,((e.clientX-t.left)/Math.max(1,t.width)*N.viewW-N.padX)/Math.max(1e-9,N.plotW)))*Math.max(0,N.points.length-1)),s=Math.max(0,Math.min(N.points.length-1,a)),r=Number(N.points[s]?.dataIndex??0);p.current=r,m.current=!0,h({a:r,b:r}),e.preventDefault()},onMouseUp:()=>{m.current=!1,p.current=null},onMouseLeave:()=>g(null),onDoubleClick:()=>n&&h(null),children:[(0,b.jsx)("defs",{children:(0,b.jsxs)("linearGradient",{id:"eqFill",x1:"0",y1:"0",x2:"0",y2:"1",children:[(0,b.jsx)("stop",{offset:"0%",stopColor:T.CHART_COLORS.equityTop}),(0,b.jsx)("stop",{offset:"100%",stopColor:T.CHART_COLORS.equityBottom})]})}),(0,b.jsx)("path",{d:N.areaPath,fill:"url(#eqFill)"}),e?(0,b.jsx)("rect",{x:e.x,y:0,width:e.w,height:N.viewH,fill:"rgba(59,130,246,0.15)",stroke:"rgba(59,130,246,0.45)",strokeWidth:"1"}):null,(0,b.jsx)("path",{d:N.linePath,fill:"none",stroke:T.CHART_COLORS.equityLine,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"}),w?.peakMilestones.map((e,s)=>{let n=t(e.idx),l=a(e.value),i=s===w.peakMilestones.length-1||s%3==0;return(0,b.jsxs)("g",{children:[(0,b.jsx)("circle",{cx:n,cy:l,r:"2.8",fill:"#22d3ee",opacity:"0.92"}),i?r(`peak-callout-${e.ts}-${s}`,n,l,`Peak ${eM(e.peak)}`,"peak",{above:!0,lane:s%2}):null]},`peak-${e.ts}-${s}`)}),w?.drawdownMilestones.map((e,s)=>{let n=t(e.idx),l=a(e.value),i=s===w.drawdownMilestones.length-1;return(0,b.jsxs)("g",{children:[(0,b.jsx)("circle",{cx:n,cy:l,r:i?"3.6":"2.8",fill:"#f43f5e",opacity:i?"1":"0.9"}),i?r(`dd-callout-${e.ts}-${s}`,n,l,`Max DD Eq ${eM(e.value)}`,"dd",{above:l>.58*N.viewH,lane:0}):null]},`dd-${e.ts}-${s}`)}),x?(()=>{let e=N.points.findIndex(e=>Number(e.time)===x.ts&&Number(e.value)===x.value);if(e<0)return null;let t=N.coords[e];return t?(0,b.jsx)("circle",{cx:t.x,cy:t.y,r:"3.5",fill:T.CHART_COLORS.equityLine,stroke:T.CHART_COLORS.bg,strokeWidth:"1.5"}):null}
1)():null,(0,b.jsx)("text",{x:"8",y:"14",fill:T.CHART_COLORS.text,fontSize:"11",fontFamily:"var(--font-mono)",children:N.maxV.toFixed(2)}),(0,b.jsx)("text",{x:"8",y:N.viewH-4,fill:T.CHART_COLORS.text,fontSize:"11",fontFamily:"var(--font-mono)",children:N.minV.toFixed(2)})]}),x?(0,b.jsxs)("div",{style:{position:"absolute",left:x.x,top:x.y,transform:"translate(-50%, -100%)",pointerEvents:"none",zIndex:20,background:"rgba(8, 10, 14, 0.92)",border:"1px solid var(--border-default)",borderRadius:8,padding:"6px 8px",minWidth:170,boxShadow:"0 8px 24px rgba(0,0,0,0.35)"},children:[(0,b.jsx)("div",{style:{fontSize:11,color:"var(--text-tertiary)",marginBottom:2},children:v(x.ts)}),(0,b.jsxs)("div",{style:{fontSize:12,color:"var(--text-primary)",fontFamily:"var(--font-mono)"},children:["Equity: ",f(x.value)]}),k?(0,b.jsxs)("div",{style:{fontSize:11,color:"var(--text-secondary)",fontFamily:"var(--font-mono)"},children:["Peak: ",f(k.peak)," | DD: ",(100*k.drawdown).toFixed(2),"%"]}):null]}):null]})}return(0,b.jsx)("div",{ref:i,className:"equity-chart-container",style:{height:s,position:"relative"},children:x?(0,b.jsxs)("div",{style:{position:"absolute",left:x.x,top:x.y,transform:"translate(-50%, -100%)",pointerEvents:"none",zIndex:20,background:"rgba(8, 10, 14, 0.92)",border:"1px solid var(--border-default)",borderRadius:8,padding:"6px 8px",minWidth:170,boxShadow:"0 8px 24px rgba(0,0,0,0.35)"},children:[(0,b.jsx)("div",{style:{fontSize:11,color:"var(--text-tertiary)",marginBottom:2},children:v(x.ts)}),(0,b.jsxs)("div",{style:{fontSize:12,color:"var(--text-primary)",fontFamily:"var(--font-mono)"},children:["Equity: ",f(x.value)]}),k?(0,b.jsxs)("div",{style:{fontSize:11,color:"var(--text-secondary)",fontFamily:"var(--font-mono)"},children:["Peak: ",f(k.peak)," | DD: ",(100*k.drawdown).toFixed(2),"%"]}):null]}):null})}return(0,b.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%",position:"relative"},children:[(0,b.jsxs)("div",{className:"panel-header",children:[(0,b.jsx)("span",{className:"panel-title",children:"Equity Curve"}),(0,b.jsxs)("span",{className:"panel-subtitle",children:[y.length," points"]})]}),(0,b.jsx)("div",{ref:i,className:"equity-chart-container"}),x?(0,b.jsxs)("div",{style:{position:"absolute",left:x.x,top:x.y+32,transform:"translate(-50%, -100%)",pointerEvents:"none",zIndex:20,background:"rgba(8, 10, 14, 0.92)",border:"1px solid var(--border-default)",borderRadius:8,padding:"6px 8px",minWidth:170,boxShadow:"0 8px 24px rgba(0,0,0,0.35)"},children:[(0,b.jsx)("div",{style:{fontSize:11,color:"var(--text-tertiary)",marginBottom:2},children:v(x.ts)}),(0,b.jsxs)("div",{style:{fontSize:12,color:"var(--text-primary)",fontFamily:"var(--font-mono)"},children:["Equity: ",f(x.value)]}),k?(0,b.jsxs)("div",{style:{fontSize:11,color:"var(--text-secondary)",fontFamily:"var(--font-mono)"},children:["Peak: ",f(k.peak)," | DD: ",(100*k.drawdown).toFixed(2),"%"]}):null]}):null]})}let eA=Array.from({length:24},(e,t)=>t);function eT({params:e,result:t,loading:a,onParamChange:s,onApply:r,onReset:n}){let l=(0,_.useCallback)(t=>{s("hourset",e.hourset.includes(t)?e.hourset.filter(e=>e!==t):[...e.hourset,t].sort((e,t)=>e-t))},[e.hourset,s]),i=t?.stats,o=i&&i.win_count+i.loss_count>0?(i.win_count/(i.win_count+i.loss_count)*100).toFixed(1):"—",c=t?.equity_curve?.map(e=>({ts:e.ts,equity:e.equity}))??[];return(0,b.jsxs)("div",{className:"strategy-dashboard",children:[(0,b.jsxs)("div",{className:"strategy-dashboard-header",children:[(0,b.jsx)("input",{className:"dashboard-name-input",type:"text",value:e.strategy_name,onChange:e=>s("strategy_name",e.target.value),placeholder:"Strategy name"}),(0,b.jsxs)("div",{className:"dashboard-badges",children:[(0,b.jsx)("span",{className:"dashboard-badge",children:e.asset}),(0,b.jsx)("span",{className:"dashboard-badge",children:e.tf}),a&&(0,b.jsx)("span",{className:"dashboard-badge dashboard-badge-loading",children:"simulating..."})]})]}),(0,b.jsxs)("div",{className:"dashboard-section",children:[(0,b.jsx)("label",{className:"dashboard-label",children:"Hours (ET)"}),(0,b.jsx)("div",{className:"hourset-grid",children:eA.map(t=>(0,b.jsx)("button",{className:`hourset-cell${e.hourset.includes(t)?" active":""}`,onClick:()=>l(t),type:"button",children:t},t))})]}),(0,b.jsxs)("div",{className:"dashboard-controls-grid",children:[(0,b.jsxs)("div",{className:"dashboard-control",children:[(0,b.jsx)("label",{children:"Streak"}),(0,b.jsx)("input",{type:"number",min:1,max:10,value:e.streak,onChange:e=>s("streak",parseInt(e.target.value,10)||1)})]}),(0,b.jsxs)("div",{className:"dashboard-control",children:[(0,b.jsx)("label",{children:"Exact"}),(0,b.jsx)("button",{type:"button",className:`dashboard-toggle${e.exact?" active":""}`,onClick:()=>s("exact",!e.exact),children:e.exact?"ON":"OFF"})]}),(0,b.jsxs)("div",{className:"dashboard-control",children:[(0,b.jsx)("label",{children:"Trigger"}),(0,b.jsxs)("div",{className:"dashboard-segmented",children:[(0,b.jsx)("button",{type:"button",className:"both"===e.trigger_mode?"active":"",onClick:()=>s("trigger_mode","both"),children:"Both"}),(0,b.jsx)("button",{type:"button",className:"down_only"===e.trigger_mode?"active":"",onClick:()=>s("trigger_mode","down_only"),children:"Down"})]})]}),(0,b.jsxs)("div",{className:"dashboard-control",children:[(0,b.jsx)("label",{children:"Base USD"}),(0,b.jsx)("input",{type:"number",min:1,value:e.base_usd,onChange:e=>s("base_usd",parseFloat(e.target.value)||1)})]}),(0,b.jsxs)("div",{className:"dashboard-control",children:[(0,b.jsx)("label",{children:"Equity"}),(0,b.jsx)("input",{type:"number",min:100,value:e.initial_equity,onChange:e=>s("initial_equity",parseFloat(e.target.value)||100)})]}),(0,b.jsxs)("div",{className:"dashboard-control",children:[(0,b.jsx)("label",{children:"Entry Price"}),(0,b.jsx)("input",{type:"number",min:.01,max:.99,step:.01,value:e.entry_price,onChange:e=>s("entry_price",parseFloat(e.target.value)||.55)})]}),(0,b.jsxs)("div",{className:"dashboard-control dashboard-control-wide",children:[(0,b.jsx)("label",{children:"Multipliers"}),(0,b.jsx)("input",{type:"text",value:e.multipliers.join(","),onChange:e=>{let t=e.target.value.split(",").map(e=>parseFloat(e.trim())).filter(Number.isFinite);t.length>0&&s("multipliers",t)},placeholder:"1,1,2,4"})]}),(0,b.jsxs)("div",{className:"dashboard-control",children:[(0,b.jsx)("label",{children:"Confidence"}),(0,b.jsxs)("select",{value:e.confidence_min_score??"",onChange:e=>{let t=e.target.value;s("confidence_min_score",""===t?null:parseInt(t,10))},children:[(0,b.jsx)("option",{value:"",children:"None"}),(0,b.jsx)("option",{value:"1",children:"1"}),(0,b.jsx)("option",{value:"2",children:"2"}),(0,b.jsx)("option",{value:"3",children:"3"}),(0,b.jsx)("option",{value:"4",children:"4"})]})]})]}),(0,b.jsxs)("div",{className:"dashboard-section",children:[(0,b.jsxs)("div",{className:"dashboard-controls-grid",children:[(0,b.jsxs)("div",{className:"dashboard-control",children:[(0,b.jsx)("label",{children:"Use CLOB Prices"}),(0,b.jsx)("button",{type:"button",className:`dashboard-toggle${e.use_clob?" active":""}`,onClick:()=>s("use_clob",!e.use_clob),children:e.use_clob?"ON":"OFF"})]}),e.use_clob&&(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)("div",{className:"dashboard-control",children:[(0,b.jsx)("label",{children:"Entry Mode"}
1),(0,b.jsxs)("select",{value:e.clob_entry_mode,onChange:e=>s("clob_entry_mode",e.target.value),children:[(0,b.jsx)("option",{value:"open",children:"Market Open"}),(0,b.jsx)("option",{value:"30s",children:"+30s"}),(0,b.jsx)("option",{value:"60s",children:"+60s"}),(0,b.jsx)("option",{value:"120s",children:"+120s"})]})]}),(0,b.jsxs)("div",{className:"dashboard-control",children:[(0,b.jsx)("label",{children:"Max Spread"}),(0,b.jsx)("input",{type:"number",min:0,step:.01,value:e.max_spread??"",onChange:e=>{let t=e.target.value;s("max_spread",""===t?null:parseFloat(t))},placeholder:"e.g. 0.10"})]}),(0,b.jsxs)("div",{className:"dashboard-control",children:[(0,b.jsx)("label",{children:"Min Depth"}),(0,b.jsx)("input",{type:"number",min:0,step:100,value:e.min_depth??"",onChange:e=>{let t=e.target.value;s("min_depth",""===t?null:parseFloat(t))},placeholder:"e.g. 500"})]})]})]}),e.use_clob&&(0,b.jsxs)("div",{className:"dashboard-clob-note",children:[e.use_clob?"Fallback ":"","Entry Price: ",e.entry_price]})]}),c.length>0&&(0,b.jsx)("div",{className:"dashboard-chart-wrap",children:(0,b.jsx)(eE,{equityCurve:c,height:180,compact:!0})}),i&&(0,b.jsxs)("div",{className:"dashboard-stats-grid",children:[(0,b.jsxs)("div",{className:`dashboard-stat${i.total_pnl>=0?" positive":" negative"}`,children:[(0,b.jsx)("span",{className:"dashboard-stat-label",children:"P&L"}),(0,b.jsxs)("span",{className:"dashboard-stat-value",children:["$",i.total_pnl>=0?"+":"",i.total_pnl.toFixed(2)]})]}),(0,b.jsxs)("div",{className:"dashboard-stat",children:[(0,b.jsx)("span",{className:"dashboard-stat-label",children:"Final Equity"}),(0,b.jsxs)("span",{className:"dashboard-stat-value",children:["$",i.final_equity.toFixed(0)]})]}),(0,b.jsxs)("div",{className:"dashboard-stat negative",children:[(0,b.jsx)("span",{className:"dashboard-stat-label",children:"Max DD"}),(0,b.jsxs)("span",{className:"dashboard-stat-value",children:[(100*i.max_drawdown).toFixed(1),"%"]})]}),(0,b.jsxs)("div",{className:"dashboard-stat",children:[(0,b.jsx)("span",{className:"dashboard-stat-label",children:"Win Rate"}),(0,b.jsxs)("span",{className:"dashboard-stat-value",children:[o,"%"]})]}),(0,b.jsxs)("div",{className:"dashboard-stat",children:[(0,b.jsx)("span",{className:"dashboard-stat-label",children:"Campaigns"}),(0,b.jsx)("span",{className:"dashboard-stat-value",children:i.campaigns})]}),(0,b.jsxs)("div",{className:`dashboard-stat${i.blown>0?" negative":""}`,children:[(0,b.jsx)("span",{className:"dashboard-stat-label",children:"Blown"}),(0,b.jsx)("span",{className:"dashboard-stat-value",children:i.blown})]}),null!=i.clob_coverage&&(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)("div",{className:"dashboard-stat",children:[(0,b.jsx)("span",{className:"dashboard-stat-label",children:"CLOB Coverage"}),(0,b.jsxs)("span",{className:"dashboard-stat-value",children:[(100*i.clob_coverage).toFixed(0),"%"]})]}),null!=i.avg_entry_price&&(0,b.jsxs)("div",{className:"dashboard-stat",children:[(0,b.jsx)("span",{className:"dashboard-stat-label",children:"Avg Entry"}),(0,b.jsxs)("span",{className:"dashboard-stat-value",children:["$",i.avg_entry_price.toFixed(4)]})]}),null!=i.pnl_vs_fixed&&(0,b.jsxs)("div",{className:`dashboard-stat${i.pnl_vs_fixed>=0?" positive":" negative"}`,children:[(0,b.jsx)("span",{className:"dashboard-stat-label",children:"vs Fixed"}),(0,b.jsxs)("span",{className:"dashboard-stat-value",children:["$",i.pnl_vs_fixed>=0?"+":"",i.pnl_vs_fixed.toFixed(2)]})]})]})]}),(0,b.jsxs)("div",{className:"dashboard-actions",children:[t?.cnl_text&&r&&(0,b.jsx)("button",{type:"button",className:"dashboard-btn dashboard-btn-primary",onClick:()=>r(t.cnl_text),children:"Apply to CNL"}),n&&(0,b.jsx)("button",{type:"button",className:"dashboard-btn",onClick:n,children:"Reset"})]})]})}function eF({market:e,strategyRules:t,strategyName:a,paperStatus:s,paperLeaderboard:r,decayAlert:n,signals:l,sessionActive:i,algoName:o,onRefreshLeaderboard:c,dashboardActive:d,dashboardParams:u,dashboardResult:h,dashboardLoading:p,onDashboardParamChange:m,onDashboardApply:x,onDashboardReset:g}){return(0,b.jsxs)("div",{className:"context-panel",children:[o&&(0,b.jsx)("div",{className:"context-panel-algo-name",children:o}),(0,b.jsxs)("div",{className:"context-panel-section",children:[(0,b.jsx)("h3",{className:"context-panel-heading",children:"Market"}),(0,b.jsx)(ek,{market:e})]}),d&&u&&m&&(0,b.jsxs)("div",{className:"context-panel-section",children:[(0,b.jsx)("h3",{className:"context-panel-heading",children:"Strategy Dashboard"}),(0,b.jsx)(eT,{params:u,result:h??null,loading:p??!1,onParamChange:m,onApply:x,onReset:g})]}),t&&t.length>0&&(0,b.jsxs)("div",{className:"context-panel-section",children:[(0,b.jsx)("h3",{className:"context-panel-heading",children:"Strategy"}),(0,b.jsxs)("div",{className:"context-strategy-card",children:[a&&(0,b.jsx)("div",{className:"context-strategy-name",children:a}),(0,b.jsx)("div",{className:"context-strategy-rules",children:t.map((e,t)=>(0,b.jsx)("div",{className:"context-rule",children:(0,b.jsxs)("code",{children:[e.indicator," ",e.operator," ",e.threshold]})},t))})]})]}),s&&(0,b.jsxs)("div",{className:"context-panel-section",children:[(0,b.jsxs)("h3",{className:"context-panel-heading",children:["Paper Trading",i&&(0,b.jsx)("span",{className:"context-live-dot"})]}),(0,b.jsx)(e$,{balance:s.current_balance,realizedPnl:s.realized_pnl,unrealizedPnl:s.unrealized_pnl,equity:s.equity,positions:s.positions||[],trades:s.trades||[],equityHistory:s.equity_history||[],leaderboard:r,forwardMetrics:s.forward_metrics||null,riskState:s.risk_state||null,decayAlert:n,onRefreshLeaderboard:c})]}),!s&&r.length>0&&(0,b.jsxs)("div",{className:"context-panel-section",children:[(0,b.jsx)("h3",{className:"context-panel-heading",children:"Forward Leaderboard"}),(0,b.jsx)(e$,{balance:0,realizedPnl:0,unrealizedPnl:0,equity:0,positions:[],trades:[],equityHistory:[],leaderboard:r,decayAlert:n,onRefreshLeaderboard:c,
1compactOnly:!0})]}),!e&&!t&&!s&&!d&&0===r.length&&(0,b.jsxs)("div",{className:"context-panel-empty",children:[(0,b.jsx)("div",{className:"context-panel-empty-icon",children:"~"}),(0,b.jsx)("p",{children:"Ask the agent to search for a Polymarket market, then generate a strategy to trade it."})]})]})}function eP(){let e=function(){let[e,t]=(0,_.useState)([]),[a,s]=(0,_.useState)(null),[r,n]=(0,_.useState)(()=>localStorage.getItem("openpoly_algo_active_id")||null),[l,i]=(0,_.useState)(!0),o=(0,_.useRef)(null),c=(0,_.useRef)(null),d=(0,_.useCallback)(async()=>{try{let e=await (0,er.authFetch)("/api/synthesizer/algo/list"),a=await e.json();a.ok&&t(a.sessions)}catch{}finally{i(!1)}},[]),u=(0,_.useCallback)(async e=>{try{let t=await (0,er.authFetch)(`/api/synthesizer/algo/${e}`),a=await t.json();a.ok&&s(a.session)}catch{}},[]),h=(0,_.useCallback)(e=>{n(e);try{e?localStorage.setItem("openpoly_algo_active_id",e):localStorage.removeItem("openpoly_algo_active_id")}catch{}e?u(e):s(null)},[u]),p=(0,_.useCallback)(async e=>{try{let a=await (0,er.authFetch)("/api/synthesizer/algo/create",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:e||"Untitled Algo"})}),s=await a.json();if(s.ok){let a={id:s.session.id,name:s.session.name||e||"Untitled Algo",market_slug:null,market_question:null,strategy_name:null,status:"draft",paper_session_id:null,created_at:s.session.created_at||new Date().toISOString(),updated_at:s.session.updated_at||new Date().toISOString()};return t(e=>[a,...e]),h(s.session.id),d(),s.session}}catch{}return null},[d,h]),m=(0,_.useCallback)(async(e,r)=>{try{await (0,er.authFetch)(`/api/synthesizer/algo/${e}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:r})}),t(t=>t.map(t=>t.id===e?{...t,name:r}:t)),a?.id===e&&s(e=>e?{...e,name:r}:e)}catch{}},[a?.id]),x=(0,_.useCallback)(async e=>{try{await (0,er.authFetch)(`/api/synthesizer/algo/${e}`,{method:"DELETE"}),t(t=>t.filter(t=>t.id!==e)),r===e&&t(t=>{let a=t.filter(t=>t.id!==e);return a.length>0?h(a[0].id):h(null),a})}catch{}},[r,h]),g=(0,_.useRef)(r);g.current=r;let f=(0,_.useCallback)((e,t)=>{let a=t||g.current;a&&(o.current&&clearTimeout(o.current),c.current=a,o.current=setTimeout(async()=>{if(c.current===a)try{await (0,er.authFetch)(`/api/synthesizer/algo/${a}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({chat_messages:e})})}catch{}},800))},[]),b=(0,_.useCallback)(async(e,n)=>{let l=n||r;if(l)try{await (0,er.authFetch)(`/api/synthesizer/algo/${l}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),t(t=>t.map(t=>t.id===l?{...t,...e}:t)),a?.id===l&&s(t=>t?{...t,...e}:t)}catch{}},[r,a?.id]);return(0,_.useEffect)(()=>{d().then(()=>{r&&!a&&u(r)})},[]),{sessions:e,activeSession:a,activeId:r,loading:l,setActiveId:h,createSession:p,renameSession:m,deleteSession:x,saveMessages:f,updateSessionContext:b,refreshSessions:d}}(),t=function(){let[e,t]=(0,_.useState)(null),[a,s]=(0,_.useState)(null),[r,n]=(0,_.useState)([]),[l,i]=(0,_.useState)([]),[o,c]=(0,_.useState)(null),[d,u]=(0,_.useState)(!1),[h,p]=(0,_.useState)(null),m=(0,_.useRef)(null),x=(0,_.useCallback)(async t=>{let a=t||e?.id;if(a)try{let e=await (0,er.authFetch)(`/api/synthesizer/paper/status?session_id=${a}`),t=await e.json();t.ok&&s(e=>t.risk_state||!e?.risk_state?t:{...t,risk_state:e.risk_state})}catch{}},[e]),g=(0,_.useCallback)(async e=>{try{let t=new URLSearchParams;e?.mode&&t.set("mode",e.mode),e?.status&&t.set("status",e.status),Number.isFinite(e?.limit)&&t.set("limit",String(Math.max(1,Number(e?.limit))));let a=await (0,er.authFetch)(`/api/synthesizer/paper/leaderboard${t.toString()?`?${t.toString()}`:""}`),s=await a.json();s.ok&&i(s.leaderboard||[])}catch{}},[]),f=(0,_.useCallback)(async e=>{let t=new AbortController;m.current=t;try{let a=await (0,er.authFetch)(`/api/synthesizer/paper/stream?session_id=${e}`,{signal:t.signal});if(!a.ok)return;let r=a.body.getReader(),l=new TextDecoder,i="";for(;;){let{done:t,value:a}=await r.read();if(t)break;let o=(i+=l.decode(a,{stream:!0})).split("\n");for(let t of(i=o.pop()||"",o))if(t.startsWith("data: "))try{let a=JSON.parse(t.slice(6));if("done"===a.type||"session_stopped"===a.type)return void x(e);("signal_fired"===a.type||"position_update"===a.type||"equity_update"===a.type)&&n(e=>[...e.slice(-99),a]),("decay_alert"===a.type||"decay_recovered"===a.type||"risk_downgrade"===a.type||"risk_kill_switch"===a.type)&&(n(e=>[...e.slice(-99),a]),c(a),("number"==typeof a.position_pct||"number"==typeof a.consecutive_decay_hits||"string"==typeof a.risk_mode)&&s(e=>{if(!e)return e;let t=e.risk_state;return{...e,risk_state:{mode:a.risk_mode||t?.mode||"normal",position_pct:"number"==typeof a.position_pct?a.position_pct:t?.position_pct??.05,consecutive_decay_hits:"number"==typeof a.consecutive_decay_hits?a.consecutive_decay_hits:t?.consecutive_decay_hits??0,kill_switch_triggered:"risk_kill_switch"===a.type||!!t?.kill_switch_triggered,downgrade_after:t?.downgrade_after,kill_after:t?.kill_after,half_life_max_hours:t?.half_life_max_hours,min_edge_decay_pct:t?.min_edge_decay_pct}}}),x(e),g({limit:20})),"equity_update"===a.type&&a.snapshot&&s(e=>e?{...e,equity:a.snapshot.equity,unrealized_pnl:a.snapshot.unrealized_pnl,realized_pnl:a.snapshot.realized_pnl,open_positions:a.snapshot.open_positions}:null)}catch{}}}catch(t){"AbortError"!==t.name&&setTimeout(()=>f(e),5e3)}},[x,g]),b=(0,_.useCallback)(async e=>{u(!0),p(null);try{let a=await (0,er.authFetch)("/api/synthesizer/paper/start",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)}),s=await a.json();if(!s.ok)return p(s.error||"Failed to start session"),null;return t(s.session),x(s.session.id),g({mode:s.session?.mode||e.mode||"paper",limit:20}),s.session?.mode==="paper"?f(s.session.id):x(s.session.id),s.session}catch(e){return p(e.message),null}finally{u(!1)}},[f,x,g]),v=(0,_.useCallback)(async a=>{let r=a||e?.id;if(r){u(!0);try{m.current&&m.current.abort();let a=await (0,er.authFetch)("/api/synthesizer/paper/stop",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:r})}),n=await a.json();n.ok&&(s(n),t(e=>e?{...e,status:"stopped"}:null),g({mode:e?.mode||"paper",limit:20}))}catch(e){p(e.message)}finally{u(!1)}}},[e,g]),y=(0,_.useCallback)(()=>{m.current&&m.current.abort()},[]);return(0,_.useEffect)(()=>{g({limit:20})},[g]),(0,_.useEffect)(()=>{let t=e?.id,s="running"===(a?.session?.status||e?.status);if(!t||e?.mode!=="live"||!s)return;let r=window.setInterval(()=>{x(t),g({mode:"live",limit:20})},15e3);return()=>window.clearInterval(r)},[e?.id,e?.status,e?.mode,a?.session?.status,x,g]),{session:e,status:a,signals:r,decayAlert:o,leaderboard:l,loading:d,error:h,startSession:b,stopSession:v,refreshStatus:x,refreshLeaderboard:g,disconnect:y}}
1(),a=function(e){let[t,a]=(0,_.useState)({...en}),[s,r]=(0,_.useState)(null),[n,l]=(0,_.useState)(!1),[i,o]=(0,_.useState)(!1),c=(0,_.useRef)(null),d=(0,_.useRef)(e?.sessionId);d.current=e?.sessionId;let u=(0,_.useRef)(0),h=(0,_.useCallback)((e,t)=>{a(a=>({...a,[e]:t}))},[]),p=(0,_.useCallback)(e=>{a(t=>({...t,...e}))},[]),m=(0,_.useCallback)(()=>o(!0),[]),x=(0,_.useCallback)(()=>o(!1),[]),g=(0,_.useCallback)(e=>{u.current=Date.now()+500,c.current&&clearTimeout(c.current),r(e)},[]),f=(0,_.useCallback)(()=>{a({...en}),r(null),o(!1),l(!1),c.current&&clearTimeout(c.current)},[]);return(0,_.useEffect)(()=>{if(!(!i||Date.now()<u.current)&&t.hourset&&0!==t.hourset.length)return c.current&&clearTimeout(c.current),c.current=setTimeout(async()=>{l(!0);try{let e=await (0,er.authPostJson)("/api/synth/strategy-simulate",{...t,session_id:d.current??void 0,lookback_days:60});e.ok&&r({equity_curve:e.equity_curve,stats:e.stats,cnl_text:e.cnl_text})}catch{}finally{l(!1)}},250),()=>{c.current&&clearTimeout(c.current)}},[i,t]),{params:t,result:s,loading:n,active:i,setParam:h,setParams:p,activate:m,deactivate:x,setExternalResult:g,reset:f}}({sessionId:e.activeId}),[s,r]=(0,_.useState)("paper"),[n,l]=(0,_.useState)(null),[i,o]=(0,_.useState)(null),[c,d]=(0,_.useState)(null),u=(0,_.useRef)(null),h=(0,_.useRef)(!1),p=(0,_.useCallback)((t,a)=>{e.saveMessages(t,a)},[e.saveMessages]),m=(0,es.default)({initialMessages:e.activeSession?.chat_messages??[],onMessagesChange:p,sessionId:e.activeId}),x=(0,_.useCallback)(async()=>{if(e.activeId)return e.activeId;h.current=!0;let t=await e.createSession();return t?.id?t.id:null},[e.activeId,e.createSession]);(0,_.useEffect)(()=>{if(h.current){e.activeId&&(h.current=!1,u.current=e.activeId);return}if(!e.activeId){null!==u.current&&(u.current=null,m.reset([]),l(null),o(null),d(null),a.reset());return}if(!e.activeSession||e.activeSession.id!==e.activeId||u.current===e.activeId)return;u.current=e.activeId;let r=e.activeSession;m.reset(r.chat_messages||[]),l(r.market_data||null),o(r.strategy_name||null),d(r.strategy_rules||null),a.reset(),r.paper_session_id&&r.status?.includes("running")&&t.refreshStatus(r.paper_session_id),t.refreshLeaderboard({mode:s,limit:20})},[e.activeId,e.activeSession,s,t.refreshStatus,t.refreshLeaderboard]),(0,_.useEffect)(()=>{t.refreshLeaderboard({mode:s,limit:20})},[s,t.refreshLeaderboard]),(0,_.useEffect)(()=>{if(0===m.messages.length)return;let t=null,s=null,r=null,n=null,i=!1,c=!1;for(let e=m.messages.length-1;e>=0;e--){let a=m.messages[e];if(a?.blocks){for(let l of a.blocks)!t&&"market"===l.type&&l.market&&(t=l.market,i=e===m.messages.length-1),!s&&"strategy"===l.type&&l.strategy&&(s=l.strategy,c=e===m.messages.length-1),r||"cnl_generated"!==l.type||(r=l),n||"campaign_results"!==l.type||(n=l);if(t&&s&&r&&n)break}}if(t&&(l(t),i&&e.updateSessionContext({market_slug:t.slug||null,market_question:t.question||null,market_data:t}
1)),s&&(o(s.name||null),d(s.rules||null),c&&e.updateSessionContext({strategy_name:s.name||null,strategy_rules:s.rules||null})),n){let e=n;e.equity_curve&&Array.isArray(e.equity_curve)&&e.equity_curve.length>0&&a.setExternalResult({equity_curve:e.equity_curve,stats:{total_pnl:e.total_pnl||0,final_equity:e.final_equity||0,initial_equity:0,max_drawdown:e.max_drawdown||0,win_count:e.win_count||0,loss_count:e.loss_count||0,blown:e.blown||0,total_bets:(e.win_count||0)+(e.loss_count||0),campaigns:e.campaigns||0},cnl_text:""})}if(r){let e=r.params,t={...r.cnl_text?function(e){let t={},a=e.match(/STRATEGY\s+"([^"]+)"/);a&&(t.strategy_name=a[1]);let s=e.match(/ASSET\s+IN\s+\[(\w+)\]/);s&&(t.asset=s[1]);let r=e.match(/INTERVAL\s*=\s*"(\w+)"/);r&&(t.tf=r[1]);let n=e.match(/TIME\(hour_et\s+IN\s+\[([^\]]+)\]\)/);n&&(t.hourset=n[1].split(",").map(e=>parseInt(e.trim(),10)).filter(Number.isFinite));let l=e.match(/STREAK\(.*?len=(\d+)/);l&&(t.streak=parseInt(l[1],10));let i=e.match(/STREAK\(.*?exact=(true|false)/);i&&(t.exact="true"===i[1]),/dir=UP/.test(e)?t.trigger_mode="both":t.trigger_mode="down_only";let o=[...e.matchAll(/size=USD\((\d+(?:\.\d+)?)\)/g)];if(o.length>0){let e=o.map(e=>parseFloat(e[1])),a=Math.min(...e);t.base_usd=a,t.multipliers=e.map(e=>e/a)}return t}(r.cnl_text):{},...e};Object.keys(t).length>0&&(a.setParams(t),a.activate())}},[m.messages]);let g=(0,_.useCallback)(async e=>{let t=await x();m.send(e,t)},[m.send,x]),f=(0,_.useCallback)(async()=>{let a=await x();if(a){if(!n||!c)return void m.send("I want to start paper trading. Help me select a market and define a strategy first.",a);t.startSession({strategy_name:i||"Unnamed Strategy",rules:c,market_slug:n.slug,market:n,mode:s}).then(t=>{t&&e.updateSessionContext({paper_session_id:t.id,status:"live"===s?"live_running":"paper_running"},a)})}},[n,c,i,s,t.startSession,m.send,e.updateSessionContext,x]),v=(0,_.useCallback)(()=>{t.stopSession();let a=t.session?.mode==="live"?"live_stopped":"paper_stopped";e.updateSessionContext({status:a})},[t.stopSession,t.session?.mode,e.updateSessionContext]),y=(0,_.useCallback)(e=>{g(`Here is the tuned CNL strategy:
2\`\`\`
3${e}
4\`\`\``)},[g]),j=t.session?.status==="running";return(0,b.jsxs)("div",{className:"synth-layout",children:[(0,b.jsx)(el,{sessions:e.sessions,activeId:e.activeId,loading:e.loading,onSelect:e.setActiveId,onCreate:()=>e.createSession(),onRename:e.renameSession,onDelete:e.deleteSession}),(0,b.jsx)("div",{className:"synth-layout-chat",children:(0,b.jsx)(eN,{messages:m.messages,streaming:m.streaming,onSend:g,isRunning:j,mode:s,onModeChange:r,onPlay:f,onStop:v,playDisabled:!n||!c,sessionName:e.activeSession?.name})}),(0,b.jsx)("div",{className:"synth-layout-context",children:(0,b.jsx)(eF,{market:n,strategyRules:c,strategyName:i,paperStatus:t.status,paperLeaderboard:t.leaderboard,decayAlert:t.decayAlert,signals:t.signals,sessionActive:j,algoName:e.activeSession?.name,onRefreshLeaderboard:()=>t.refreshLeaderboard({mode:s,limit:20}),dashboardActive:a.active,dashboardParams:a.params,dashboardResult:a.result,dashboardLoading:a.loading,onDashboardParamChange:a.setParam,onDashboardApply:y,onDashboardReset:a.reset})})]})}function eR({data:e}){if(!e||e.length<2)return null;let t=e.map(e=>e.equity),a=Math.min(...t),s=Math.max(...t),r=Math.max(s-a,.01),n=t.map((e,a)=>{let n=2+a/(t.length-1)*196;return`${n.toFixed(1)},${(2+(s-e)/r*56).toFixed(1)}`}).join(" "),l=t[t.length-1],i=t[0];return(0,b.jsx)("svg",{viewBox:"0 0 200 60",className:"trader-sidebar-equity-svg",children:(0,b.jsx)("polyline",{points:n,fill:"none",stroke:l>=i?"var(--color-long)":"var(--color-short)",strokeWidth:"1.5",strokeLinejoin:"round"})})}function eO({candidates:e,selectedIndex:t,onSelect:a}){return 0===e.length?null:(0,b.jsxs)("div",{className:"hunt-candidate-list",children:[(0,b.jsxs)("div",{className:"hunt-candidate-list-header",children:["Similar Traders (",e.length,")"]}),(0,b.jsx)("div",{className:"hunt-candidate-list-scroll",children:e.map((e,s)=>(0,b.jsxs)("button",{className:`hunt-candidate-card ${t===s?"active":""}`,onClick:()=>a(s),children:[(0,b.jsxs)("span",{className:"hunt-candidate-rank",children:["#",s+1]}),(0,b.jsx)("div",{className:"hunt-candidate-bar-wrap",children:(0,b.jsx)("div",{className:"hunt-candidate-bar",style:{width:`${e.similarityScore}%`}})}),(0,b.jsxs)("span",{className:"hunt-candidate-score",children:[e.similarityScore,"%"]}),(0,b.jsxs)("div",{className:"hunt-candidate-info",children:[(0,b.jsx)("span",{className:"hunt-candidate-name",children:e.userName||`${e.wallet.slice(0,6)}...${e.wallet.slice(-4)}`}),(0,b.jsxs)("span",{className:`hunt-candidate-pnl ${e.pnl>=0?"up":"down"}`,children:[e.pnl>=0?"+":"",(0,S.fmtUsd)(e.pnl,0)]})]})]},e.wallet))})]})}function eL({label:e,profile:t}){let a=t.userName||`${t.wallet.slice(0,6)}...${t.wallet.slice(-4)}`,s=t.categories.filter(e=>e.vol>0).map(e=>{let a=t.totalVol||1;return{name:e.category,pct:e.vol/a*100}}).sort((e,t)=>
4t.pct-e.pct);return(0,b.jsxs)("div",{className:"hunt-profile-col",children:[(0,b.jsx)("div",{className:"hunt-profile-label",children:e}),(0,b.jsxs)("div",{className:"trader-sidebar-header",children:[(0,b.jsx)("div",{className:"trader-sidebar-avatar",children:t.profileImage?(0,b.jsx)("img",{src:t.profileImage,alt:"",width:36,height:36}):(0,b.jsx)(N,{size:20})}),(0,b.jsxs)("div",{children:[(0,b.jsx)("div",{className:"trader-sidebar-name",children:a}),(0,b.jsxs)("div",{className:"trader-sidebar-wallet",children:[t.wallet.slice(0,8),"...",t.wallet.slice(-6)]})]})]}),(0,b.jsxs)("div",{className:"trader-sidebar-classification",children:[(0,b.jsx)("span",{className:`trader-sidebar-class-badge ${"market_maker"===t.classification?"mm":"dir"}`,children:"market_maker"===t.classification?"Market Maker":"Directional"}),(0,b.jsxs)("span",{className:"trader-sidebar-class-score",children:[(0,S.fmtPct)(100*t.classificationScore,0)," confidence"]})]}),t.equityCurve&&t.equityCurve.length>1&&(0,b.jsxs)("div",{className:"trader-sidebar-equity",children:[(0,b.jsx)("div",{className:"trader-sidebar-section-title",children:"Equity Curve"}),(0,b.jsx)(eR,{data:t.equityCurve})]}),(0,b.jsxs)("div",{className:"trader-sidebar-stats",children:[(0,b.jsx)("div",{className:"trader-sidebar-section-title",children:"PnL"}),(0,b.jsxs)("div",{className:"trader-sidebar-stats-grid",children:[(0,b.jsxs)("div",{className:"trader-sidebar-stat",children:[(0,b.jsx)("span",{className:"label",children:"Today"}),(0,b.jsxs)("span",{className:t.pnlToday>=0?"up":"down",children:[t.pnlToday>=0?"+":"",(0,S.fmtUsd)(t.pnlToday,0)]})]}),(0,b.jsxs)("div",{className:"trader-sidebar-stat",children:[(0,b.jsx)("span",{className:"label",children:"Week"}),(0,b.jsxs)("span",{className:t.pnlWeek>=0?"up":"down",children:[t.pnlWeek>=0?"+":"",(0,S.fmtUsd)(t.pnlWeek,0)]})]}),(0,b.jsxs)("div",{className:"trader-sidebar-stat",children:[(0,b.jsx)("span",{className:"label",children:"Month"}),(0,b.jsxs)("span",{className:t.pnlMonth>=0?"up":"down",children:[t.pnlMonth>=0?"+":"",(0,S.fmtUsd)(t.pnlMonth,0)]})]}),(0,b.jsxs)("div",{className:"trader-sidebar-stat",children:[(0,b.jsx)("span",{className:"label",children:"All Time"}),(0,b.jsxs)("span",{className:t.totalPnl>=0?"up":"down",children:[t.totalPnl>=0?"+":"",(0,S.fmtUsd)(t.totalPnl,0)]})]})]})]}),(0,b.jsxs)("div",{className:"trader-sidebar-stats",children:[(0,b.jsx)("div",{className:"trader-sidebar-section-title",children:"Performance"}),(0,b.jsxs)("div",{className:"trader-sidebar-stats-grid",children:[(0,b.jsxs)("div",{className:"trader-sidebar-stat",children:[(0,b.jsx)("span",{className:"label",children:"Win Rate"}),(0,b.jsx)("span",{children:(0,S.fmtPct)(t.winRate,1)})]}),(0,b.jsxs)("div",{className:"trader-sidebar-stat",children:[(0,b.jsx)("span",{className:"label",children:"Max DD"}),(0,b.jsx)("span",{className:"down",children:(0,S.fmtPct)(t.maxDrawdownPct,1)})]}),(0,b.jsxs)("div",{className:"trader-sidebar-stat",children:[(0,b.jsx)("span",{className:"label",children:"Markets"}),(0,b.jsx)("span",{children:(0,S.fmtNum)(t.numMarkets)})]}),(0,b.jsxs)("div",{className:"trader-sidebar-stat",children:[(0,b.jsx)("span",{className:"label",children:"Trades"}),(0,b.jsx)("span",{children:(0,S.fmtNum)(t.totalTrades)})]}),(0,b.jsxs)("div",{className:"trader-sidebar-stat",children:[(0,b.jsx)("span",{className:"label",children:"Avg Size"}),(0,b.jsx)("span",{children:(0,S.fmtUsd)(t.avgPositionSize,0)})]}),(0,b.jsxs)("div",{className:"trader-sidebar-stat",children:[(0,b.jsx)("span",{className:"label",children:"Volume"}),(0,b.jsx)("span",{children:(0,S.fmtUsd)(t.totalVol,0)})]}),(0,b.jsxs)("div",{className:"trader-sidebar-stat",children:[(0,b.jsx)("span",{className:"label",children:"Period"}),(0,b.jsxs)("span",{children:[t.periodDays,"d"]})]}),(0,b.jsxs)("div",{className:"trader-sidebar-stat",children:[(0,b.jsx)("span",{className:"label",children:"Avg Hold"}),(0,b.jsx)("span",{children:function(e){if(!e||e<=0)return"—";if(e<1)return`${Math.round(60*e)}m`;if(e<24)return`${e.toFixed(1)}h`;let t=e/24;return t<30?`${t.toFixed(1)}d`:`${(t/30).toFixed(1)}mo`}(t.avgHoldHours)})]})]})]}),s.length>0&&(0,b.jsxs)("div",{className:"hunt-profile-cats",children:[(0,b.jsx)("div",{className:"trader-sidebar-section-title",children:"Categories"}),s.map(e=>(0,b.jsxs)("div",{className:"hunt-cat-row",children:[(0,b.jsx)("span",{className:"hunt-cat-name",children:e.name}),(0,b.jsx)("div",{className:"hunt-cat-bar-wrap",children:(0,b.jsx)("div",{className:"hunt-cat-bar",style:{width:`${Math.min(100,e.pct)}%`}})}),(0,b.jsxs)("span",{className:"hunt-cat-pct",children:[e.pct.toFixed(0),"%"]})]},e.name))]}
4),t.topMarkets&&t.topMarkets.length>0&&(0,b.jsxs)("div",{className:"trader-sidebar-markets",children:[(0,b.jsx)("div",{className:"trader-sidebar-section-title",children:"Top Markets"}),(0,b.jsx)("div",{className:"trader-sidebar-market-list",children:t.topMarkets.slice(0,10).map(e=>(0,b.jsxs)("div",{className:"trader-sidebar-market-item",children:[(0,b.jsx)("span",{className:"trader-sidebar-market-slug",children:e.market}),(0,b.jsxs)("span",{className:"trader-sidebar-market-meta",children:[0!==e.pnl&&(0,b.jsxs)("span",{className:e.pnl>=0?"up":"down",children:[e.pnl>=0?"+":"",(0,S.fmtUsd)(e.pnl,0)]}),e.trades>0&&(0,b.jsxs)("span",{className:"trader-sidebar-market-count",children:[e.trades,"t"]})]})]},e.market))})]}),t.recentTrades&&t.recentTrades.length>0&&(0,b.jsxs)("div",{className:"trader-sidebar-markets",children:[(0,b.jsx)("div",{className:"trader-sidebar-section-title",children:"Latest Activity"}),(0,b.jsx)("div",{className:"trader-sidebar-market-list",children:t.recentTrades.map((e,t)=>{var a;let s,r=(a=e.timestamp,(s=Date.now()/1e3-a)<60?"just now":s<3600?`${Math.floor(s/60)}m ago`:s<86400?`${Math.floor(s/3600)}h ago`:s<604800?`${Math.floor(s/86400)}d ago`:`${Math.floor(s/604800)}w ago`);return(0,b.jsxs)("div",{className:"hunt-trade-item",children:[(0,b.jsx)("div",{className:"hunt-trade-title",children:e.title}),(0,b.jsxs)("div",{className:"hunt-trade-meta",children:[(0,b.jsx)("span",{className:`hunt-trade-side ${"BUY"===e.side?"buy":"sell"}`,children:e.side}),(0,b.jsx)("span",{className:"hunt-trade-outcome",children:e.outcome}),(0,b.jsx)("span",{className:"hunt-trade-size",children:(0,S.fmtUsd)(e.size*e.price,0)}),(0,b.jsxs)("span",{className:"hunt-trade-price",children:["@",e.price.toFixed(2)]}),(0,b.jsx)("span",{className:"hunt-trade-ago",children:r})]})]},`${e.slug}-${e.timestamp}-${t}`)})})]})]})}function eI({target:e,candidate:t,candidateProfile:a,candidateProfileLoading:s,stage:r,loading:n,totalFound:l,totalAnalyzed:i}){return(0,b.jsxs)("div",{className:"hunt-comparison",children:[(0,b.jsxs)("div",{className:`hunt-comparison-grid ${t?"two-col":"one-col"}`,children:[(0,b.jsx)(eL,{label:"TARGET",profile:e}),t&&(a?(0,b.jsx)(eL,{label:`COMPARE — ${t.similarityScore}% match`,profile:a}):(0,b.jsxs)("div",{className:"hunt-profile-col",children:[(0,b.jsxs)("div",{className:"hunt-profile-label",children:["COMPARE — ",t.similarityScore,"% match"]}),(0,b.jsxs)("div",{className:"trader-sidebar-header",children:[(0,b.jsx)("div",{className:"trader-sidebar-avatar",children:t.profileImage?(0,b.jsx)("img",{src:t.profileImage,alt:"",width:36,height:36}):(0,b.jsx)(N,{size:20})}),(0,b.jsxs)("div",{children:[(0,b.jsx)("div",{className:"trader-sidebar-name",children:t.userName||`${t.wallet.slice(0,6)}...${t.wallet.slice(-4)}`}),(0,b.jsxs)("div",{className:"trader-sidebar-wallet",children:[t.wallet.slice(0,8),"...",t.wallet.slice(-6)]})]})]}),(0,b.jsxs)("div",{className:"trader-sidebar-stats",children:[(0,b.jsx)("div",{className:"trader-sidebar-section-title",children:"Leaderboard Stats"}),(0,b.jsxs)("div",{className:"trader-sidebar-stats-grid",children:[(0,b.jsxs)("div",{className:"trader-sidebar-stat",children:[(0,b.jsx)("span",{className:"label",children:"PnL"}),(0,b.jsxs)("span",{className:t.pnl>=0?"up":"down",children:[t.pnl>=0?"+":"",(0,S.fmtUsd)(t.pnl,0)]})]}),(0,b.jsxs)("div",{className:"trader-sidebar-stat",children:[(0,b.jsx)("span",{className:"label",children:"Volume"}),(0,b.jsx)("span",{children:(0,S.fmtUsd)(t.volume,0)})]}),(0,b.jsxs)("div",{className:"trader-sidebar-stat",children:[(0,b.jsx)("span",{className:"label",children:"Rank"}),(0,b.jsxs)("span",{children:["#",(0,S.fmtNum)(t.rank)]})]})]})]}),s&&(0,b.jsx)("div",{className:"trader-sidebar-loading",children:"Loading full profile..."})]}))]}),n&&(0,b.jsxs)("div",{className:"hunt-progress",children:[r&&(0,b.jsx)("div",{className:"hunt-progress-text",children:r}),l>0&&(0,b.jsxs)("div",{className:"hunt-progress-counts",children:["Found: ",l," | Analyzed: ",i]}),(0,b.jsx)("div",{className:"hunt-progress-bar",children:(0,b.jsx)("div",{className:"hunt-progress-fill",style:{width:l>0?`${Math.min(100,i/Math.max(1,l)*100)}%`:"0%"}})})]})]})}function eD(){let[e,t]=(0,_.useState)(""),{stage:a,target:s,candidates:r,selectedCandidate:n,candidateProfile:l,candidateProfileLoading:i,totalFound:o,totalAnalyzed:c,loading:d,error:u,hunt:h,selectCandidate:p,clear:m}=function(){let[e,t]=(0,_.useState)(null),[a,s]=(0,_.useState)(null),[r,n]=(0,_.useState)([]),[l,i]=(0,_.useState)(null),[o,c]=(0,_.useState)(null),[d,u]=(0,_.useState)(!1),[h,p]=(0,_.useState)(0),[m,x]=(0,_.useState)(0),[g,f]=(0,_.useState)(!1),[b,v]=(0,_.useState)(null),j=(0,_.useRef)(null),w=(0,_.useRef)(null),N=(0,_.useRef)(new Map),k=(0,_.useCallback)(async(e,a=25)=>{if(!e)return;j.current&&j.current.abort(),f(!0),v(null),t(null),s(null),n([]),i(null),c(null),u(!1),p(0),x(0),N.current.clear();let r=new AbortController;j.current=r;
4try{let l=`${y.API_BASE}/api/trader/${encodeURIComponent(e)}/hunt?pages=${a}`,i=await fetch(l,{signal:r.signal});if(!i.ok){let e=await i.text();throw Error(`${i.status}: ${e}`)}let o=i.body.getReader(),c=new TextDecoder,d="",u=e=>{let a;if(!e.startsWith("data: "))return!1;let r=e.slice(6).trim();if(!r)return!1;try{a=JSON.parse(r)}catch{return!1}switch(a.type){case"hunt_stage":t(a.message);break;case"hunt_target":s({wallet:a.wallet,userName:a.userName||"",profileImage:a.profileImage||"",categories:a.categories||[],active_categories:a.active_categories||[],winRate:a.winRate||0,totalPnl:a.totalPnl||0,totalVol:a.totalVol||0,pnlToday:a.pnlToday||0,pnlWeek:a.pnlWeek||0,pnlMonth:a.pnlMonth||0,numMarkets:a.numMarkets||0,totalTrades:a.totalTrades||0,avgEntryPrice:a.avgEntryPrice||0,avgPositionSize:a.avgPositionSize||0,avgHoldHours:a.avgHoldHours||0,maxDrawdownPct:a.maxDrawdownPct||0,periodDays:a.periodDays||0,holdToResolutionRatio:a.holdToResolutionRatio||0,marketConcentration:a.marketConcentration||0,classification:a.classification||"directional",classificationScore:a.classificationScore||1,equityCurve:a.equityCurve||[],topMarkets:a.topMarkets||[],recentTrades:a.recentTrades||[]});break;case"hunt_progress":p(a.totalFound||0),x(a.totalAnalyzed||0);break;case"hunt_results":n(a.candidates||[]);break;case"done":return!0}return!1},h=!1;for(;!h;){let{done:e,value:t}=await o.read();if(e)break;let a=(d+=c.decode(t,{stream:!0})).split("\n");for(let e of(d=a.pop()||"",a))if(u(e)){h=!0;break}}if(!h&&d.trim()){for(let e of d.split("\n"))if(u(e))break}}catch(e){"AbortError"!==e.name&&v(e.message)}finally{f(!1),j.current=null}},[]);return{stage:e,target:a,candidates:r,selectedCandidate:l,candidateProfile:o,candidateProfileLoading:d,totalFound:h,totalAnalyzed:m,loading:g,error:b,hunt:k,selectCandidate:(0,_.useCallback)(async(e,t)=>{if(i(e),w.current&&w.current.abort(),null===e){c(null),u(!1);return}if(!t||e>=t.length)return void c(null);let a=t[e].wallet,s=N.current.get(a);if(s){c(s),u(!1);return}c(null),u(!0);let r=new AbortController;w.current=r;try{let e=`${y.API_BASE}/api/trader/${encodeURIComponent(a)}/hunt-profile`,t=await fetch(e,{signal:r.signal});if(!t.ok)throw Error(`${t.status}`);let s=await t.json();if(s.ok&&s.profile){let e=s.profile;N.current.set(a,e),c(e)}}catch(e){"AbortError"!==e.name&&c(null)}finally{u(!1),w.current=null}},[]),clear:(0,_.useCallback)(()=>{j.current&&j.current.abort(),w.current&&w.current.abort(),t(null),s(null),n([]),i(null),c(null),u(!1),p(0),x(0),v(null),f(!1),N.current.clear()},[])}}(),x=(0,_.useCallback)((e,a)=>{m(),t(e),h(e)},[h,m]),g=(0,_.useCallback)(e=>{p(n===e?null:e,r)},[p,n,r]);return(0,b.jsxs)("div",{className:"hunt-view",children:[(0,b.jsxs)("div",{className:"hunt-view-header",children:[(0,b.jsx)($,{onSelect:x}),d&&a&&!s&&(0,b.jsxs)("div",{className:"hunt-stage-indicator",children:[(0,b.jsx)("span",{className:"hunt-stage-dot"}),a]}),u&&(0,b.jsx)("div",{className:"hunt-error",children:u})]}),(0,b.jsxs)("div",{className:"hunt-view-body",children:[r.length>0&&(0,b.jsx)("div",{className:"hunt-sidebar",children:(0,b.jsx)(eO,{candidates:r,selectedIndex:n,onSelect:g})}),(0,b.jsx)("div",{className:"hunt-main",children:s?(0,b.jsx)(eI,{target:s,candidate:null!==n?r[n]??null:null,candidateProfile:l,candidateProfileLoading:i,stage:a,loading:d,totalFound:o,totalAnalyzed:c}):d?(0,b.jsxs)("div",{className:"hunt-loading",children:[(0,b.jsx)("div",{className:"hunt-stage-dot"}),(0,b.jsx)("span",{children:a||"Starting hunt..."})]}):(0,b.jsxs)("div",{className:"hunt-empty",children:[(0,b.jsx)("div",{className:"hunt-empty-title",children:"Trader Hunt"}),(0,b.jsx)("div",{className:"hunt-empty-desc",children:"Search for a trader to find similar profiles by trading style, category preferences, win rate, and position sizing."})]})})]})]})}var ez=e.i(70071);let eB=[{key:"all",label:"All tape"},{key:"high",label:"High signal"},{key:"contrarian",label:"Against OpenPoly"},{key:"entries",label:"Entries + adds"},{key:"exits",label:"Trims + exits"},{key:"locks",label:"Resolution locks"}];function eW(e,t=!1){let a=Number(e||0);return t&&Math.abs(a)>=1e6?`${a<0?"-":""}$${(Math.abs(a)/1e6).toFixed(1)}m`:t&&Math.abs(a)>=1e3?`${a<0?"-":""}$${(Math.abs(a)/1e3).toFixed(a>=1e5?0:1)}k`:`${a<0?"-":""}
4$${Math.abs(a).toLocaleString(void 0,{maximumFractionDigits:2*(a<100)})}`}function eU(e,t=!1){let a=Number(e||0);return`${a>=0?"+":""}${eW(a,t)}`}function eH(e){return null==e?"—":`${Math.round(100*Number(e))}\xa2`}function eq(e,t){if(!e)return"quiet";let a=Math.max(0,Math.floor((t-e)/1e3));return a<8?"now":a<60?`${a}s`:a<3600?`${Math.floor(a/60)}m`:a<86400?`${Math.floor(a/3600)}h`:`${Math.floor(a/86400)}d`}function eV({trader:e,small:t=!1}){return(0,b.jsx)("span",{className:`tw-avatar${t?" small":""}`,children:e.avatar?(0,b.jsx)("img",{src:e.avatar,alt:""}):(e.name||e.handle).split(/[-_\s]+/).filter(Boolean).slice(0,2).map(e=>e[0]?.toUpperCase()).join("")||"?"})}function eG(e){return null==e?"—":`${String((e+24)%24).padStart(2,"0")}:00`}function eJ(e,t){let a=new Date;a.setUTCHours(e,0,0,0);try{return new Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",hourCycle:"h23",timeZone:t}).format(a)}catch{return eG(e)}}function eY({trader:e,selected:t,now:a,onSelect:s}){let r,n=(r=a-e.last_active_ms)<=9e5?{cls:"hot",label:"on tape"}:r<=216e5?{cls:"warm",label:"active"}:{cls:"quiet",label:"quiet"};return(0,b.jsxs)("button",{className:`tw-trader-card${t?" selected":""}`,onClick:s,children:[(0,b.jsxs)("div",{className:"tw-trader-card-head",children:[(0,b.jsx)(eV,{trader:e}),(0,b.jsxs)("span",{className:"tw-trader-identity",children:[(0,b.jsxs)("b",{children:["@",e.handle]}),(0,b.jsxs)("span",{className:`tw-presence ${n.cls}`,children:[(0,b.jsx)("i",{}),n.label," · ",eq(e.last_active_ms,a)]})]}),(e.hedge_profile?.hedged_markets||0)>0&&(0,b.jsxs)("span",{className:"tw-card-hedge",title:`${e.hedge_profile?.hedged_markets} visible offset books`,children:["H",Math.round(e.hedge_profile?.portfolio_hedged_pct||0),"%"]}),e.verified&&(0,b.jsx)("span",{className:"tw-verified",title:"Verified Polymarket profile",children:"✓"})]}),(0,b.jsxs)("div",{className:"tw-trader-numbers",children:[(0,b.jsxs)("span",{children:[(0,b.jsx)("small",{children:"all-time pnl"}),(0,b.jsx)("b",{className:(e.lifetime_pnl||0)>=0?"up":"down",children:null==e.lifetime_pnl?"—":eU(e.lifetime_pnl,!0)})]}),(0,b.jsxs)("span",{children:[(0,b.jsx)("small",{children:"24h tape"}),(0,b.jsx)("b",{children:eW(e.recent_flow_24h,!0)})]}),(0,b.jsxs)("span",{children:[(0,b.jsx)("small",{children:"visible book"}),(0,b.jsx)("b",{children:eW(e.portfolio_value,!0)})]})]})]})}function eK({trader:e,timeZone:t}){let a=e.activity_profile,s=a?.hour_distribution_utc?.length===24?a.hour_distribution_utc:Array(24).fill(0),r=Math.max(1,...s),n=s.map((e,a)=>({count:e,utcHour:a,local:eJ(a,t)})).sort((e,t)=>e.local.localeCompare(t.local)),l=a?.active_window_utc?.start,i=a?.active_window_utc?.end,o=t.replaceAll("_"," ").replace("/"," / ");return(0,b.jsxs)("div",{className:"tw-dossier-block tw-activity-block",children:[(0,b.jsxs)("div",{className:"tw-dossier-label",children:[(0,b.jsx)("span",{children:"OBSERVED ACTIVE WINDOW"}),(0,b.jsx)("small",{children:o})]}),null!=l&&null!=i?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)("div",{className:"tw-window-call",children:[(0,b.jsxs)("b",{children:[eJ(l,t),"–",eJ(i,t)]}),(0,b.jsx)("span",{children:"your time"})]}),(0,b.jsxs)("div",{className:"tw-window-sub",children:[eG(l),"–",eG(i)," UTC · ",Math.round(100*(a?.active_window_utc.share||0)),"% of observed moves",a?.dominant_session?` \xb7 ${a.dominant_session.label} overlap ${Math.round(100*a.dominant_session.share)}%`:"",a?.peak_day?` \xb7 peak ${a.peak_day}`:""]})]}):(0,b.jsx)("div",{className:"tw-window-empty",children:"Not enough public fills yet."}),(0,b.jsx)("div",{className:"tw-hour-strip",role:"img","aria-label":`Hourly activity in ${o}`,children:n.map(e=>(0,b.jsx)("i",{style:{backgroundColor:`rgba(82, 224, 210, ${.07+e.count/r*.86})`},title:`${e.local} your time (${eG(e.utcHour)} UTC): ${e.count} clustered move${1===e.count?"":"s"}`},e.utcHour))}),(0,b.jsx)("div",{className:"tw-hour-labels",children:n.filter((e,t)=>t%6==0).map(e=>(0,b.jsx)("span",{children:e.local},e.utcHour))})]})}function eX({trader:e,timeZone:t}){var a;let s=e.activity_profile,r=e.hedge_profile,n=e.category_performance?.
4slice(0,4)||[],l=r?.top_books?.[0];return(0,b.jsxs)("div",{className:"tw-dossier","aria-label":`Behavioral profile for @${e.handle}`,children:[(0,b.jsxs)("div",{className:"tw-dossier-id",children:[(0,b.jsx)("span",{children:"OPERATOR PROFILE // PUBLIC TAPE"}),(0,b.jsxs)("b",{children:["@",e.handle]}),(0,b.jsxs)("p",{children:[s?.sample_actions||0," clustered decisions · ",(a=s?.coverage_hours||0)>=48?`${Math.max(2,Math.round(a/24))}d tape`:a>=1?`${Math.round(a)}h tape`:"new sample"," · ",s?.confidence||"low"," confidence"]}),(0,b.jsx)("small",{children:"Activity cadence, not a location claim."})]}),(0,b.jsx)(eK,{trader:e,timeZone:t}),(0,b.jsxs)("div",{className:"tw-dossier-block tw-hedge-block",children:[(0,b.jsxs)("div",{className:"tw-dossier-label",children:[(0,b.jsx)("span",{children:"VISIBLE HEDGE EXPOSURE"}),(0,b.jsx)("small",{children:"current positions"})]}),(0,b.jsxs)("div",{className:"tw-hedge-call",children:[(0,b.jsxs)("b",{children:[Math.round(r?.portfolio_hedged_pct||0),"%"]}),(0,b.jsx)("span",{children:"of visible book offset"})]}),(0,b.jsx)("div",{className:"tw-hedge-meter",children:(0,b.jsx)("i",{style:{width:`${Math.min(100,r?.portfolio_hedged_pct||0)}%`}})}),(0,b.jsxs)("div",{className:"tw-window-sub",children:[r?.hedged_markets||0," offset market",r?.hedged_markets===1?"":"s"," · ",eW(r?.offset_value||0,!0)," matched exposure"]}),l&&(0,b.jsxs)("div",{className:"tw-top-hedge",title:l.title,children:[(0,b.jsxs)("span",{children:[l.style," · net ",l.net_outcome||"mixed"," ",eW(l.net_value,!0)]}),(0,b.jsx)("b",{children:l.title})]})]}),(0,b.jsxs)("div",{className:"tw-dossier-block tw-category-block",children:[(0,b.jsxs)("div",{className:"tw-dossier-label",children:[(0,b.jsx)("span",{children:"CATEGORY TRACK RECORD"}),(0,b.jsx)("small",{children:"all-time Polymarket"})]}),n.length?(0,b.jsx)("div",{className:"tw-category-grid",children:n.map(e=>(0,b.jsxs)("div",{children:[(0,b.jsxs)("span",{children:[e.label,e.rank?` \xb7 #${e.rank}`:""]}),(0,b.jsx)("b",{className:e.pnl>=0?"up":"down",children:eU(e.pnl,!0)}),(0,b.jsxs)("small",{children:[eW(e.volume,!0)," volume"]})]},e.category))}):(0,b.jsx)("div",{className:"tw-window-empty",children:"No category leaderboard record returned."})]})]})}function eZ({row:e,onOpen:t}){let a=e.yes_value+e.no_value+e.hedged_value,s=a>0?e.yes_value/a*100:0,r=a>0?e.no_value/a*100:0,n=Math.max(0,100-s-r),l=null!=e.case_p_yes&&null!=e.market_yes?e.case_p_yes-e.market_yes:null;return(0,b.jsxs)("button",{className:"tw-consensus-card",onClick:t,disabled:!e.market_id,children:[(0,b.jsxs)("div",{className:"tw-consensus-top",children:[(0,b.jsx)("span",{className:`tw-consensus-call ${e.side}`,children:"split"===e.side?"SPLIT BOOK":"mixed"===e.side?"MULTI":`${e.side.toUpperCase()} LEAN`}),(0,b.jsxs)("span",{className:"tw-consensus-age",children:[e.n_directional," directional",e.n_hedged?` \xb7 ${e.n_hedged} paired`:""]})]}),(0,b.jsx)("div",{className:"tw-consensus-title",children:e.title||"Unindexed market"}),(e.yes_value>0||e.no_value>0||e.hedged_value>0)&&(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)("div",{className:"tw-capital-bar","aria-label":`YES ${eW(e.yes_value)}, NO ${eW(e.no_value)}, paired ${eW(e.hedged_value)}`,children:[(0,b.jsx)("span",{className:"yes",style:{width:`${s}%`}}),(0,b.jsx)("span",{className:"hedged",style:{width:`${n}%`}}),(0,b.jsx)("span",{className:"no",style:{width:`${r}%`}})]}),(0,b.jsxs)("div",{className:"tw-capital-labels",children:[(0,b.jsxs)("span",{className:"yes",children:["YES ",eW(e.yes_value,!0)]}),e.hedged_value>0&&(0,b.jsxs)("span",{children:["paired ",eW(e.hedged_value,!0)]}),(0,b.jsxs)("span",{className:"no",children:["NO ",eW(e.no_value,!0)]})]})]}),(0,b.jsxs)("div",{className:"tw-consensus-prices",children:[(0,b.jsxs)("span",{children:["market ",(0,b.jsx)("b",{children:eH(e.market_yes)})]}),(0,b.jsxs)("span",{children:["OP case ",(0,b.jsx)("b",{children:eH(e.case_p_yes)})]}),null!=l&&Math.abs(l)>=.05&&(0,b.jsxs)("span",{className:l>0?"up":"down",children:[l>0?"cheap":"rich"," ",Math.abs(Math.round(100*l)),"¢"]})]}),(0,b.jsx)("div",{className:"tw-stance-row",children:e.stances.slice(0,6).map(e=>(0,b.jsxs)("span",{className:`tw-stance ${e.side.toLowerCase()}`,children:["@",e.handle," · ",e.side.toUpperCase()]},e.handle))}),(e.recent_yes_usd>0||e.recent_no_usd>0)&&(0,b.jsxs)("div",{className:"tw-recent-flow",children:["recent flow · ",(0,b.jsxs)("b",{className:"yes",children:["YES ",eW(e.recent_yes_usd,!0)]})," / ",(0,b.jsxs)("b",{className:"no",children:["NO ",eW(e.recent_no_usd,!0)]})]})]})}function eQ({action:e,now:t,expanded:a,isNew:s,onToggle:r,onOpen:n}){let l=a?e.reasoning.items:e.reasoning.items.slice(0,3),i=e.reasoning.alignment,o=e.position?.total_pnl,c=e.category_performance,d="yes"===e.outcome.toLowerCase()?e.market.yes_price:"no"===e.outcome.toLowerCase()&&null!=e.market.yes_price?1-e.market.yes_price:e.position?.current_price;return(0,b.jsxs)("article",{className:`tw-action tw-tier-${e.importance_tier}${s?" tw-new":""}`,children:[(0,b.jsxs)("div",{className:"tw-action-score",children:[(0,b.jsx)("span",{children:e.importance_score}),(0,b.jsx)("small",{children:"signal"})]}),(0,b.jsxs)("div",{className:"tw-action-main",children:[(0,b.jsxs)("div",{className:"tw-action-meta",children:[(0,b.jsxs)("a",{href:e.trader_profile_url,target:"_blank",rel:"noreferrer",className:"tw-action-trader",children:[(0,b.jsx)(eV,{trader:{avatar:e.trader_avatar,handle:e.trader_handle,name:e.trader_name},small:!0}),(0,b.jsxs)("b",{children:["@",e.trader_handle]})]}),(0,b.jsx)("span",{className:`tw-order ${e.order_side.toLowerCase()}`,children:e.order_side}),(0,b.jsx)("span",{className:"tw-outcome",children:e.outcome||"combo"}),(0,b.jsxs)("span",{className:"tw-action-time",children:[eq(e.timestamp_ms,t)," ago"]}),s&&(0,b.jsx)("span",{className:"tw-new-chip",children:"NEW"})]}),(0,b.jsxs)("button",{className:"tw-market-title",onClick:n,disabled:!e.market.market_id&&!e.market.url,children:[e.market.title||e.title,(e.market.market_id||e.market.url)&&(0,b.jsx)("span",{children:"↗"})]}),(0,b.jsxs)("div",{className:"tw-execution-line",children:[(0,b.jsxs)("span",{className:"tw-exec-big",children:["BUY"===e.order_side?"deployed":"unwound"," ",(0,b.jsx)("b",{children:eW(e.usd)})]}
4),(0,b.jsxs)("span",{children:[e.shares.toLocaleString(void 0,{maximumFractionDigits:1})," sh @ ",(0,b.jsx)("b",{children:eH(e.avg_price)})]}),(0,b.jsxs)("span",{children:[e.fills," fill",1===e.fills?"":"s"]}),null!=d&&(0,b.jsxs)("span",{children:["now ",(0,b.jsx)("b",{children:eH(d)})]}),null!=o&&(0,b.jsxs)("span",{className:o>=0?"up":"down",children:["position ",eU(o,!0)]}),e.hedge_detail&&(0,b.jsxs)("span",{children:["visible offset ",(0,b.jsx)("b",{children:eW(e.hedge_detail.offset_value,!0)})," · net ",e.hedge_detail.net_outcome||"mixed"]})]}),(0,b.jsxs)("div",{className:"tw-tags",children:[e.market.category&&(0,b.jsx)("span",{className:"tw-market-category",children:e.market.category}),(0,b.jsx)("span",{className:`tw-intent ${e.intent}`,children:e.intent_label}),e.hedge_detail&&(0,b.jsxs)("span",{className:"tw-hedge-tag",children:[e.hedge_detail.style," hedge · ",Math.round(100*e.hedge_detail.balance_ratio),"%"]}),c&&(0,b.jsxs)("span",{className:`tw-category-record ${c.pnl>=0?"positive":"negative"}`,children:[c.label," all-time ",eU(c.pnl,!0),c.rank?` \xb7 #${c.rank}`:""]}),"unknown"!==i&&(0,b.jsx)("span",{className:`tw-alignment ${i}`,children:"contrarian"===i?"against OP":"aligned"===i?"with OP":"near OP fair"}),e.market.dispute_status&&(0,b.jsx)("span",{className:"tw-dispute",children:e.market.dispute_status}),null!=e.market.one_day_change&&Math.abs(e.market.one_day_change)>=.03&&(0,b.jsxs)("span",{className:e.market.one_day_change>=0?"up":"down",children:["24h ",e.market.one_day_change>=0?"+":"",Math.round(100*e.market.one_day_change),"¢"]})]})]}),(0,b.jsxs)("div",{className:"tw-read",children:[(0,b.jsxs)("div",{className:"tw-read-head",children:[(0,b.jsxs)("span",{children:[(0,b.jsx)("i",{})," OPENPOLY INFERENCE"]}),(0,b.jsxs)("span",{className:`tw-confidence ${e.reasoning.confidence}`,children:[e.reasoning.confidence," conf"]})]}),(0,b.jsx)("div",{className:"tw-read-summary",children:e.reasoning.summary}),(0,b.jsx)("div",{className:"tw-reason-list",children:l.map((e,t)=>(0,b.jsxs)("div",{className:`tw-reason ${e.kind} ${e.tone||""}`,children:[(0,b.jsx)("span",{children:e.label}),e.url?(0,b.jsxs)("a",{href:e.url,target:"_blank",rel:"noreferrer",children:[e.text," ↗"]}):(0,b.jsx)("p",{children:e.text})]},`${e.kind}-${t}`))}),e.reasoning.items.length>3&&(0,b.jsx)("button",{className:"tw-expand",onClick:r,children:a?"show less":`show ${e.reasoning.items.length-3} more evidence links`}),(0,b.jsx)("div",{className:"tw-inference-note",children:e.reasoning.disclaimer})]})]})}function e0(){let{data:e,loading:t,refreshing:a,mutating:s,error:r,mutationError:n,clearMutationError:l,refresh:i,addTrader:o,removeTrader:c}=function(){let[e,t]=(0,_.useState)(null),[a,s]=(0,_.useState)(!0),[r,n]=(0,_.useState)(!1),[l,i]=(0,_.useState)(null),[o,c]=(0,_.useState)(null),[d,u]=(0,_.useState)(null),h=(0,_.useRef)(!0),p=(0,_.useRef)(!1),m=(0,_.useRef)(1e4),x=(0,_.useCallback)(async(e=!1)=>{if(!p.current){p.current=!0,e&&n(!0);try{let a=await (0,er.authGetJson)(`/api/trader-watch?limit=120${e?"&refresh=1":""}`);if(!h.current)return;t(a.data),m.current=Math.max(5e3,Number(a.data?.poll_after_ms||1e4)),i(null)}catch(e){h.current&&i(e instanceof Error?e.message:"Trader Watch is unavailable")}finally{p.current=!1,h.current&&(s(!1),n(!1))}}},[]),g=(0,_.useCallback)(async e=>{c("add"),u(null);try{let a=await (0,er.authFetch)("/api/trader-watch/watchlist",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({trader:e})}),s=await a.json().catch(()=>({}));if(!a.ok||!s.ok||!s.data||!s.entry)throw Error(s.error||`Could not add trader (${a.status})`);return h.current&&(t(s.data),i(null)),{entry:s.entry,added:!!s.added}}catch(t){let e=t instanceof Error?t.message:"Could not add this trader";throw h.current&&u(e),t}finally{h.current&&c(null)}},[]),f=(0,_.useCallback)(async e=>{c(e),u(null);try{let a=await (0,er.authFetch)(`/api/trader-watch/watchlist/${encodeURIComponent(e)}`,{method:"DELETE"}),s=await a.json().catch(()=>({}));if(!a.ok||!s.ok||!s.data)throw Error(s.error||`Could not remove trader (${a.status})`);h.current&&(t(s.data),i(null))}catch(t){let e=t instanceof Error?t.message:"Could not remove this trader";throw h.current&&u(e),t}finally{h.current&&c(null)}},[]);return(0,_.useEffect)(()=>{h.current=!0,x();let e=0,t=()=>{let a="visible"===document.visibilityState?m.current:Math.max(2e4,m.current);e=window.setTimeout(async()=>{await x(),h.current&&t()},a)};return t(),()=>{h.current=!1,window.clearTimeout(e)}},[x]),{data:e,loading:a,refreshing:r,mutating:o,error:l,mutationError:d,clearMutationError:()=>u(null),refresh:()=>x(!0),addTrader:g,removeTrader:f}}(),{openTab:d}=(0,ez.useMarketTabs)(),[u,h]=(0,_.useState)(()=>Date.now()),[p,m]=(0,_.useState)("all"),[x,g]=(0,_.useState)(null),[f,v]=(0,_.useState)(new Set),[y,j]=(0,_.useState)(new Set),[w,N]=(0,_.useState)(!1),[k,S]=(0,_.useState)(!1),[$,C]=(0,_.useState)(""),[M,E]=(0,_.useState)(null),[A,T]=(0,_.useState)("UTC"),F=(0,_.useRef)(!1),P=(0,_.useRef)(0);(0,_.useEffect)(()=>{let e=window.setInterval(()=>h(Date.now()),1e3);try{N("1"===localStorage.getItem("op_trader_watch_notifications")&&"granted"===Notification.permission),P.current=Number(localStorage.getItem("op_trader_watch_seen_at")||0),T(Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC")}catch{P.current=0}return()=>window.clearInterval(e)},[]),(0,_.useEffect)(()=>
4{if(!e?.actions?.length)return;let t=Math.max(...e.actions.map(e=>e.timestamp_ms));if(!F.current){F.current=!0,P.current=Math.max(P.current,t);try{localStorage.setItem("op_trader_watch_seen_at",String(P.current))}catch{}return}let a=e.actions.filter(e=>e.timestamp_ms>P.current);if(a.length){j(new Set(a.map(e=>e.id))),window.setTimeout(()=>j(new Set),12e3),w&&"granted"===Notification.permission&&a.filter(e=>e.importance_score>=66).slice(0,3).forEach(e=>{new Notification(`@${e.trader_handle} ${e.order_side} ${e.outcome}`,{body:`${eW(e.usd)} @ ${eH(e.avg_price)} \xb7 ${e.market.title}`,icon:e.trader_avatar||void 0,tag:`openpoly-${e.id}`})}),P.current=Math.max(P.current,t);try{localStorage.setItem("op_trader_watch_seen_at",String(P.current))}catch{}}},[e?.checked_at_ms,e?.actions,w]);let R=async()=>{if(!("Notification"in window))return;if(w){N(!1),localStorage.setItem("op_trader_watch_notifications","0");return}let e="granted"===await Notification.requestPermission();N(e),localStorage.setItem("op_trader_watch_notifications",e?"1":"0")},O=async e=>{e.preventDefault();let t=$.trim();if(t&&!s){E(null),l();try{let e=await o(t);C(""),E(e.added?`@${e.entry.handle} joined the live tape.`:`@${e.entry.handle} is already being watched.`)}catch{E(null)}}},L=async e=>{if(!s){E(null),l();try{await c(e),g(t=>t===e?null:t),E(`@${e} removed from the custom watchlist.`)}catch{E(null)}}},I=(e,t="Market")=>{e&&d({kind:"radar",marketId:e,title:t.length>42?`${t.slice(0,40)}…`:t})},D=(0,_.useMemo)(()=>(e?.actions||[]).filter(e=>(!x||e.trader_handle===x)&&("high"===p?e.importance_score>=66:"contrarian"===p?"contrarian"===e.reasoning.alignment:"entries"===p?"opened"===e.lifecycle||"added"===e.lifecycle:"exits"===p?"trimmed"===e.lifecycle||"exited"===e.lifecycle:"locks"!==p||"resolution_lock"===e.intent)),[e?.actions,p,x]),z=(0,_.useMemo)(()=>(e?.consensus||[]).filter(e=>e.last_action_ms>0||e.n_directional>=2).slice(0,12),[e?.consensus]),B=(0,_.useMemo)(()=>e?.watchlist_entries||(e?.traders||[]).map(e=>({handle:e.handle,wallet:e.wallet,profile_url:e.profile_url,source:e.watchlist_source||"default",removable:!!e.removable})),[e?.traders,e?.watchlist_entries]),W=(0,_.useMemo)(()=>(e?.traders||[]).find(e=>e.handle===x)||null,[e?.traders,x]);return t&&!e?(0,b.jsxs)("div",{className:"tw-view tw-loading",children:[(0,b.jsx)("span",{className:"tw-loader"}),(0,b.jsx)("b",{children:"Warming the smart-money tape…"}),(0,b.jsx)("span",{children:"Resolving profiles, positions, cases and live order flow."})]}):(0,b.jsxs)("div",{className:"tw-view",children:[(0,b.jsxs)("header",{className:"tw-header",children:[(0,b.jsxs)("div",{className:"tw-title-lockup",children:[(0,b.jsxs)("span",{className:"tw-sigil",children:[(0,b.jsx)("i",{}),(0,b.jsx)("i",{}),(0,b.jsx)("i",{})]}),(0,b.jsxs)("div",{children:[(0,b.jsx)("div",{className:"tw-eyebrow",children:"PRIVATE ORDER-FLOW DESK // 01"}),(0,b.jsx)("h1",{children:"Trader Watch"})]}),(0,b.jsxs)("span",{className:"tw-live-mark",children:[(0,b.jsx)("i",{})," LIVE"]})]}),(0,b.jsxs)("div",{className:"tw-header-copy",children:["Watch what proven Polymarket operators do, then cross-examine every move against OpenPoly's case file, news clock and market tape.",(0,b.jsx)("span",{children:" No conversation required."})]}),(0,b.jsxs)("div",{className:"tw-controls",children:[(0,b.jsx)("button",{className:k?"active":"",onClick:()=>S(e=>!e),children:k?"× close intake":"+ watch trader"}),(0,b.jsx)("button",{className:w?"active":"",onClick:R,children:w?"◉ alerts on":"○ enable alerts"}),(0,b.jsx)("button",{onClick:i,disabled:a,children:a?"syncing…":"↻ force sync"}),(0,b.jsxs)("span",{className:"tw-sync",children:["last join ",eq(e?.checked_at_ms||0,u)," ago"]})]})]}),k&&(0,b.jsxs)("section",{className:"tw-watchlist-console","aria-label":"Manage Trader Watch profiles",children:[(0,b.jsxs)("div",{className:"tw-intake-copy",children:[(0,b.jsx)("span",{children:"WATCHLIST INTAKE // EXACT PROFILE MATCH"}),(0,b.jsx)("b",{children:"Put another operator under surveillance."}),(0,b.jsx)("small",{children:"Paste a Polymarket profile URL, @handle, or proxy wallet. OpenPoly verifies the profile before it joins the shared live tape."})]}),(0,b.jsxs)("form",{className:"tw-intake-form",onSubmit:O,children:[(0,b.jsx)("label",{htmlFor:"tw-trader-input",children:"POLYMARKET IDENTITY"}),(0,b.jsxs)("div",{children:[(0,b.jsx)("input",{id:"tw-trader-input",value:$,onChange:e=>{C(e.target.value),E(null),l()},placeholder:"polymarket.com/@trader",autoComplete:"off",spellCheck:!1,disabled:!!s}),(0,b.jsx)("button",{type:"submit",disabled:!$.trim()||!!s,children:"add"===s?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)("i",{})," resolving + joining"]}
4):"add to watchlist →"})]}),(0,b.jsx)("p",{className:n?"error":M?"success":"",children:n||M||"New profiles inherit the same fill clustering, position tracking and OpenPoly reasoning."})]}),(0,b.jsxs)("div",{className:"tw-watchlist-ledger",children:[(0,b.jsxs)("div",{className:"tw-ledger-head",children:[(0,b.jsx)("span",{children:"ACTIVE ROSTER"}),(0,b.jsxs)("b",{children:[B.length," / ",e?.watchlist_limit||24]})]}),(0,b.jsx)("div",{className:"tw-ledger-chips",children:B.map(e=>(0,b.jsxs)("span",{className:e.removable?"custom":"default",children:[(0,b.jsxs)("a",{href:e.profile_url,target:"_blank",rel:"noreferrer",children:["@",e.handle]}),(0,b.jsx)("small",{children:e.removable?"custom":"desk"}),e.removable&&(0,b.jsx)("button",{type:"button",onClick:()=>L(e.handle),disabled:!!s,"aria-label":`Remove @${e.handle} from Trader Watch`,title:"Remove custom profile",children:s===e.handle?"…":"×"})]},e.wallet))})]})]}),(0,b.jsxs)("section",{className:"tw-kpis",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{children:"WATCHING"}),(0,b.jsx)("b",{children:e?.stats.watching||0}),(0,b.jsxs)("small",{children:[e?.stats.active_24h||0," active today"]})]}),(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{children:"24H OBSERVED FLOW"}),(0,b.jsx)("b",{children:eW(e?.stats.flow_24h||0,!0)}),(0,b.jsx)("small",{children:"public matched fills"})]}),(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{children:"HIGH-SIGNAL MOVES"}),(0,b.jsx)("b",{children:e?.stats.high_signal||0}),(0,b.jsx)("small",{children:"size × skill × context"})]}),(0,b.jsxs)("div",{className:(e?.stats.contrarian||0)>0?"hot":"",children:[(0,b.jsx)("span",{children:"AGAINST OUR CASE"}),(0,b.jsx)("b",{children:e?.stats.contrarian||0}),(0,b.jsx)("small",{children:"worth investigating"})]}),(0,b.jsxs)("div",{className:(e?.stats.conflicted_markets||0)>0?"warn":"",children:[(0,b.jsx)("span",{children:"SMART-MONEY SPLITS"}),(0,b.jsx)("b",{children:e?.stats.conflicted_markets||0}),(0,b.jsx)("small",{children:"disagreement is alpha"})]})]}),(0,b.jsxs)("section",{className:`tw-roster-zone${W?" profiled":""}`,"aria-label":"Watched traders",children:[(0,b.jsx)("div",{className:"tw-roster",children:(e?.traders||[]).map(e=>(0,b.jsx)(eY,{trader:e,selected:x===e.handle,now:u,onSelect:()=>g(t=>t===e.handle?null:e.handle)},e.handle))}),W&&(0,b.jsx)(eX,{trader:W,timeZone:A})]}),(0,b.jsxs)("div",{className:"tw-toolbar",children:[(0,b.jsxs)("div",{className:"tw-filter-row",children:[eB.map(e=>(0,b.jsx)("button",{className:p===e.key?"active":"",onClick:()=>m(e.key),children:e.label},e.key)),x&&(0,b.jsxs)("button",{className:"tw-clear-trader",onClick:()=>g(null),children:["@",x," ×"]})]}),(0,b.jsxs)("div",{className:"tw-method",children:[(0,b.jsx)("span",{children:"INFERENCE, NOT MIND-READING"}),(0,b.jsx)("span",{children:"·"}),(0,b.jsx)("span",{children:"public fills + current hedges + category record + time-valid OpenPoly evidence"})]})]}),r&&(0,b.jsxs)("div",{className:"tw-error",children:["⚠ Live refresh failed. Showing the last persisted tape. ",(0,b.jsx)("span",{children:r})]}),(e?.degraded||[]).length>0&&(0,b.jsxs)("div",{className:"tw-degraded",children:["degraded source cache: ",e.degraded.join(", ")," · stale-good data retained"]}),(0,b.jsxs)("div",{className:"tw-workspace",children:[(0,b.jsxs)("aside",{className:"tw-consensus-panel",children:[(0,b.jsxs)("div",{className:"tw-panel-head",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{children:"MARKET MAP"}),(0,b.jsx)("b",{children:"Where the watchlist converges"})]}),(0,b.jsxs)("small",{children:[z.length," live books"]})]}),(0,b.jsx)("div",{className:"tw-consensus-scroll",children:z.length?z.map(e=>(0,b.jsx)(eZ,{row:e,onOpen:()=>I(e.market_id,e.title)},e.condition_id)):(0,b.jsx)("div",{className:"tw-empty",children:"No overlapping live books yet. The map fills as wat
4ched traders establish positions."})})]}),(0,b.jsxs)("main",{className:"tw-tape-panel",children:[(0,b.jsxs)("div",{className:"tw-panel-head",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{children:"LIVE TAPE"}),(0,b.jsx)("b",{children:x?`@${x}`:"All watched operators"})]}),(0,b.jsxs)("small",{children:[D.length," move",1===D.length?"":"s"," in view"]})]}),(0,b.jsx)("div",{className:"tw-tape-scroll",children:D.length?D.map(e=>(0,b.jsx)(eQ,{action:e,now:u,expanded:f.has(e.id),isNew:y.has(e.id),onToggle:()=>v(t=>{let a=new Set(t);return a.has(e.id)?a.delete(e.id):a.add(e.id),a}),onOpen:()=>{e.market.market_id?I(e.market.market_id,e.market.title):e.market.url&&window.open(e.market.url,"_blank","noopener,noreferrer")}},e.id)):(0,b.jsxs)("div",{className:"tw-empty",children:[(0,b.jsx)("b",{children:"No tape matches this lens."}),(0,b.jsx)("span",{children:"Clear the filter or wait for the next public fill."})]})})]})]})]})}var e1=e.i(71675);let e2=(0,w.default)("arrow-up-right",[["path",{d:"M7 7h10v10",key:"1tivn9"}],["path",{d:"M7 17 17 7",key:"1vkiza"}]]),e5=(0,w.default)("brain-circuit",[["path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z",key:"l5xja"}],["path",{d:"M9 13a4.5 4.5 0 0 0 3-4",key:"10igwf"}],["path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5",key:"105sqy"}],["path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396",key:"ql3yin"}],["path",{d:"M6 18a4 4 0 0 1-1.967-.516",key:"2e4loj"}],["path",{d:"M12 13h4",key:"1ku699"}],["path",{d:"M12 18h6a2 2 0 0 1 2 2v1",key:"105ag5"}],["path",{d:"M12 8h8",key:"1lhi5i"}],["path",{d:"M16 8V5a2 2 0 0 1 2-2",key:"u6izg6"}],["circle",{cx:"16",cy:"13",r:".5",key:"ry7gng"}],["circle",{cx:"18",cy:"3",r:".5",key:"1aiba7"}],["circle",{cx:"20",cy:"21",r:".5",key:"yhc1fs"}],["circle",{cx:"20",cy:"8",r:".5",key:"1e43v0"}]]);var e4=e.i(216),e3=e.i(23207);let e6=(0,w.default)("circle-dollar-sign",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8",key:"1h4pet"}],["path",{d:"M12 18V6",key:"zqpxq5"}]]);var e8=e.i(31762),e9=e.i(74114);let e7=(0,w.default)("flask-conical",[["path",{d:"M14 2v6a2 2 0 0 0 .245.96l5.51 10.08A2 2 0 0 1 18 22H6a2 2 0 0 1-1.755-2.96l5.51-10.08A2 2 0 0 0 10 8V2",key:"18mbvz"}],["path",{d:"M6.453 15h11.094",key:"3shlmq"}],["path",{d:"M8.5 2h7",key:"csnxdl"}]]),te=(0,w.default)("git-branch",[["path",{d:"M15 6a9 9 0 0 0-9 9V3",key:"1cii5b"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}]]),tt=(0,w.default)("loader-circle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]),ta=(0,w.default)("notebook-pen",[["path",{d:"M13.4 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-7.4",key:"re6nr2"}],["path",{d:"M2 6h4",key:"aawbzj"}],["path",{d:"M2 10h4",key:"l0bgd4"}],["path",{d:"M2 14h4",key:"1gsvsf"}],["path",{d:"M2 18h4",key:"1bu2t1"}],["path",{d:"M21.378 5.626a1 1 0 1 0-3.004-3.004l-5.01 5.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"pqwjuv"}]]);var ts=e.i(42414);let tr=(0,w.default)("rotate-ccw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]),tn=(0,w.default)("shield-check",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);var tl=e.i(15937),ti=e.i(10459),to=e.i(78044);let tc={lane:"all",timing:"all",phase:"all",hedge:"all",status:"completed",league:"all",price_min:0,price_max:1,min_deployed:0,lookback_days:0,unit:"match"},td=["@rollobravado","@rn1","@us391"],tu="openpoly.reverse-lab.recent.v1";function th(e,t=!1){let a=Number(e);if(!Number.isFinite(a))return"—";let s=a>0?"+$":a<0?"-$":"$";return t&&Math.abs(a)>=1e6?`${s}${(Math.abs(a)/1e6).toFixed(2)}m`:t&&Math.abs(a)>=1e3?`${s}${(Math.abs(a)/1e3).toFixed(1)}k`:`${s}${Math.abs(a).toLocaleString(void 0,{minimumFractionDigits:0,maximumFractionDigits:2})}`}function tp(e,t=1){let a=Number(e);return Number.isFinite(a)?`${a>0?"+":""}${(100*a).toFixed(t)}
4%`:"—"}function tm(e){let t=Number(e);return Number.isFinite(t)?`${(100*t).toFixed(1)}\xa2`:"—"}function tx(e){return e?`${e.slice(0,6)}…${e.slice(-4)}`:"—"}function tg(e){return e?new Date(e).toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}):"—"}function tf(e){let t=Number(e);return!Number.isFinite(t)||1e-6>Math.abs(t)?"flat":t>0?"up":"down"}function tb(e){return"settled"===e.status||"exited"===e.status}function t_(e,t){let a="leg"===t?e.map(e=>({key:e.id,pnl:e.cashflow_pnl_usd,feeScenario:e.fee_scenario_pnl_usd,deployed:e.deployed_usd,fees:e.estimated_fee_usd,timestamp:e.first_entry_ts_ms,done:tb(e),hedge:e.hedged_match})):Array.from(e.reduce((e,t)=>{let a=e.get(t.event_slug)||{key:t.event_slug,pnl:0,feeScenario:0,deployed:0,fees:0,timestamp:t.first_entry_ts_ms,done:!0,hedge:!1};return a.pnl+=t.cashflow_pnl_usd,a.feeScenario+=t.fee_scenario_pnl_usd,a.deployed+=t.deployed_usd,a.fees+=t.estimated_fee_usd,a.timestamp=Math.min(a.timestamp||t.first_entry_ts_ms,t.first_entry_ts_ms),a.done=a.done&&tb(t),a.hedge=a.hedge||t.hedged_match,e.set(t.event_slug,a),e},new Map).values()),s=a.filter(e=>e.done),r=a.reduce((e,t)=>e+t.deployed,0),n=s.reduce((e,t)=>e+t.deployed,0),l=a.reduce((e,t)=>e+t.pnl,0),i=s.reduce((e,t)=>e+t.pnl,0),o=a.reduce((e,t)=>e+t.feeScenario,0),c=a.reduce((e,t)=>e+t.fees,0),d=s.filter(e=>e.pnl>0).length,u=s.filter(e=>e.pnl<0).length,h=s.reduce((e,t)=>e+Math.max(0,t.pnl),0),p=Math.abs(s.reduce((e,t)=>e+Math.min(0,t.pnl),0)),m=s.map(e=>e.pnl).sort((e,t)=>e-t),x=m.length?m.length%2?m[Math.floor(m.length/2)]:(m[m.length/2-1]+m[m.length/2])/2:null,g=0,f=0,b=0;return[...s].sort((e,t)=>e.timestamp-t.timestamp).forEach(e=>{g+=e.pnl,b=Math.max(b,(f=Math.max(f,g))-g)}),{unit:t,n:a.length,completed:s.length,open:a.length-s.length,wins:d,losses:u,win_rate:s.length?d/s.length:null,deployed_usd:r,completed_deployed_usd:n,cashflow_pnl_usd:l,gross_pnl_usd:l,net_pnl_usd:o,fee_scenario_pnl_usd:o,estimated_fee_usd:c,completed_pnl_usd:i,roi:r?l/r:null,completed_roi:n?i/n:null,profit_factor:p?h/p:h?999:null,median_pnl_usd:x,max_drawdown_usd:b,avg_deployed_usd:a.length?r/a.length:null,hedged_rate:a.length?a.filter(e=>e.hedge).length/a.length:null}}function tv(e,t,a){let s=new Map;return e.forEach(e=>{let a=String(e[t]??"unknown");s.set(a,[...s.get(a)||[],e])}),Array.from(s,([e,t])=>({key:e,...t_(t,a)})).sort((e,t)=>t.deployed_usd-e.deployed_usd)}function ty({rows:e}){let t=(0,_.useMemo)(()=>{let t=new Map;e.filter(tb).forEach(e=>{let a=t.get(e.event_slug)||{timestamp:e.first_entry_ts_ms,pnl:0};a.timestamp=Math.min(a.timestamp||e.first_entry_ts_ms,e.first_entry_ts_ms),a.pnl+=e.cashflow_pnl_usd,t.set(e.event_slug,a)});let a=0;return Array.from(t.values()).sort((e,t)=>e.timestamp-t.timestamp).map(e=>(a+=e.pnl,{...e,cumulative:a}))},[e]);if(t.length<2)return(0,b.jsx)("div",{className:"rl-chart-empty",children:"Need at least two completed matches for a trace."});let a=t.map(e=>e.cumulative),s=Math.min(0,...a),r=Math.max(1,Math.max(0,...a)-s),n=t.map((e,a)=>{let n=8+a/(t.length-1)*584,l=92-(e.cumulative-s)/r*82;return`${n.toFixed(1)},${l.toFixed(1)}`}).join(" "),l=92-(0-s)/r*82,i=t.at(-1)?.cumulative&&t.at(-1).cumulative>=0?"up":"down";return(0,b.jsxs)("div",{className:`rl-equity ${i}`,children:[(0,b.jsxs)("svg",{viewBox:"0 0 600 100",preserveAspectRatio:"none","aria-label":"Filtered cumulative PnL",children:[(0,b.jsx)("line",{x1:"0",y1:l,x2:"600",y2:l,className:"rl-equity-zero"}),(0,b.jsx)("polyline",{points:n,fill:"none",vectorEffect:"non-scaling-stroke"})]}),(0,b.jsxs)("div",{className:"rl-equity-meta",children:[(0,b.jsxs)("span",{children:[t.length," completed matches"]}),(0,b.jsx)("b",{children:th(t.at(-1)?.cumulative||0)})]})]})}function tj({title:e,rows:t}){return(0,b.jsxs)("section",{className:"rl-segment-card",children:[(0,b.jsxs)("header",{children:[(0,b.jsx)("span",{children:e}),(0,b.jsx)("small",{children:"match grouped"})]}),(0,b.jsxs)("div",{className:"rl-segment-list",children:[t.slice(0,9).map(e=>(0,b.jsxs)("div",{className:"rl-segment-row",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("b",{children:e.key}),(0,b.jsxs)("small",{children:[e.completed," closed"]})]}),(0,b.jsxs)("span",{children:[tp(e.win_rate,0)," WR"]}),(0,b.jsx)("span",{className:tf(e.completed_roi),children:tp(e.completed_roi)}),(0,b.jsx)("strong",{className:tf(e.completed_pnl_usd),children:th(e.completed_pnl_usd,!0)})]},e.key)),!t.length&&(0,b.jsx)("div",{className:"rl-segment-empty",children:"No observations in this slice."})]})]})}function tw({label:e,value:t,note:a,tone:s}){return(0,b.jsxs)("div",{className:`rl-metric-block ${s||""}`,children:[(0,b.jsx)("span",{children:e}),(0,b.jsx)("b",{children:t}),(0,b.jsx)("small",{children:a})]})}function tN({result:e}){let t=e.verdict.replaceAll("_"," ");return(0,b.jsxs)("section",{className:"rl-test-result",children:[(0,b.jsxs)("div",{className:"rl-test-verdict",children:[(0,b.jsx)("span",{className:e.verdict,children:t}),(0,b.jsxs)("div",{children:[(0,b.jsx)("small",{children:"OBSERVABLE CLAIM"}),(0,b.jsx)("b",{children:e.statement})]})]}),(0,b.jsxs)("div",{className:"rl-compare-grid",children:[(0,b.jsx)(tw,{label:"Selected Slice",value:tp(e.selected.completed_roi),note:`${e.selected.completed} closed \xb7 ${tp(e.selected.win_rate,0)}
4 WR`,tone:tf(e.selected.completed_roi)}),(0,b.jsx)(tw,{label:"Remaining Tape",value:tp(e.control.completed_roi),note:`${e.control.completed} closed \xb7 ${tp(e.control.win_rate,0)} WR`,tone:tf(e.control.completed_roi)}),(0,b.jsx)(tw,{label:"Observed ROI Lift",value:tp(e.lift.roi),note:"descriptive, not causal",tone:tf(e.lift.roi)})]}),(0,b.jsx)("div",{className:"rl-folds",children:e.folds.map(e=>(0,b.jsxs)("div",{className:tf(e.completed_roi),children:[(0,b.jsxs)("span",{children:["TIME ",e.fold]}),(0,b.jsx)("b",{children:tp(e.completed_roi)}),(0,b.jsxs)("small",{children:[e.completed," closed"]})]},e.fold))}),(0,b.jsxs)("div",{className:"rl-result-warning",children:[(0,b.jsx)(e1.AlertTriangle,{size:13}),e.warnings[0]]})]})}function tk({audit:e,filters:t,setFilters:a,preview:s}){let r=(0,_.useMemo)(()=>Array.from(new Set(e.ledger.map(e=>e.league))).sort(),[e]),n=(0,_.useMemo)(()=>Array.from(new Set(e.ledger.map(e=>e.entry_phase))).sort(),[e]),l=(e,s)=>a({...t,[e]:s});return(0,b.jsxs)("aside",{className:"rl-filter-desk",children:[(0,b.jsxs)("div",{className:"rl-rail-title",children:[(0,b.jsx)(tl.SlidersHorizontal,{size:14}),(0,b.jsx)("span",{children:"Protocol Slice"})]}),(0,b.jsx)("p",{children:"Change one observable at a time. The lab groups outcomes by match and preserves the untouched complement as a weak comparison."}),(0,b.jsxs)("label",{children:[(0,b.jsx)("span",{children:"PROP LANE"}),(0,b.jsxs)("select",{value:t.lane,onChange:e=>l("lane",e.target.value),children:[(0,b.jsx)("option",{value:"all",children:"All soccer props"}),e.lanes.map(e=>(0,b.jsx)("option",{value:e.key,children:e.label},e.key))]})]}),(0,b.jsxs)("label",{children:[(0,b.jsx)("span",{children:"LEAGUE / NICHE"}),(0,b.jsxs)("select",{value:t.league,onChange:e=>l("league",e.target.value),children:[(0,b.jsx)("option",{value:"all",children:"Every mapped league"}),r.map(e=>(0,b.jsx)("option",{value:e,children:e},e))]})]}),(0,b.jsxs)("div",{className:"rl-filter-group",children:[(0,b.jsx)("span",{children:"ENTRY CLOCK"}),(0,b.jsx)("div",{className:"rl-choice-row three",children:["all","prematch","live"].map(e=>(0,b.jsx)("button",{className:t.timing===e?"active":"",onClick:()=>l("timing",e),children:e},e))})]}),(0,b.jsxs)("label",{children:[(0,b.jsx)("span",{children:"ENTRY PHASE"}),(0,b.jsxs)("select",{value:t.phase,onChange:e=>l("phase",e.target.value),children:[(0,b.jsx)("option",{value:"all",children:"Any phase"}),n.map(e=>(0,b.jsx)("option",{value:e,children:e},e))]})]}),(0,b.jsxs)("div",{className:"rl-filter-group",children:[(0,b.jsx)("span",{children:"AVG ENTRY RANGE"}),(0,b.jsxs)("div",{className:"rl-price-range",children:[(0,b.jsxs)("label",{children:[(0,b.jsx)("input",{type:"number",min:"0",max:"100",value:Math.round(100*t.price_min),onChange:e=>l("price_min",Math.max(0,Math.min(1,Number(e.target.value)/100)))}),(0,b.jsx)("i",{children:"¢ min"})]}),(0,b.jsx)("b",{children:"→"}),(0,b.jsxs)("label",{children:[(0,b.jsx)("input",{type:"number",min:"0",max:"100",value:Math.round(100*t.price_max),onChange:e=>l("price_max",Math.max(0,Math.min(1,Number(e.target.value)/100)))}),(0,b.jsx)("i",{children:"¢ max"})]})]})]}),(0,b.jsxs)("div",{className:"rl-filter-group",children:[(0,b.jsx)("span",{children:"BOOK SHAPE"}),(0,b.jsx)("div",{className:"rl-choice-row three",children:["all","hedged","unhedged"].map(e=>(0,b.jsx)("button",{className:t.hedge===e?"active":"",onClick:()=>l("hedge",e),children:e},e))})]}),(0,b.jsxs)("div",{className:"rl-filter-split",children:[(0,b.jsxs)("label",{children:[(0,b.jsx)("span",{children:"STATE"}),(0,b.jsxs)("select",{value:t.status,onChange:e=>l("status",e.target.value),children:[(0,b.jsx)("option",{value:"completed",children:"Completed only"}),(0,b.jsx)("option",{value:"all",children:"Completed + mark"}),(0,b.jsx)("option",{value:"open",children:"Open mark only"})]})]}),(0,b.jsxs)("label",{children:[(0,b.jsx)("span",{children:"LOOKBACK"}),(0,b.jsxs)("select",{value:t.lookback_days,onChange:e=>l("lookback_days",Number(e.target.value)),children:[(0,b.jsx)("option",{value:0,children:"All history"}),(0,b.jsx)("option",{value:14,children:"14 days"}),(0,b.jsx)("option",{value:30,children:"30 days"}),(0,b.jsx)("option",{value:60,children:"60 days"}),(0,b.jsx)("option",{value:90,children:"90 days"})]})]})]}),(0,b.jsxs)("label",{children:[(0,b.jsx)("span",{children:"MINIMUM DEPLOYE
4D / LEG"}),(0,b.jsx)("input",{className:"rl-rail-input",type:"number",min:"0",step:"25",value:t.min_deployed,onChange:e=>l("min_deployed",Math.max(0,Number(e.target.value)))})]}),(0,b.jsxs)("div",{className:"rl-filter-group",children:[(0,b.jsx)("span",{children:"UNIT OF ANALYSIS"}),(0,b.jsx)("div",{className:"rl-choice-row two",children:["match","leg"].map(e=>(0,b.jsx)("button",{className:t.unit===e?"active":"",onClick:()=>l("unit",e),children:e},e))})]}),(0,b.jsxs)("button",{className:"rl-reset",onClick:()=>a({...tc}),children:[(0,b.jsx)(tr,{size:12}),"Reset protocol"]}),(0,b.jsxs)("div",{className:"rl-live-sample",children:[(0,b.jsx)("span",{children:"CURRENT SLICE"}),(0,b.jsxs)("b",{children:[s.completed,(0,b.jsxs)("small",{children:[" closed ",s.unit,"s"]})]}),(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{className:tf(s.completed_pnl_usd),children:th(s.completed_pnl_usd,!0)}),(0,b.jsxs)("span",{children:[tp(s.completed_roi)," ROI"]})]})]})]})}function tS(){let e=function(){let[e,t]=(0,_.useState)(null),[a,s]=(0,_.useState)(null),[r,n]=(0,_.useState)(null),[l,i]=(0,_.useState)(!1),[o,c]=(0,_.useState)(!1),[d,u]=(0,_.useState)(null),[h,p]=(0,_.useState)(null),[m,x]=(0,_.useState)(!1),[g,f]=(0,_.useState)(null),[b,v]=(0,_.useState)(!1),y=(0,_.useRef)(null),j=(0,_.useCallback)(async(e,a=!1)=>{let r=e.trim();if(!r)return;y.current?.abort();let l=new AbortController;y.current=l,i(!0),u(null),n({stage:"connect",message:"Opening governed audit stream…",progress:1}),t(null),s(null),c(!1),p(null),f(null);try{let e=await (0,er.authFetch)(`/api/trader/reverse-lab/audit?trader=${encodeURIComponent(r)}&refresh=${+!!a}`,{signal:l.signal,cache:"no-store"});if(!e.ok)throw Error(await e.text());if(!e.body)throw Error("Reverse Lab stream is unavailable");let i=e.body.getReader(),o=new TextDecoder,d="",h=!1,p=!1,m=null,x=!1,g=e=>{let a;if(!e.startsWith("data: "))return;let r=e.slice(6).trim();if(r){try{a=JSON.parse(r)}catch{return}"stage"===a.type?n({stage:String(a.stage||"working"),message:String(a.message||"Working…"),progress:Number(a.progress||0)}):"profile"===a.type?t(a.profile||null):"audit"===a.type?(p=!0,s(a.audit||null),c(!!a.cached)):"audit_ready"===a.type?(m=String(a.wallet||""),x=!!a.cached):"error"===a.type?u(String(a.error||"Reverse Lab audit failed")):"done"===a.type&&(h=!0)}};for(;!h;){let{done:e,value:t}=await i.read();if(e)break;let a=(d+=o.decode(t,{stream:!0})).split("\n");d=a.pop()||"",a.forEach(g)}if(d.trim()&&d.split("\n").forEach(g),m&&!p){n({stage:"deliver",message:"Downloading audit…",progress:100});let e=null;for(let t=0;t<3&&!e;t+=1)try{e=await (0,er.authGetJson)(`/api/trader/reverse-lab/result?wallet=${encodeURIComponent(m)}`)}catch{if(2===t)throw Error("The audit finished but could not be downloaded — run again to fetch it from cache.");await new Promise(e=>setTimeout(e,1200*(t+1)))}p=!0,s(e?.audit||null),c(x)}if(!h&&!p)throw Error("The audit stream was interrupted — run again to reattach to the audit in progress.")}catch(e){e?.name!=="AbortError"&&u(e?.message||"Reverse Lab audit failed")}finally{i(!1),y.current=null}},[]),w=(0,_.useCallback)(async(e,t,a)=>{x(!0),u(null);try{let s=await (0,er.authPostJson)("/api/trader/reverse-lab/hypothesis",{wallet:e,filters:t,statement:a});return p(s.data),s.data}catch(e){return u(e?.message||"Hypothesis test failed"),null}finally{x(!1)}},[]);return{profile:e,audit:a,stage:r,loading:l,cached:o,error:d,hypothesis:h,testing:m,aiRead:g,askingAi:b,runAudit:j,testHypothesis:w,askAi:(0,_.useCallback)(async(e,t,a,s)=>{v(!0),u(null);try{let r=await (0,er.authPostJson)("/api/trader/reverse-lab/ai",{wallet:e,filters:t,statement:a,question:s});return f(r.data),r.data?.hypothesis_test&&p(r.data.hypothesis_test),r.data}catch(e){return u(e?.message||"Research copilot failed"),null}finally{v(!1)}},[]),clear:(0,_.useCallback)(()=>{y.current?.abort(),t(null),s(null),n(null),i(!1),c(!1),u(null),p(null),f(null)},[])}}(),[t,a]=(0,_.useState)(""),[s,r]=(0,_.useState)("edge"),[n,l]=(0,_.useState)({...tc}),[i,o]=(0,_.useState)("This observable slice has a repeatable trader edge."),[c,d]=(0,_.useState)("What is the strongest honest explanation for this behavior, and what should I test next?"),[u,h]=(0,_.useState)(""),[p,m]=(0,_.useState)([]),[x,g]=(0,_.useState)([]);(0,_.useEffect)(()=>{try{m(JSON.parse(localStorage.getItem(tu)||"[]").slice(0,6))}catch{m([])}},[]),(0,_.useEffect)(()=>
4{if(!e.audit?.profile.wallet)return;let t=`openpoly.reverse-lab.notebook.${e.audit.profile.wallet}`;try{g(JSON.parse(localStorage.getItem(t)||"[]"))}catch{g([])}},[e.audit?.profile.wallet]),(0,_.useEffect)(()=>{if(!e.audit)return;let t=e.audit.profile.handle?`@${e.audit.profile.handle}`:e.audit.profile.wallet;a(t),l({...tc});let s=e.audit.lanes.find(e=>e.match.completed>=5);s&&o(`${s.label} entries outperform the trader's remaining soccer tape.`),m(e=>{let a=[t,...e.filter(e=>e!==t)].slice(0,6);return localStorage.setItem(tu,JSON.stringify(a)),a})},[e.audit?.generated_at_ms]);let f=(0,_.useMemo)(()=>{var t;let a,s;return t=e.audit?.ledger||[],a=t.reduce((e,t)=>Math.max(e,t.first_entry_ts_ms||0),0),s=n.lookback_days>0?a-864e5*n.lookback_days:0,t.filter(e=>("all"===n.lane||e.lane===n.lane)&&("all"===n.timing||e.entry_timing===n.timing)&&("all"===n.phase||e.entry_phase===n.phase)&&("hedged"!==n.hedge||!!e.hedged_match)&&("unhedged"!==n.hedge||!e.hedged_match)&&("completed"!==n.status||!!tb(e))&&("open"!==n.status||"open"===e.status)&&("all"===n.league||e.league===n.league)&&!(e.avg_entry<n.price_min)&&!(e.avg_entry>n.price_max)&&!(e.deployed_usd<n.min_deployed)&&(!s||!(e.first_entry_ts_ms<s))&&!0)},[e.audit,n]),v=(0,_.useMemo)(()=>t_(f,n.unit),[f,n.unit]),y=(0,_.useMemo)(()=>tv(f,"entry_phase","match"),[f]),w=(0,_.useMemo)(()=>tv(f,"price_band","match"),[f]),N=(0,_.useMemo)(()=>tv(f,"league","match"),[f]),S=(0,_.useMemo)(()=>{let e=u.trim().toLowerCase();return f.filter(t=>!e||[t.event_title,t.market_title,t.league,t.outcome,t.lane_label].some(t=>t.toLowerCase().includes(e))).slice(0,300)},[f,u]);return(0,b.jsxs)("div",{className:"rl-view",children:[(0,b.jsxs)("header",{className:"rl-header",children:[(0,b.jsxs)("div",{className:"rl-brand",children:[(0,b.jsxs)("div",{className:"rl-mark",children:[(0,b.jsx)(te,{size:18}),(0,b.jsx)("i",{}),(0,b.jsx)("i",{})]}),(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{children:"SOCCER INTELLIGENCE / BEHAVIORAL FORENSICS"}),(0,b.jsx)("h1",{children:"Reverse Lab"})]}),(0,b.jsx)("em",{children:"RESEARCH ONLY"})]}),(0,b.jsxs)("form",{className:"rl-search",onSubmit:a=>{a.preventDefault(),e.runAudit(t)},children:[(0,b.jsx)(j.Search,{size:15}),(0,b.jsx)("input",{value:t,onChange:e=>a(e.target.value),placeholder:"Paste polymarket.com/@trader, @handle, or 0x wallet…"}),t&&(0,b.jsx)("button",{type:"button",className:"rl-search-clear",onClick:()=>a(""),children:(0,b.jsx)(k,{size:12})}),(0,b.jsxs)("button",{type:"submit",className:"rl-run",disabled:e.loading||!t.trim(),children:[e.loading?(0,b.jsx)(tt,{size:14,className:"spin"}):(0,b.jsx)(e7,{size:14}),e.loading?"Auditing":"Audit Trader"]})]}),(0,b.jsx)("div",{className:"rl-recents",children:(p.length?p:td).slice(0,4).map(t=>(0,b.jsx)("button",{onClick:()=>{a(t),e.runAudit(t)},children:t},t))})]}),e.error&&(0,b.jsxs)("div",{className:"rl-error",children:[(0,b.jsx)(e1.AlertTriangle,{size:14}),(0,b.jsx)("span",{children:e.error}),(0,b.jsx)("button",{onClick:()=>e.runAudit(t,!0),children:"retry"})]}),e.loading&&!e.audit&&(0,b.jsxs)("main",{className:"rl-loading",children:[(0,b.jsxs)("div",{className:"rl-loader-orbit",children:[(0,b.jsx)(te,{size:24}),(0,b.jsx)("i",{}),(0,b.jsx)("i",{}),(0,b.jsx)("i",{})]}),(0,b.jsx)("span",{children:e.stage?.stage||"CONNECTING"}),(0,b.jsx)("h2",{children:e.stage?.message||"Opening audit stream…"}),(0,b.jsx)("div",{className:"rl-progress",children:(0,b.jsx)("i",{style:{width:`${e.stage?.progress||1}%`}})}),e.profile&&(0,b.jsxs)("p",{children:["@",e.profile.handle," · ",tx(e.profile.wallet)]}),(0,b.jsx)("small",{children:"BUY/SELL tape → market identity → settlement → protocol gates"})]}),!e.loading&&!e.audit&&(0,b.jsxs)("main",{className:"rl-empty",children:[(0,b.jsxs)("div",{className:"rl-empty-grid",children:[(0,b.jsxs)("section",{children:[(0,b.jsx)("span",{children:"01 / ACCOUNTING"}),(0,b.jsx)(e6,{size:24}),(0,b.jsx)("h2",{children:"Find the real lane"}),(0,b.jsx)("p",{children:"Reconcile buys, sells, redemptions and current marks before discussing “edge,” while keeping unknown maker/taker fees explicit."})]}),(0,b.jsxs)("section",{children:[(0,b.jsx)("span",{children:"02 / BEHAVIOR"}),(0,b.jsx)(to.Target,{size:24}),(0,b.jsx)("h2",{children:"Break down intent"}),(0,b.jsx)("p",{children:"Split soccer P&L by moneyline, overs, unders, timing, price, league, sizing and hedge structure."})]}),(0,b.jsxs)("section",{children:[(0,b.jsx)("span",{children:"03 / FALSIFICATION"}),(0,b.jsx)(tn,{size:24}),(0,b.jsx)("h2",{children:"Try to kill the story"}),(0,b.jsx)("p",{children:"Compare chronological folds, expose missing controls and ask AI for the next non-lookahead test—not a flattering summary."})]})]}),(0,b.jsxs)("div",{className:"rl-empty-prompt",children:[(0,b.jsx)("b",{children:"Start with a public Polymarket trader profile."}),(0,b.jsx)("span",{children:"The first pass is descriptive. A strategy is not promotable until independent value and forward execution gates pass."})]})]}),e.audit&&(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)("section",{className:"rl-profile-strip",children:[(0,b.jsxs)("div",{className:"rl-identity",children:[(0,b.jsx)("div",{className:"rl-avatar",children:e.audit.profile.avatar?(0,b.jsx)("img",{src:e.audit.profile.avatar,alt:""}):e.audit.profile.handle.slice(0,2).toUpperCase()}),(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{children:"PROFILE UNDER EXAMINATION"}),(0,b.jsxs)("b",{children:["@",e.audit.profile.handle]}),(0,b.jsx)("small",{children:e.audit.profile.pseudonym||tx(e.audit.profile.wallet)}
4)]}),(0,b.jsx)("a",{href:e.audit.profile.profile_url,target:"_blank",rel:"noreferrer",children:(0,b.jsx)(e9.ExternalLink,{size:12})})]}),(0,b.jsxs)("div",{className:"rl-coverage-line",children:[(0,b.jsxs)("span",{children:[(0,b.jsx)(e8.Database,{size:11}),e.audit.coverage.soccer_trade_rows.toLocaleString()," soccer fills"]}),(0,b.jsxs)("span",{children:[e.audit.coverage.soccer_assets.toLocaleString()," token legs"]}),(0,b.jsxs)("span",{children:[e.audit.coverage.soccer_matches.toLocaleString()," matches"]}),(0,b.jsxs)("span",{children:[tg(e.audit.coverage.from_ts_ms)," → ",tg(e.audit.coverage.to_ts_ms)]}),(0,b.jsx)("em",{className:e.audit.protocol.mode,children:e.audit.protocol.mode.replaceAll("_"," ")}),e.cached&&(0,b.jsx)("i",{children:"CACHED"})]}),(0,b.jsxs)("button",{className:"rl-refresh",onClick:()=>e.runAudit(e.audit.profile.wallet,!0),disabled:e.loading,children:[(0,b.jsx)(ts.RefreshCw,{size:12,className:e.loading?"spin":""}),"refresh tape"]})]}),(0,b.jsxs)("section",{className:"rl-kpis",children:[(0,b.jsx)(tw,{label:"Cash-Flow P&L",value:th(e.audit.headline.cashflow_pnl_usd,!0),note:`${th(e.audit.headline.fee_scenario_pnl_usd,!0)} if every fill was taker`,tone:tf(e.audit.headline.cashflow_pnl_usd)}),(0,b.jsx)(tw,{label:"Completed ROI",value:tp(e.audit.headline.completed_roi),note:`${th(e.audit.headline.completed_deployed_usd,!0)} settled capital`,tone:tf(e.audit.headline.completed_roi)}),(0,b.jsx)(tw,{label:"Match Win Rate",value:tp(e.audit.headline.win_rate,1),note:`${e.audit.headline.wins} wins / ${e.audit.headline.losses} losses`}),(0,b.jsx)(tw,{label:"Observed Deployed",value:th(e.audit.headline.deployed_usd,!0),note:`${th(e.audit.headline.avg_deployed_usd,!0)} avg / match`}),(0,b.jsx)(tw,{label:"Lifecycle",value:`${e.audit.headline.sell_fills} sells`,note:`${e.audit.headline.redemptions} redemptions \xb7 ${th(e.audit.headline.rebates_usd,!0)} rebates`}),(0,b.jsx)(tw,{label:"Hedged Matches",value:tp(e.audit.headline.hedged_rate,1),note:`${e.audit.headline.open} currently open`})]}),(0,b.jsx)("nav",{className:"rl-tabs",children:[["edge","Edge Map",to.Target],["hypothesis","Hypothesis Bench",e7],["ledger","Evidence Ledger",e8.Database],["protocol","Protocol Gates",tn]].map(([e,t,a])=>(0,b.jsxs)("button",{className:s===e?"active":"",onClick:()=>r(e),children:[(0,b.jsx)(a,{size:13}),t]},e))}),(0,b.jsxs)("div",{className:"rl-workbench",children:[(0,b.jsx)(tk,{audit:e.audit,filters:n,setFilters:l,preview:v}),(0,b.jsxs)("main",{className:"rl-canvas",children:["edge"===s&&(0,b.jsxs)("div",{className:"rl-edge-view",children:[(0,b.jsxs)("div",{className:"rl-section-head",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{children:"OBSERVED ECONOMICS"}),(0,b.jsx)("h2",{children:"Prop edge map"}),(0,b.jsx)("p",{children:"Match-grouped performance. Open positions use current mark and never enter the completed win rate."})]}),(0,b.jsxs)("div",{className:"rl-slice-chip",children:[(0,b.jsx)("span",{children:"ACTIVE SLICE"}),(0,b.jsxs)("b",{children:[v.completed," closed"]}),(0,b.jsxs)("em",{className:tf(v.completed_roi),children:[tp(v.completed_roi)," ROI"]})]})]}),(0,b.jsx)(ty,{rows:f}),(0,b.jsx)("div",{className:"rl-lane-grid",children:e.audit.lanes.map(e=>(0,b.jsxs)("button",{className:`rl-lane-card ${n.lane===e.key?"selected":""}`,onClick:()=>l({...n,lane:n.lane===e.key?"all":e.key}),children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{children:e.family.replaceAll("_"," ")}),(0,b.jsx)("b",{children:e.label})]}),(0,b.jsx)("strong",{className:tf(e.match.completed_pnl_usd),children:th(e.match.completed_pnl_usd,!0)}),(0,b.jsxs)("div",{className:"rl-lane-stats",children:[(0,b.jsxs)("span",{children:[(0,b.jsx)("i",{children:"ROI"}),(0,b.jsx)("b",{className:tf(e.match.completed_roi),children:tp(e.match.completed_roi)})]}),(0,b.jsxs)("span",{children:[(0,b.jsx)("i",{children:"WR"}),(0,b.jsx)("b",{children:tp(e.match.win_rate,0)})]}),(0,b.jsxs)("span",{children:[(0,b.jsx)("i",{children:"N"}),(0,b.jsx)("b",{children:e.match.completed})]})]}),(0,b.jsxs)("div",{className:"rl-lane-foot",children:[(0,b.jsxs)("span",{children:[tm(e.avg_entry)," avg entry"]}),(0,b.jsxs)("span",{children:[tp(e.hold_to_resolution_rate,0)," held"]}),(0,b.jsx)(e3.ChevronRight,{size:12})]})]},e.key))}),(0,b.jsxs)("div",{className:"rl-segment-grid",children:[(0,b.jsx)(tj,{title:"Entry Clock",rows:y}),(0,b.jsx)(tj,{title:"Price Bands",rows:w}),(0,b.jsx)(tj,{title:"League Niches",rows:N})]})]}),"hypothesis"===s&&(0,b.jsxs)("div",{className:"rl-hypothesis-view",children:[(0,b.jsx)("div",{className:"rl-section-head",children:(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{children:"FALSIFICATION WORKBENCH"}),(0,b.jsx)("h2",{children:"Hypothesis bench"}),(0,b.jsx)("p",{children:"Write the claim before looking at the result. The slice is compared with the remaining eligible tape and split chronologically."})]})}),(0,b.jsxs)("section",{className:"rl-hypothesis-editor",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("label",{children:"CLAIM UNDER TEST"}),(0,b.jsx)("textarea",{value:i,onChange:e=>o(e.target.value)})]}),(0,b.jsxs)("div",{className:"rl-hypothesis-actions",children:[(0,b.jsxs)("button",{className:"primary",disabled:e.testing,onClick:()=>e.testHypothesis(e.audit.profile.wallet,n,i),children:[e.testing?(0,b.jsx)(tt,{size:13,className:"spin"}):(0,b.jsx)(e7,{size:13}),"Test current slice"]}),(0,b.jsxs)("button",{onClick:()=>
4{if(!e.audit)return;let t=[{id:`${Date.now()}`,statement:i,filters:{...n},verdict:e.hypothesis?.verdict,roi:e.hypothesis?.selected.completed_roi,savedAt:Date.now()},...x].slice(0,40);g(t),localStorage.setItem(`openpoly.reverse-lab.notebook.${e.audit.profile.wallet}`,JSON.stringify(t))},children:[(0,b.jsx)(ta,{size:13}),"Save note"]})]})]}),e.hypothesis?(0,b.jsx)(tN,{result:e.hypothesis}):(0,b.jsxs)("div",{className:"rl-test-placeholder",children:[(0,b.jsx)(te,{size:20}),(0,b.jsx)("b",{children:"No test run yet"}),(0,b.jsx)("span",{children:"Choose a lane, clock, league or price band, then test the written claim."})]}),(0,b.jsxs)("section",{className:"rl-registry",children:[(0,b.jsxs)("header",{children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{children:"PROTOCOL REGISTRY"}),(0,b.jsx)("b",{children:e.audit.protocol.deep_report?"Point-in-time study attached":"Default research hypotheses"})]}),(0,b.jsx)("small",{children:e.audit.protocol.deep_report?`${e.audit.protocol.deep_report.frames.toLocaleString()} frames \xb7 ${e.audit.protocol.deep_report.events} events`:"click a hypothesis to load it"})]}),(0,b.jsx)("div",{className:"rl-registry-list",children:(e.audit.protocol.deep_report?.hypotheses||e.audit.protocol.default_hypotheses).slice(0,20).map(e=>(0,b.jsxs)("button",{onClick:()=>o(e.statement),children:[(0,b.jsx)("span",{children:e.hypothesis_id}),(0,b.jsxs)("div",{children:[(0,b.jsx)("b",{children:e.statement}),(0,b.jsxs)("small",{children:[e.feature||e.primary_feature," · ",e.expected_direction]})]}),null!=e.directional_hit_rate?(0,b.jsxs)("em",{className:"direction_supported"===e.status?"up":"flat",children:[tp(e.directional_hit_rate,0)," hit"]}):(0,b.jsx)(e3.ChevronRight,{size:12})]},e.hypothesis_id))})]}),(0,b.jsxs)("section",{className:"rl-notebook",children:[(0,b.jsxs)("header",{children:[(0,b.jsx)(ta,{size:13}),(0,b.jsx)("b",{children:"Research notebook"}),(0,b.jsxs)("span",{children:[x.length," saved"]})]}),x.length?x.map(t=>(0,b.jsxs)("div",{children:[(0,b.jsxs)("button",{onClick:()=>{o(t.statement),l(t.filters)},children:[(0,b.jsx)("b",{children:t.statement}),(0,b.jsxs)("small",{children:[new Date(t.savedAt).toLocaleString()," · ",t.verdict?.replaceAll("_"," ")||"untested"," ",null!=t.roi?`\xb7 ${tp(t.roi)} ROI`:""]})]}),(0,b.jsx)("button",{className:"delete",onClick:()=>(t=>{if(!e.audit)return;let a=x.filter(e=>e.id!==t);g(a),localStorage.setItem(`openpoly.reverse-lab.notebook.${e.audit.profile.wallet}`,JSON.stringify(a))})(t.id),children:(0,b.jsx)(k,{size:11})})]},t.id)):(0,b.jsx)("p",{children:"Save a slice and its result to build an iterative research trail for this trader."})]})]}),"ledger"===s&&(0,b.jsxs)("div",{className:"rl-ledger-view",children:[(0,b.jsxs)("div",{className:"rl-section-head",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{children:"AUDITABLE SOURCE TAPE"}),(0,b.jsx)("h2",{children:"Evidence ledger"}),(0,b.jsx)("p",{children:"One row per token asset. SELL proceeds and actual redemptions are included; unresolved inventory is marked."})]}),(0,b.jsxs)("label",{className:"rl-ledger-search",children:[(0,b.jsx)(j.Search,{size:13}),(0,b.jsx)("input",{value:u,onChange:e=>h(e.target.value),placeholder:"Find match, market, league…"})]})]}),(0,b.jsxs)("div",{className:"rl-ledger-accounting",children:[(0,b.jsx)(e8.Database,{size:13}),(0,b.jsx)("span",{children:e.audit.coverage.accounting_basis})]}),(0,b.jsxs)("div",{className:"rl-ledger-table-wrap",children:[(0,b.jsxs)("table",{className:"rl-ledger-table",children:[(0,b.jsx)("thead",{children:(0,b.jsxs)("tr",{children:[(0,b.jsx)("th",{children:"First Entry / Match"}),(0,b.jsx)("th",{children:"Prop Lane"}),(0,b.jsx)("th",{children:"Clock"}),(0,b.jsx)("th",{children:"Avg"}),(0,b.jsx)("th",{children:"Deployed"}),(0,b.jsx)("th",{children:"Lifecycle"}),(0,b.jsx)("th",{children:"Cash-Flow P&L"}),(0,b.jsx)("th",{children:"ROI"}),(0,b.jsx)("th",{children:"Book"})]})}),(0,b.jsx)("tbody",{children:S.map(e=>(0,b.jsxs)("tr",{onClick:()=>l({...n,lane:e.lane}),children:[(0,b.jsxs)("td",{children:[(0,b.jsx)("span",{children:tg(e.first_entry_ts_ms)}),(0,b.jsx)("b",{children:e.event_title}),(0,b.jsxs)("small",{children:[e.league," · ",e.market_title]})]}),(0,b.jsxs)("td",{children:[(0,b.jsx)("b",{children:e.lane_label}),(0,b.jsxs)("small",{children:[e.outcome,e.line?` \xb7 ${e.line}`:""]})]}),(0,b.jsxs)("td",{children:[(0,b.jsx)("b",{children:e.entry_phase}),(0,b.jsx)("small",{children:null!=e.entry_minute?`${e.entry_minute.toFixed(1)}′ scheduled`:e.entry_timing})]}),(0,b.jsxs)("td",{children:[(0,b.jsx)("b",{children:tm(e.avg_entry)}),(0,b.jsxs)("small",{children:[tm(e.effective_entry)," all-taker scenario"]})]}),(0,b.jsxs)("td",{children:[(0,b.jsx)("b",{children:th(e.deployed_usd)}),(0,b.jsxs)("small",{children:[e.buy_fills," buys"]})]}),(0,b.jsxs)("td",{children:[(0,b.jsx)("b",{children:e.status}),(0,b.jsx)("small",{children:e.sell_fills?`${e.sell_fills} sells`:e.redemptions?`${e.redemptions} redeem`:e.remaining_shares?"marked":"held"})]}),(0,b.jsxs)("td",{className:tf(e.cashflow_pnl_usd),children:[(0,b.jsx)("b",{children:th(e.cashflow_pnl_usd)}),(0,b.jsxs)("small",{children:[th(e.fee_scenario_pnl_usd)," all-taker · ",th(e.estimated_fee_usd)," fee"]})]}),(0,b.jsx)("td",{className:tf(e.roi),children:(0,b.jsx)("b",{children:tp(e.roi)})}),(0,b.jsx)("td",{children:e.hedged_match?(0,b.jsx)("span",{className:"rl-hedge yes",children:"HEDGE
4D"}):(0,b.jsx)("span",{className:"rl-hedge",children:"DIRECTIONAL"})})]},e.id))})]}),!S.length&&(0,b.jsx)("div",{className:"rl-ledger-empty",children:"No ledger rows match the current protocol slice."})]}),f.length>S.length&&(0,b.jsxs)("div",{className:"rl-table-cap",children:["Showing first ",S.length," of ",f.length," matching token legs."]})]}),"protocol"===s&&(0,b.jsxs)("div",{className:"rl-protocol-view",children:[(0,b.jsxs)("div",{className:"rl-section-head",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{children:e.audit.protocol.version}),(0,b.jsx)("h2",{children:"Promotion gates"}),(0,b.jsx)("p",{children:"A trader can be imitated accurately and still lose money. Behavior, value and execution stay separate."})]}),(0,b.jsxs)("div",{className:"rl-protocol-mode",children:[(0,b.jsx)("span",{children:"RESEARCH STATE"}),(0,b.jsx)("b",{children:e.audit.protocol.mode.replaceAll("_"," ")})]})]}),(0,b.jsx)("div",{className:"rl-gate-grid",children:e.audit.protocol.gates.map(e=>(0,b.jsxs)("div",{className:`rl-gate ${e.status}`,children:[(0,b.jsxs)("span",{children:["pass"===e.status?(0,b.jsx)(e4.Check,{size:12}):"warn"===e.status?(0,b.jsx)(e1.AlertTriangle,{size:12}):(0,b.jsx)(k,{size:12}),e.status]}),(0,b.jsx)("b",{children:e.label}),(0,b.jsx)("p",{children:e.detail})]},e.key))}),(0,b.jsxs)("div",{className:"rl-protocol-columns",children:[(0,b.jsxs)("section",{children:[(0,b.jsxs)("header",{children:[(0,b.jsx)(tn,{size:13}),(0,b.jsx)("b",{children:"Non-negotiable principles"})]}),e.audit.protocol.principles.map((e,t)=>(0,b.jsxs)("div",{className:"rl-principle",children:[(0,b.jsx)("span",{children:String(t+1).padStart(2,"0")}),(0,b.jsx)("p",{children:e})]},e))]}),(0,b.jsxs)("section",{children:[(0,b.jsxs)("header",{children:[(0,b.jsx)(e8.Database,{size:13}),(0,b.jsx)("b",{children:"Data lineage"})]}),(0,b.jsxs)("div",{className:"rl-lineage",children:[(0,b.jsx)("span",{children:"PUBLIC ACTIONS"}),(0,b.jsx)("b",{children:e.audit.coverage.all_trade_rows.toLocaleString()}),(0,b.jsx)("p",{children:"BUY/SELL rows queried chronologically beyond the normal offset window."})]}),(0,b.jsxs)("div",{className:"rl-lineage",children:[(0,b.jsx)("span",{children:"CONTRACT IDENTITY"}),(0,b.jsx)("b",{children:e.audit.coverage.market_metadata.toLocaleString()}),(0,b.jsx)("p",{children:"Both open and closed Gamma contracts resolved; local soccer metadata overlays when available."})]}),(0,b.jsxs)("div",{className:"rl-lineage",children:[(0,b.jsx)("span",{children:"VALUATION"}),(0,b.jsxs)("b",{children:[e.audit.coverage.redemption_rows.toLocaleString()," redeems"]}),(0,b.jsx)("p",{children:"Terminal payout or current public mark closes the remaining token inventory."})]})]})]}),e.audit.protocol.deep_report&&(0,b.jsxs)("section",{className:"rl-deep-report",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{children:"ATTACHED GOVERNED ARTIFACT"}),(0,b.jsx)("b",{children:e.audit.protocol.deep_report.artifact}),(0,b.jsxs)("small",{children:[e.audit.protocol.deep_report.frames.toLocaleString()," decision frames · ",e.audit.protocol.deep_report.actions," actions · ",e.audit.protocol.deep_report.leakage_issues," leakage issues"]})]}),(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{children:"WALK-FORWARD"}),(0,b.jsxs)("b",{children:[e.audit.protocol.deep_report.walk_forward_folds||0," folds"]}),(0,b.jsx)("small",{children:"event-grouped chronological partitions"})]}),(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{children:"PROMOTION"}),(0,b.jsx)("b",{className:"down",children:"NOT LIVE-READY"}),(0,b.jsx)("small",{children:"forward executable economics still required"})]})]}),(0,b.jsxs)("div",{className:"rl-limitations",children:[(0,b.jsx)(e1.AlertTriangle,{size:14}),(0,b.jsxs)("div",{children:[(0,b.jsx)("b",{children:"Accounting precision is explicit—not magical."}),(0,b.jsx)("p",{children:String(e.audit.protocol.limitations.fees||"")})]})]})]})]}),(0,b.jsxs)("aside",{className:"rl-ai-panel",children:[(0,b.jsxs)("div",{className:"rl-ai-head",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)(e5,{size:16}),(0,b.jsx)("span",{children:"AI RESEARCH COPILOT"})]}),(0,b.jsx)("em",{children:e.aiRead?.confidence||"grounded"})]}),(0,b.jsxs)("div",{className:"rl-ai-context",children:[(0,b.jsx)("span",{children:"SUPPLIED CONTEXT ONLY"}),(0,b.jsx)("b",{children:"all"===n.lane?"All soccer props":e.audit.lanes.find(e=>e.key===n.lane)?.label}),(0,b.jsxs)("div",{children:[(0,b.jsxs)("span",{children:[v.completed," closed ",n.unit,"s"]}
4),(0,b.jsxs)("span",{className:tf(v.completed_roi),children:[tp(v.completed_roi)," ROI"]})]})]}),!e.aiRead&&(0,b.jsxs)("div",{className:"rl-ai-fingerprint",children:[(0,b.jsx)("span",{children:"DETERMINISTIC FIRST READ"}),e.audit.fingerprint.map(e=>(0,b.jsxs)("div",{className:e.tone,children:[(0,b.jsx)("i",{}),(0,b.jsxs)("div",{children:[(0,b.jsx)("b",{children:e.title}),(0,b.jsx)("p",{children:e.text})]})]},e.title))]}),e.aiRead&&(0,b.jsxs)("div",{className:"rl-ai-read",children:[(0,b.jsxs)("section",{children:[(0,b.jsx)("span",{children:"RESEARCH READ"}),(0,b.jsx)("h3",{children:e.aiRead.summary}),(0,b.jsx)("p",{children:e.aiRead.edge_read})]}),(0,b.jsxs)("section",{className:"evidence",children:[(0,b.jsx)("span",{children:"EVIDENCE"}),e.aiRead.evidence.map(e=>(0,b.jsxs)("p",{children:[(0,b.jsx)(e4.Check,{size:11}),e]},e))]}),(0,b.jsxs)("section",{className:"contradictions",children:[(0,b.jsx)("span",{children:"WHAT BREAKS IT"}),e.aiRead.contradictions.map(e=>(0,b.jsxs)("p",{children:[(0,b.jsx)(k,{size:11}),e]},e))]}),(0,b.jsxs)("section",{children:[(0,b.jsx)("span",{children:"ANSWER"}),(0,b.jsx)("p",{children:e.aiRead.answer})]}),(0,b.jsxs)("section",{className:"rl-next-tests",children:[(0,b.jsx)("span",{children:"NEXT TESTS"}),e.aiRead.next_tests.map(e=>(0,b.jsxs)("button",{onClick:()=>{o(e.title),r("hypothesis")},children:[(0,b.jsx)(ti.Sparkles,{size:11}),(0,b.jsxs)("div",{children:[(0,b.jsx)("b",{children:e.title}),(0,b.jsx)("p",{children:e.why}),(0,b.jsx)("small",{children:e.protocol_change})]}),(0,b.jsx)(e2,{size:11})]},e.title))]}),(0,b.jsxs)("div",{className:"rl-ai-warning",children:[(0,b.jsx)(e1.AlertTriangle,{size:12}),e.aiRead.warning]})]}),(0,b.jsxs)("div",{className:"rl-ai-ask",children:[(0,b.jsx)("label",{children:"ASK ABOUT THIS SLICE"}),(0,b.jsx)("textarea",{value:c,onChange:e=>d(e.target.value)}),(0,b.jsxs)("button",{disabled:e.askingAi,onClick:()=>e.askAi(e.audit.profile.wallet,n,i,c),children:[e.askingAi?(0,b.jsx)(tt,{size:13,className:"spin"}):(0,b.jsx)(e5,{size:13}),e.askingAi?"Reasoning…":"Ask research AI"]}),(0,b.jsx)("small",{children:"AI cannot pass a gate. It proposes hypotheses for chronological validation."})]})]})]})]})]})}var t$=e.i(71808),tC=e.i(71540);let tM=[{key:"all",label:"Desk"},{key:"live",label:"Live today"},{key:"upcoming",label:"Next session"},{key:"edges",label:"Model gaps"},{key:"high",label:"Daily highs"},{key:"low",label:"Daily lows"}];function tE(e,t=0){return null==e?"—":`${(100*e).toFixed(t)}%`}function tA(e){return null==e?"—":`${Math.round(100*e)}\xa2`}function tT(e){return null==e?"—":`${e>=0?"+":"−"}${Math.abs(100*e).toFixed(1)}\xa2`}function tF(e){let t=Number(e||0);return Math.abs(t)>=1e6?`$${(t/1e6).toFixed(1)}m`:Math.abs(t)>=1e3?`$${(t/1e3).toFixed(t>=1e5?0:1)}k`:`$${Math.round(t)}`}function tP(e){let t=Number(e||0);return Math.abs(t)>=1e6?`${(t/1e6).toFixed(1)}m sh`:Math.abs(t)>=1e3?`${(t/1e3).toFixed(t>=1e5?0:1)}k sh`:`${t.toLocaleString(void 0,{maximumFractionDigits:t>=100?0:1})} sh`}function tR(e){return`${(100*Number(e||0)).toFixed(1)}\xa2`}function tO(e,t){let a=Math.max(0,Math.floor((t-e)/1e3));return a<5?"just now":a<60?`${a}s ago`:`${Math.floor(a/60)}m ago`}function tL(e){return new Date(`${e}T12:00:00Z`).toLocaleDateString(void 0,{month:"short",day:"numeric"})}function tI(e){return e&&e.split("T")[1]?.slice(0,5)||"—"}function tD(e){if(null==e||!Number.isFinite(e))return"—";let t=Math.floor(e),a=Math.round((e-t)*60);return`${String(t+Math.floor(a/60)).padStart(2,"0")}:${String(a%60).padStart(2,"0")}`}function tz(e,t){let a=t.trim().toLowerCase().split(/\s+/).filter(Boolean);if(!a.length)return!0;let[s,r,n]=e.target_date.split("-").map(Number),l=new Date(Date.UTC(s,(r||1)-1,n||1)),i=Number.isFinite(l.getTime())?l.toLocaleDateString("en-US",{timeZone:"UTC",month:"long",day:"numeric",year:"numeric"}):"",o=Number.isFinite(l.getTime())?l.toLocaleDateString("en-US",{timeZone:"UTC",month:"short",day:"numeric",year:"numeric"}):"",c=[e.slug,e.city,e.kind,e.station.code,e.station.name,e.title,e.target_date,i,o,`${r}/${n}/${s}`,`${r}/${n}`,`${n}/${r}/${s}`,`${n}/${r}`].join(" ").toLowerCase();return a.every(e=>c.includes(e))}function tB({market:e}){let t="live"===e.stage?`${e.hours_remaining?.toFixed(1)}h left`:"upcoming"===e.stage?"next session":"finalizing"===e.stage?"source lock":"feed down";return(0,b.jsxs)("span",{className:`wx-stage ${e.stage}`,children:[(0,b.jsx)("i",{}),t]})}function tW({market:e,selected:t,boughtBasketCount:a,onSelect:s}){let r=[...e.buckets].sort((e,t)=>
4(t.fair_probability||0)-(e.fair_probability||0)).slice(0,5),n=e.best_edge?.edge||0;return(0,b.jsxs)("button",{"data-weather-event":e.event_id,className:`wx-market-card${t?" selected":""}`,onClick:s,children:[(0,b.jsxs)("div",{className:"wx-card-top",children:[(0,b.jsx)("span",{className:"wx-station-code",children:e.station.code}),(0,b.jsx)(tB,{market:e}),(0,b.jsx)("span",{className:"wx-card-date",children:tL(e.target_date)})]}),(0,b.jsxs)("div",{className:"wx-card-city",children:[(0,b.jsx)("span",{children:"high"===e.kind?"MAX":"MIN"}),e.city,a>0&&(0,b.jsxs)("em",{className:"wx-bought-badge",title:`Active wallet currently holds ${a} bucket${1===a?"":"s"} in this market`,children:["BOUGHT ",a," ",1===a?"BASKET":"BASKETS"]})]}),(0,b.jsxs)("div",{className:"wx-card-read",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("small",{children:"path mean"}),(0,b.jsx)("b",{children:e.forecast?.mean_display||"—"})]}),(0,b.jsxs)("div",{children:[(0,b.jsxs)("small",{children:["verified ",e.kind]}),(0,b.jsx)("b",{children:e.observation?.effective_extreme_display||e.observation?.extreme_display||"not started"})]})]}),(0,b.jsxs)("div",{className:"wx-card-mode",children:[(0,b.jsx)("span",{children:"modal bucket"}),(0,b.jsx)("b",{children:e.forecast?.mode_bucket||"—"}),(0,b.jsx)("em",{children:tE(e.forecast?.mode_probability)})]}),(0,b.jsx)("div",{className:"wx-mini-bars","aria-label":"Top bucket probabilities",children:r.map(e=>(0,b.jsx)("i",{style:{height:`${Math.max(4,100*(e.fair_probability||0))}%`},title:`${e.label}: ${tE(e.fair_probability)}`},e.market_id))}),(0,b.jsxs)("div",{className:"wx-card-foot",children:[(0,b.jsxs)("span",{children:[tF(e.volume_24h)," today"]}),n>=.04&&e.best_edge?e.best_edge.guarded?(0,b.jsxs)("b",{className:"watch",title:`Gap is real but not executable yet — ${e.best_edge.guard_reason||"waiting on the station"}`,children:["⏳ ",e.best_edge.action," ",e.best_edge.label," · ",tT(n)]}):(0,b.jsxs)("b",{className:n>=.08?"hot":"warm",children:[e.best_edge.action," ",e.best_edge.label," · ",tT(n)]}):(0,b.jsx)("b",{className:"quiet",children:"no 4¢ gap"})]}),(0,b.jsx)("div",{className:"wx-dayline",children:(0,b.jsx)("i",{style:{width:`${Math.round(100*e.day_progress)}%`}})})]})}function tU({session:e,loading:t,onSelect:a}){return(0,b.jsxs)("button",{className:"wx-market-card wx-catalog-card",onClick:a,disabled:t,children:[(0,b.jsxs)("div",{className:"wx-card-top",children:[(0,b.jsx)("span",{className:"wx-station-code",children:e.station_code}),(0,b.jsxs)("span",{className:"wx-stage upcoming",children:[(0,b.jsx)("i",{}),e.opening?"opening now":"next session"]}),(0,b.jsx)("span",{className:"wx-card-date",children:tL(e.target_date)})]}),(0,b.jsxs)("div",{className:"wx-card-city",children:[(0,b.jsx)("span",{children:"high"===e.kind?"MAX":"MIN"}),e.city]}),(0,b.jsxs)("div",{className:"wx-card-read",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("small",{children:"resolution station"}),(0,b.jsx)("b",{children:e.station_name||e.station_code})]}),(0,b.jsxs)("div",{children:[(0,b.jsx)("small",{children:"source"}),(0,b.jsx)("b",{children:e.source_name})]})]}),(0,b.jsxs)("div",{className:"wx-card-mode",children:[(0,b.jsx)("span",{children:e.opening?"market just detected":"forecast on demand"}),(0,b.jsx)("b",{children:t?"LOADING…":`${e.market_count} BUCKET${1===e.market_count?"":"S"}`}),(0,b.jsx)("em",{children:e.unit})]}),(0,b.jsxs)("div",{className:"wx-card-foot",children:[(0,b.jsxs)("span",{children:[tF(e.volume_24h)," today"]}),(0,b.jsx)("b",{className:e.opening?"hot":"quiet",children:e.opening?"CLOB LIVE SIGNAL":"OPEN MODEL"})]})]})}function tH(){var e,t,a,s;let[r,n]=(0,_.useState)(null),[l,i]=(0,_.useState)(null),[o,c]=(0,_.useState)(!0),[d,u]=(0,_.useState)(!1),[h,p]=(0,_.useState)(null),[m,x]=(0,_.useState)(null),[g,f]=(0,_.useState)("all"),[v,y]=(0,_.useState)(""),[j,w]=(0,_.useState)(null),[N,k]=(0,_.useState)({}),[S,$]=(0,_.useState)(0),[C,M]=(0,_.useState)([]),[E,A]=(0,_.useState)("joining"),[T,F]=(0,_.useState)(0),[P,R]=(0,_.useState)([]),[O,L]=(0,_.useState)([]),[I,D]=(0,_.useState)("joining"),[z,B]=(0,_.useState)(0),[W,U]=(0,_.useState)(null),[H,q]=(0,_.useState)(()=>Date.now()),V=(0,_.useRef)(0),G=(0,_.useRef)(""),J=(0,_.useRef)(""),Y=(0,_.useCallback)(async(e=!1,t,a=!1,s,r=!1)=>{let l=++V.current,i=s??G.current,o=t??J.current;e&&u(!0);try{let t=i?`&focus_slug=${encodeURIComponent(i)}`:"",s=o?`&search=${encodeURIComponent(o)}`:"",c=await (0,er.authGetJson)(`/api/radar/weather?limit=18${e?"&refresh=true":""}${t}${s}`);if(l!==V.current)return!1;if(!c.data||!Array.isArray(c.data.markets))throw Error("Weather response did not contain a market board");let d=i?c.data.markets.find(e=>e.slug===i):null;if(r&&!d)return!1;if(n(c.data),d&&r&&(G.current=d.slug,w(d.event_id)),o&&a){let e=c.data.markets.find(e=>tz(e,o));e&&(G.current=e.slug,w(e.event_id))}return x(null),!0}catch(e){if(l!==V.current)return!1;return x(e instanceof Error?e.message:"Weather radar unavailable"),!1}finally{l===V.current&&(c(!1),u(!1))}},[]),K=(0,_.useCallback)(async(e=!1)=>{try{let t=await (0,er.authGetJson)(`/api/radar/weather/catalog${e?"?refresh=true":""}`);t.data&&Array.isArray(t.data.sessions)&&i(t.data)}catch{return}},[]);(0,_.useEffect)(()=>{Y();let e=window.setInterval(()=>Y(),45e3),t=window.setInterval(()=>q(Date.now()),1e3);return()=>{window.clearInterval(e),window.clearInterval(t)}},[Y]),(0,_.useEffect)(()=>{K();let e=window.setInterval(()=>K(),4e3);return()=>window.clearInterval(e)},[K]),(0,_.useEffect)(()=>{let e=v.trim().length>=2?v.trim():"";if(J.current===e)return;J.current=e;let t=window.setTimeout(()=>Y(!1,e,!0),300);return()=>window.clearTimeout(t)},[Y,v]);let X=r?.markets||[];(0,_.useEffect)(()=>{X.length&&w(e=>{if(e&&X.some(t=>t.event_id===e))return e;let t=X.find(e=>"live"===e.stage)||X[0];return G.current=t.slug,t.event_id})},[X]);let Z=v.trim().length>0,Q=(0,_.useMemo)(()=>X.filter(e=>!!tz(e,v)&&(!!Z||("live"===g?"live"===e.stage:"upcoming"===g?"upcoming"===e.stage:"edges"===g?(e.best_edge?.edge||0)>=.04:"high"===g?"high"===e.kind:"low"!==g||"low"===e.kind))),[X,g,v,Z]),ee=(0,_.useMemo)(()=>X.filter(e=>(e.best_edge?.edge??null)!==null).sort((e,t)=>
4(t.best_edge?.edge||0)-(e.best_edge?.edge||0)),[X]),et=ee[0]||null,ea="edges"===g&&!Z&&0===Q.length&&ee.length>0,es=(0,_.useMemo)(()=>new Set(X.map(e=>e.slug)),[X]),en=(0,_.useMemo)(()=>"upcoming"!==g||Z?[]:(l?.sessions||[]).filter(e=>("upcoming"===e.stage||e.opening)&&!es.has(e.slug)),[l?.sessions,g,es,Z]),el=ea?ee:"edges"!==g||Z?Q:[...Q].sort((e,t)=>(t.best_edge?.edge||0)-(e.best_edge?.edge||0)),ei=el.length+en.length,eo=Z?{title:"No open station or date matches that search.",hint:"Try a city, an ICAO code, or a date like “Seoul July 21”."}:"edges"===g?{title:"Our model agrees with the market right now.",hint:"No live station is reading far enough from its price to trade. Gaps show up once today’s stations start reporting — check back, or open the Desk tab."}:"live"===g?{title:"Nothing is live this minute.",hint:"No station is mid-session. Open Next session for what’s coming up."}:"upcoming"===g?{title:"No sessions queued next.",hint:"Everything currently trading is on the Desk tab."}:"high"===g?{title:"No daily-high markets on the board.",hint:"Switch to Daily lows or the full Desk."}:"low"===g?{title:"No daily-low markets on the board.",hint:"Switch to Daily highs or the full Desk."}:{title:"The desk is still loading stations.",hint:"The board refreshes every 45 seconds — give it a moment, or hit “force model run”."},ec=(Z?Q:X).find(e=>e.event_id===j)||el[0]||X[0]||null,ed=ec?.buckets.map(e=>e.condition_id).filter(Boolean).join(",")||"",eu=(0,_.useMemo)(()=>[...new Set(X.map(e=>e.event_id).filter(Boolean))].join(","),[X]),eh=ec?.forecast?.source_dynamics||null,ep=ec?.forecast?.timing,em=ec?.source.observation_feed==="resolution_unavailable",ex=ec?.source.observation_feed==="resolution_not_started",eg=(0,_.useCallback)(async e=>{G.current=e.slug,J.current="",y(""),p(e.slug);let t=!1;try{for(let a=0;a<3&&!t;a+=1){if(G.current!==e.slug)return;(t=await Y(!0,"",!1,e.slug,!0))||!(a<2)||await new Promise(e=>window.setTimeout(e,1500))}t||x("The market is open, but its complete Gamma metadata is still propagating. OpenPoly will retry automatically."),await K()}finally{p(t=>t===e.slug?null:t)}},[Y,K]);(0,_.useEffect)(()=>{ec?.slug&&(G.current=ec.slug)},[ec?.slug]),(0,_.useEffect)(()=>{j&&window.requestAnimationFrame(()=>{document.querySelector(`[data-weather-event="${j}"]`)?.scrollIntoView({block:"nearest"})})},[j]),(0,_.useEffect)(()=>{if(k({}),$(0),!ec)return;let e=ec.buckets.flatMap(e=>e.token_ids.slice(0,2)).filter(Boolean).slice(0,50);if(!e.length)return;let t=!0,a=()=>(0,er.authGetJson)(`/api/radar/books?tokens=${encodeURIComponent(e.join(","))}`).then(e=>{t&&(k(e.data?.tops||{}),$(Date.now()))}).catch(()=>{});a();let s=window.setInterval(a,5e3);return()=>{t=!1,window.clearInterval(s)}},[ec?.event_id]),(0,_.useEffect)(()=>{let e=!0;if(M([]),F(0),R([]),!ed)return A("unavailable"),()=>{e=!1};A("joining");let t=()=>(0,er.authGetJson)(`/api/trader-watch/positions?condition_ids=${encodeURIComponent(ed)}`).then(t=>{e&&(M(t.data?.positions||[]),F(Number(t.data?.checked_at_ms||Date.now())),R(t.data?.stale_handles||[]),A((t.data?.stale_handles||[]).length?"stale":"live"))}).catch(()=>{e&&A("error")});t();let a=window.setInterval(t,25e3);return()=>{e=!1,window.clearInterval(a)}},[ed]),(0,_.useEffect)(()=>{let e=!0;if(L([]),B(0),!eu)return U(null),D("unavailable"),()=>{e=!1};D("joining");let t=()=>(0,er.authGetJson)(`/api/wallets/positions?event_ids=${encodeURIComponent(eu)}`).then(t=>{if(!e)return;let a=String(t.data?.wallet_id||"");L(t.data?.positions||[]),B(Date.now()),U(a?{id:a,name:String(t.data?.wallet_name||"Active wallet"),address:t.data?.address||null}:null),D(a?"live":"no_wallet")}).catch(()=>{e&&D("error")});t();let a=window.setInterval(t,1e4);return()=>{e=!1,window.clearInterval(a)}},[eu]);let ef=(0,_.useMemo)(()=>{let e=new Map;for(let t of C){let a=String(t.condition_id||"").toLowerCase();if(!a)continue;let s=e.get(a)||new Map,r=s.get(t.handle)||{handle:t.handle,profile_url:t.profile_url,positions:[],hedged:!1,cost_basis:0};r.positions.push(t),r.cost_basis+=Number(t.cost_basis||0);let n=new Set(r.positions.map(e=>e.outcome.toLowerCase()));r.hedged=n.has("yes")&&n.has("no"),s.set(t.handle,r),e.set(a,s)}let t=new Map;for(let[a,s]of e.entries())t.set(a,[...s.values()].map(e=>({...e,positions:[...e.positions].sort((e,t)=>
4Number("no"===e.outcome.toLowerCase())-Number("no"===t.outcome.toLowerCase()))})).sort((e,t)=>t.cost_basis-e.cost_basis));return t},[C]),eb=(0,_.useMemo)(()=>{let e=new Map;for(let t of O){let a=String(t.conditionId||"").toLowerCase();if(!a)continue;let s=e.get(a)||[];s.push(t),e.set(a,s)}for(let t of e.values())t.sort((e,t)=>Number("no"===String(e.outcome||"").toLowerCase())-Number("no"===String(t.outcome||"").toLowerCase()));return e},[O]),e_=(0,_.useMemo)(()=>new Map(X.map(e=>[e.event_id,new Set(e.buckets.map(e=>String(e.condition_id||"").toLowerCase()).filter(e=>e&&eb.has(e))).size])),[X,eb]),ev=!!ec?.forecast?.coverage?.degraded,ey=ep?.source_pending||ep?.status==="SOURCE_PENDING"?"resolution source pending":ep&&"POST_PEAK"!==ep.status?`station timing ${ep.status.toLowerCase().replaceAll("_"," ")}`:ep&&!ep.entry_ready?"station clock not ready":null,ej=ev||!!ey,ew=ev?ec?.forecast?.coverage?.reason||"regional model coverage":ey||"execution guard",eN=(0,_.useMemo)(()=>ec?.buckets.map(e=>({bucket:e,read:function(e,t,a=!1){let s=e.token_ids[0]?t[e.token_ids[0]]:null,r=e.token_ids[1]?t[e.token_ids[1]]:null,n=e.fair_probability,l=s?.ask??e.yes_entry,i=r?.ask??e.no_entry,o=s?(s.bid+s.ask)/2:e.market_probability,c=null!=n&&null!=l?n-l:null,d=null!=n&&null!=i?1-n-i:null,u=null,h=null,p=null;(null!=c||null!=d)&&(null==d||null!=c&&c>=d?(u="YES",h=c,p=l):(u="NO",h=d,p=i));let m=null!=h&&h>=.08?"strong":null!=h&&h>=.04?"watch":"none";return{market:o,yesAsk:l,noAsk:i,action:u,edge:h,entry:p,strength:a?"none":m,live:!!(s||r),guarded:a}}(e,N,ej)}))||[],[ec?.buckets,N,ej]),ek=(0,_.useMemo)(()=>eN.filter(e=>!e.read.guarded&&null!=e.read.edge).sort((e,t)=>(t.read.edge||-1)-(e.read.edge||-1))[0]||null,[eN]),eS=(0,_.useMemo)(()=>ej?null:eN.slice(0,-1).map((e,t)=>{let a=eN[t+1],s=e.bucket.fair_probability,r=a.bucket.fair_probability;if(null==s||null==r)return null;let n=s+r,l=null!=e.read.yesAsk&&null!=a.read.yesAsk?e.read.yesAsk+a.read.yesAsk:null,i=null!=e.read.market&&null!=a.read.market?e.read.market+a.read.market:null;return{labels:[e.bucket.label,a.bucket.label],fair:n,entry:l,market:i,edge:null==l?null:n-l}}).filter(e=>null!=e).sort((e,t)=>t.fair-e.fair||(t.edge||-1)-(e.edge||-1))[0]||null,[eN,ej]);return o&&!r?(0,b.jsxs)("div",{className:"wx-view wx-loading",children:[(0,b.jsx)("span",{className:"wx-radar-loader",children:(0,b.jsx)("i",{})}),(0,b.jsx)("b",{children:"Opening the weather desk…"}),(0,b.jsx)("span",{children:"Joining resolution stations, live observations, model runs and order books."})]}):(0,b.jsxs)("div",{className:"wx-view",children:[ec&&(0,b.jsx)(tC.TradeWidgetSource,{marketSlug:ec.slug,sourceKind:"weather",title:`${ec.city} ${"high"===ec.kind?"high":"low"} \xb7 ${ec.station.code} \xb7 ${tL(ec.target_date)}`}),(0,b.jsxs)("header",{className:"wx-header",children:[(0,b.jsxs)("div",{className:"wx-lockup",children:[(0,b.jsxs)("span",{className:"wx-radar-mark",children:[(0,b.jsx)("i",{}),(0,b.jsx)("i",{}),(0,b.jsx)("i",{})]}),(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{className:"wx-eyebrow",children:"STATION OUTCOME DESK // WX-01"}),(0,b.jsx)("h1",{children:"Weather Radar"})]}),(0,b.jsxs)("span",{className:"wx-live",children:[(0,b.jsx)("i",{})," LIVE SOURCES"]})]}),(0,b.jsx)("p",{children:"Forecast the exact number the resolution source will print—not generic city weather. Every path is snapped through station rules before it reaches a market bucket."}),(0,b.jsxs)("div",{className:"wx-head-controls",children:[(0,b.jsx)("button",{onClick:()=>Y(!0),disabled:d,children:d?"re-running models…":"↻ force model run"}),(0,b.jsx)("span",{children:r?tO(r.generated_at_ms,H):"—"})]})]}),(0,b.jsxs)("section",{className:"wx-kpis",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{children:"DESK COVERAGE"}),(0,b.jsx)("b",{children:l?.stats.contracts||r?.catalog?.contracts||r?.stats.markets||0}),(0,b.jsxs)("small",{children:[l?.stats.stations??r?.catalog?.stations??0," stations · ",l?.stats.live??r?.catalog?.live??r?.stats.live??0," live · ",l?.stats.upcoming??r?.catalog?.upcoming??r?.stats.upcoming??0," next"]})]}),(0,b.jsxs)("div",{className:(r?.stats.source_dislocations||0)>0?"active":"",children:[(0,b.jsx)("span",{children:"FRESH STATIONS"}),(0,b.jsx)("b",{children:r?.stats.stations_fresh||0}),(0,b.jsxs)("small",{children:["≤90m · ",r?.stats.source_dislocations||0," source gaps"]})]}),(0,b.jsxs)("div",{className:(r?.stats.signals||0)>0?"active":"",children:[(0,b.jsx)("span",{children:"MODEL GAPS ≥4¢"}),(0,b.jsx)("b",{children:r?.stats.signals||0}),(0,b.jsxs)("small",{children:[r?.stats.signals_tradeable||0," tradeable now · ",r?.stats.strong_signals||0," over 8¢"]})]}),(0,b.jsxs)("div",{className:(r?.stats.best_edge||0)>=.08?"hot":"",children:[(0,b.jsx)("span",{children:"LARGEST GAP"}),(0,b.jsx)("b",{children:tT(r?.stats.best_edge)}),(0,b.jsx)("small",{children:"before fees + slippage"})]}),(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{children:"24H WEATHER TAPE"}),(0,b.jsx)("b",{children:tF(r?.stats.volume_24h)}),(0,b.jsx)("small",{children:"tracked event volume"})]})]}),(0,b.jsxs)("div",{className:"wx-toolbar",children:[(0,b.jsx)("div",{className:"wx-filters",children:tM.map(e=>(0,b.jsx)("button",{className:g===e.key?"active":"",onClick:()=>f(e.key),children:e.label},e.key))}),(0,b.jsxs)("label",{className:"wx-search",children:[(0,b.jsx)("span",{children:"⌕"}
4),(0,b.jsx)("input",{value:v,onChange:e=>y(e.target.value),placeholder:"city / station / date"})]}),(0,b.jsxs)("div",{className:"wx-method",children:[(0,b.jsx)("b",{children:r?.model.version||"station-ensemble-v7"}),(0,b.jsx)("span",{children:"verified floor → station clock → source settlement → regional ensemble → CLOB"})]})]}),(m||r?.error||r?.stale)&&(0,b.jsx)("div",{className:"wx-notice-stack",children:(0,b.jsx)("div",{className:"wx-warning",children:m||r?.error||"Live refresh failed; showing the last good weather snapshot."})}),(0,b.jsxs)("main",{className:"wx-workspace",children:[(0,b.jsxs)("aside",{className:"wx-market-panel",children:[(0,b.jsxs)("div",{className:"wx-panel-head",children:[(0,b.jsx)("span",{children:ea?"LARGEST GAPS":"upcoming"!==g||Z?"ACTIVE BOARD":"NEXT SESSION CATALOG"}),(0,b.jsxs)("b",{children:[ei," contracts"]})]}),(0,b.jsxs)("div",{className:"wx-market-scroll",children:[ea&&et&&(0,b.jsxs)("div",{className:"wx-gap-note",children:[(0,b.jsx)("b",{children:"Our model agrees with the market right now."}),(0,b.jsxs)("span",{children:["No live station is off its price by ","4","¢ — the gap it needs to beat fees. Showing the biggest gaps we do see (top: ",et.city||et.station.code," ",(100*Math.abs(et.best_edge?.edge||0)).toFixed(1),"¢)."]})]}),ei?(0,b.jsxs)(b.Fragment,{children:[el.map(e=>(0,b.jsx)(tW,{market:e,selected:ec?.event_id===e.event_id,boughtBasketCount:e_.get(e.event_id)||0,onSelect:()=>{G.current=e.slug,w(e.event_id)}},e.event_id)),en.map(e=>(0,b.jsx)(tU,{session:e,loading:h===e.slug,onSelect:()=>eg(e)},e.event_id||e.slug))]}):(0,b.jsxs)("div",{className:"wx-empty",children:[(0,b.jsx)("b",{children:eo.title}),(0,b.jsx)("span",{children:eo.hint})]})]})]}),(0,b.jsx)("section",{className:"wx-detail-panel",children:ec?(0,b.jsxs)("div",{className:"wx-detail-scroll",children:[(0,b.jsxs)("section",{className:"wx-detail-hero",children:[(0,b.jsxs)("div",{className:"wx-detail-title",children:[(0,b.jsxs)("div",{className:"wx-detail-overline",children:[(0,b.jsx)("span",{children:ec.station.code}),(0,b.jsx)("span",{children:"high"===ec.kind?"DAILY MAX":"DAILY MIN"}),(0,b.jsx)("span",{children:tL(ec.target_date)}),(0,b.jsx)(tB,{market:ec})]}),(0,b.jsx)("h2",{children:ec.city}),(0,b.jsxs)("p",{children:[ec.station.name," · ",ec.station.timezone?.replaceAll("_"," ")||"timezone unresolved"]})]}),(0,b.jsxs)("a",{className:"wx-source-ticket",href:ec.source.url||ec.url,target:"_blank",rel:"noreferrer",children:[(0,b.jsx)("span",{children:"RESOLUTION TAPE"}),(0,b.jsxs)("b",{children:[ec.source.name," ↗"]}),(0,b.jsx)("small",{children:ec.source.lag_note||ec.source.revision_policy.replaceAll("_"," ")})]})]}),ec.forecast?(0,b.jsxs)(b.Fragment,{children:[ec.source.station_mismatch&&(0,b.jsxs)("section",{className:`wx-source-dislocation ${eh?.status||"source_conflict"}`,children:[(0,b.jsxs)("div",{className:"wx-dislocation-head",children:[(0,b.jsxs)("div",{children:[(0,b.jsxs)("span",{children:["SOURCE DISLOCATION // ","rewrite_watch"===(e=eh?.status)?"REWRITE WATCH":"provisional_rewrite"===e?"LIVE ROW CHANGED":"blend_zone"===e?"BLEND ZONE":"source_conflict"===e?"SOURCE CONFLICT":"FEEDS ALIGNED"]}),(0,b.jsxs)("b",{children:[ec.source.name," maps ",ec.station.code," to ",ec.source.resolution_station_name||"another station",ec.source.resolution_station_code?` (${ec.source.resolution_station_code})`:""]})]}),(0,b.jsxs)("small",{children:["The number visible now is not final: the newest ",ec.observation?.mutable_reports||0," WU rows remain mutable until the next-day lock."]})]}),eh?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)("div",{className:"wx-tape-grid",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{children:"WU PUBLISHED MAX"}),(0,b.jsx)("b",{children:eh.published_display}),(0,b.jsx)("small",{children:eh.stable_display?`stable floor ${eh.stable_display}`:"no stable row yet"})]}),(0,b.jsxs)("div",{children:[(0,b.jsxs)("span",{children:[eh.upstream_station_name?.toUpperCase()||"UPSTREAM"," OFFICIAL MAX"]}),(0,b.jsxs)("b",{children:[eh.upstream_raw_c.toFixed(1),"°C"]}),(0,b.jsxs)("small",{children:["rounds to ",eh.upstream_display]})]}),(0,b.jsxs)("div",{children:[(0,b.jsxs)("span",{children:[ec.station.code," METAR MAX"]}),(0,b.jsx)("b",{children:eh.reference_display}),(0,b.jsx)("small",{children:"airport tape, not direct resolver"})]})]}),(0,b.jsxs)("div",{className:"wx-rewrite-prior",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{children:"AUDITED FINAL-PRINT PRIOR"}),(0,b.jsx)("b",{children:eh.outcomes.map(e=>`${e.display} ${tE(e.probability)}`).join(" · ")}),(0,b.jsxs)("small",{children:[eh.condition," · ",eh.audit.conditional_days," matching days inside a ",eh.audit.days,"-day audit"]})]}),(0,b.jsxs)("div",{className:"wx-rewrite-odds",children:[(0,b.jsx)("span",{children:eh.down_probability>eh.up_probability?"FINAL BELOW WU":"FINAL ABOVE WU"}),(0,b.jsx)("b",{children:tE(Math.max(eh.up_probability,eh.down_probability))}),(0,b.jsxs)("small",{children:[tE(eh.prior_weight)," weight in live fair"]})]})]}),(0,b.jsx)("p",{children:"Trade the inconsistency only when the executable bucket ask is below the rewrite-adjusted fair. Raw Lau or METAR alone is not a lock because WU historically often kept the hourly print 1°C lower."})]}):(0,b.jsx)("p",{children:"The airport METAR is reference-only. OpenPoly is collecting the remapped source and its upstream station before issuing a rewrite probability."})]}),(0,b.jsxs)("section",{className:"wx-primary-readouts",children:[(0,b.jsxs)("div",{className:"wx-observed-readout",children:[(0,b.jsx)("span",{children:em?"RESOLUTION TAPE UNAVAILABLE":ex?"RESOLUTION TAPE NOT STARTED":ec.observation?.effective_extreme_source==="matching_metar_pending"?"MATCHING REPORT // WU PENDING":ec.observation?.effective_extreme_source&&"resolution"!==ec.observation.effective_extreme_source?"LIVE VERIFIED FLOOR":ec.observation?.extreme_display?"STABLE RESOLUTION FLOOR":"PUBLISHED TAPE // PROVISIONAL"}),(0,b.jsx)("b",{children:ec.observation?.effective_extreme_display||ec.observation?.extreme_display||ec.observation?.published_extreme_display||"NOT STARTED"}),(0,b.jsx)("small",{children:em?`${ec.station.code} reference ${ec.observation?.reference_extreme_display||"—"} is not a settlement floor \xb7 signals guarded`:ex?`Target-day tape opens at local midnight \xb7 day-ahead ensemble remains active`:ec.observation?.effective_extreme_source==="
4kma_amo"?`KMA live ${ec.observation.upstream_raw_current_c?.toFixed(1)||"—"}\xb0C \xb7 WU published ${ec.observation.published_extreme_display||"—"}`:ec.observation?.effective_extreme_source==="matching_metar"||ec.observation?.effective_extreme_source==="matching_metar_pending"?`${ec.station.code} METAR already ${ec.observation.reference_extreme_display||"—"} \xb7 WU published ${ec.observation.published_extreme_display||"—"}`:ec.observation?`WU published ${ec.observation.published_extreme_display||"—"} \xb7 ${ec.observation.mutable_reports||0} newest rows mutable${null!=ec.observation.reference_extreme&&null!=ec.observation.extreme&&ec.observation.reference_extreme!==ec.observation.extreme?` \xb7 ${ec.station.code} METAR ${ec.observation.reference_extreme_display||"—"} is reference-only`:""}`:"waiting for source window"})]}),(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{children:"EXPECTED VALUE"}),(0,b.jsx)("b",{children:ec.forecast.mean_display}),(0,b.jsx)("small",{children:"average across all resolved paths"})]}),(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{children:"MEDIAN PATH"}),(0,b.jsx)("b",{children:ec.forecast.median_display}),(0,b.jsx)("small",{children:"half the paths finish either side"})]}),(0,b.jsxs)("div",{className:"mode",children:[(0,b.jsx)("span",{children:"MOST LIKELY BUCKET"}),(0,b.jsx)("b",{children:ec.forecast.mode_bucket}),(0,b.jsxs)("small",{children:[tE(ec.forecast.mode_probability,1)," of modeled paths"]})]})]}),(0,b.jsxs)("section",{className:"wx-nowcast-grid",children:[(0,b.jsxs)("div",{className:"wx-thermal-card",children:[(0,b.jsxs)("div",{className:"wx-section-label",children:[(0,b.jsx)("span",{children:"THERMAL RUNWAY"}),(0,b.jsxs)("small",{children:[Math.round(100*ec.day_progress),"% elapsed · station time ",function(e,t){if(!e)return"—";try{return new Intl.DateTimeFormat("en-GB",{timeZone:e,hour:"2-digit",minute:"2-digit",hourCycle:"h23"}).format(new Date(t))}catch{return"—"}}(ec.station.timezone,H)]})]}),(0,b.jsxs)("div",{className:"wx-range-call",children:[(0,b.jsx)("b",{children:ec.forecast.interval_67.display}),(0,b.jsx)("span",{children:"2-in-3 landing zone"})]}),(0,b.jsxs)("div",{className:"wx-runway",children:[(0,b.jsx)("i",{style:{width:`${Math.max(2,100*ec.day_progress)}%`}}),(0,b.jsx)("em",{style:{left:`${Math.min(98,Math.max(2,100*ec.day_progress))}%`}})]}),(0,b.jsxs)("div",{className:"wx-runway-meta",children:[(0,b.jsxs)("span",{children:["current ",ec.observation?.upstream_hard_bound&&null!=ec.observation.upstream_raw_current_c?`${ec.observation.upstream_raw_current_c.toFixed(1)}\xb0C`:ec.observation?.reference_current_display||ec.observation?.current_display||"—"]}),(0,b.jsxs)("span",{children:["expected ",ec.kind," near ",tI(ec.forecast.peak_time_local)]}),(0,b.jsx)("span",{children:null!=ec.hours_remaining?`${ec.hours_remaining.toFixed(1)}h to local midnight`:"source finalizing"})]}),(0,b.jsxs)("div",{className:"wx-runway-meta wx-clock-meta",children:[(0,b.jsxs)("span",{children:["calibrated P90 ",tD(ep?.profile.final_extreme_p90_hour)," · P95 ",tD(ep?.profile.final_extreme_p95_hour)]}),(0,b.jsxs)("span",{children:[ec.observation?.cloud_cover||"cloud n/a"," · ",null==(t=ec.observation?.wind_direction)?"—":["N","NE","E","SE","S","SW","W","NW"][Math.round(t/45)%8]," ",ec.observation?.wind_speed_kt!=null?`${ec.observation.wind_speed_kt}kt`:"wind n/a"]}),(0,b.jsx)("span",{children:function(e,t){if(!e)return"next report unknown";let a=Math.max(0,Math.ceil((new Date(e).getTime()-t)/6e4));return a<=1?"report due now":`next report ~${a}m`}(ep?.next_report_local,H)})]})]}),(0,b.jsxs)("div",{className:`wx-maturity ${(ep?.status||"EARLY").toLowerCase()}`,children:[(0,b.jsx)("span",{children:"STATION CLOCK"}),(0,b.jsx)("b",{children:"PEAK_WINDOW"===(a=ep?.status)?"PEAK WINDOW":"POST_PEAK"===a?"POST-PEAK":"SOURCE_PENDING"===a?"SOURCE PENDING":"FINALIZATION_PENDING"===a?"FINALIZING":"SETTLEMENT_SAFE"===a?"SETTLEMENT SAFE":"EARLY"}),(0,b.jsxs)("small",{children:[null!=(s=ep?.hours_from_peak)&&Number.isFinite(s)?.15>Math.abs(s)?"at modeled peak":`${Math.abs(s).toFixed(1)}h ${s>0?"after":"before"} modeled peak`:"peak distance unavailable"," · safe-time guide ",tI(ep?.safe_after_local)]})]}),(0,b.jsxs)("div",{className:"wx-new-extreme",children:[(0,b.jsxs)("span",{children:["PHYSICAL NEW ",ec.kind.toUpperCase()]}),(0,b.jsx)("b",{children:tE(ep?.physical_new_extreme_probability??ec.forecast.new_extreme_probability,1)}),(0,b.jsxs)("small",{children:["raw paths ",tE(ep?.raw_model_new_extreme_probability,1)," · station clock calibrated"]})]}
4),(0,b.jsxs)("div",{className:`wx-settlement${ep?.source_pending?" pending":""}`,children:[(0,b.jsx)("span",{children:"SETTLEMENT REVISION RISK"}),(0,b.jsx)("b",{children:tE(ep?.settlement_revision_probability??ec.forecast.settlement_revision_probability,1)}),(0,b.jsx)("small",{children:em?`${ec.source.name} unavailable \xb7 reference feed only`:ex?`source opens on ${tL(ec.target_date)}`:ep?.source_pending?`source ${Math.round(ep.source_gap_minutes||0)}m behind \xb7 do not treat as locked`:`${ec.source.report_cadence_minutes||"—"}m source cadence \xb7 tape aligned`})]}),(0,b.jsxs)("div",{className:`wx-confidence ${ec.forecast.confidence}`,children:[(0,b.jsx)("span",{children:"MODEL COHESION"}),(0,b.jsx)("b",{children:ec.forecast.confidence}),(0,b.jsx)("small",{children:ec.forecast.coverage?.degraded?`signals guarded \xb7 ${ec.forecast.coverage.reason}`:`${ec.forecast.model_count} models \xb7 spread ${ec.forecast.model_spread.toFixed(1)}\xb0${ec.unit}`})]})]}),(0,b.jsx)(t$.default,{eventId:ec.event_id,eventSlug:ec.slug},ec.event_id),eS&&(0,b.jsxs)("section",{className:`wx-pair-call${(eS.edge||0)>=.08?" strong":(eS.edge||0)>=.04?" watch":""}`,children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{children:"ADJACENT TWO-BUCKET COVER"}),(0,b.jsx)("b",{children:eS.labels.join(" + ")}),(0,b.jsx)("small",{children:"One ticket wins if the source resolves into either neighboring bucket."})]}),(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{children:"OPENPOLY FAIR"}),(0,b.jsx)("b",{children:tE(eS.fair,1)}),(0,b.jsxs)("small",{children:[tE(r?.model.benchmark?.d1_adjacent_two_accuracy,1)," held-out D1 coverage"]})]}),(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{children:"COMBINED LIVE ASK"}),(0,b.jsx)("b",{children:tA(eS.entry)}),(0,b.jsxs)("small",{children:[tE(eS.market,1)," midpoint mass"]})]}),(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{children:"EXECUTABLE GAP"}),(0,b.jsx)("b",{children:tT(eS.edge)}),(0,b.jsx)("small",{children:"before fees and slippage"})]})]}),(0,b.jsxs)("section",{className:"wx-section wx-buckets",children:[(0,b.jsxs)("div",{className:"wx-section-head",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{children:"EXECUTABLE DISTRIBUTION"}),(0,b.jsx)("b",{children:"Every bucket, source-rounded"})]}),(0,b.jsxs)("div",{className:"wx-book-states",children:[(0,b.jsxs)("div",{className:"wx-book-state",children:[(0,b.jsx)("i",{className:S?"live":""}),"CLOB ",S?tO(S,H):"joining…"]}),(0,b.jsxs)("div",{className:"wx-book-state",title:W?`Active wallet: ${W.name}${W.address?` \xb7 ${W.address}`:""}`:"No active wallet selected in Wallet Management",children:[(0,b.jsx)("i",{className:"live"===I?"live":"error"===I?"stale":""}),"WALLET ","no_wallet"===I?"not set":"unavailable"===I?"unmapped":"error"===I?"offline":z?tO(z,H):"joining…"]}),(0,b.jsxs)("div",{className:"wx-book-state",title:P.length?`Cached positions for: ${P.map(e=>`@${e}`).join(", ")}`:"Current public positions held by profiles in Trader Watch",children:[(0,b.jsx)("i",{className:"live"===E?"live":"stale"===E?"stale":""}),"WATCH ",T?tO(T,H):"unavailable"===E?"unmapped":"error"===E?"offline":"joining…"]})]})]}),(0,b.jsx)("div",{className:"wx-bucket-scroll",children:(0,b.jsxs)("div",{className:"wx-bucket-table",children:[(0,b.jsxs)("div",{className:"wx-bucket-header",children:[(0,b.jsx)("span",{children:"Outcome"}),(0,b.jsx)("span",{children:"OpenPoly fair"}),(0,b.jsx)("span",{children:"Market"}),(0,b.jsx)("span",{children:"Executable call"}),(0,b.jsx)("span",{children:"Your wallet + Trader Watch"}),(0,b.jsx)("span",{children:"24h tape"}),(0,b.jsx)("span",{})]}),eN.map(({bucket:e,read:t})=>{let a=!t.guarded&&(t.edge||0)>=.04,s=eb.get(String(e.condition_id||"").toLowerCase())||[],r=new Set(s.map(e=>String(e.outcome||"").toLowerCase())),n=r.has("yes")&&r.has("no"),l=ef.get(String(e.condition_id||"").toLowerCase())||[];return(0,b.jsxs)("div",{"data-weather-bucket":e.slug,className:`wx-bucket-row${a?` ${t.strength}`:""}`,children:[(0,b.jsxs)("div",{className:"wx-bucket-name",children:[(0,b.jsx)("b",{children:e.label}),(0,b.jsx)("span",{children:(0,b.jsx)("i",{style:{width:`${Math.max(1,100*(e.fair_probability||0))}%`}})})]}),(0,b.jsxs)("div",{className:"wx-prob",children:[(0,b.jsx)("b",{children:tE(e.fair_probability,1)}),(0,b.jsx)("small",{children:"model"})]}),(0,b.jsxs)("div",{className:"wx-prob",children:[(0,b.jsx)("b",{children:tE(t.market,1)}),(0,b.jsx)("small",{children:t.live?"live midpoint":"Gamma"})]}),(0,b.jsx)("div",{className:`wx-call ${a?t.action?.toLowerCase():"flat"}`,children:!t.guarded&&t.action&&null!=t.edge?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)("b",{children:[t.action," @ ",tA(t.entry)]}),(0,b.jsxs)("small",{children:[tT(t.edge)," model gap"]})]}):(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)("b",{children:"PASS"}),(0,b.jsx)("small",{children:t.guarded?ew:"no executable book"})]})}),(0,b.jsxs)("div",{className:"wx-watch-positions",children:[s.length>0&&(0,b.jsxs)("div",{className:"wx-watch-position mine",title:`${W?.name||"Active wallet"} \xb7 ${s.map(e=>`${String(e.outcome||"").toUpperCase()} ${tP(Number(e.size||0))} at ${tR(Number(e.avgPrice||0))} average, now ${tR(Number(e.curPrice||0))}`).join(" · ")}`,children:[(0,b.jsxs)("div",{children:[(0,b.jsxs)("strong",{children:["YOU · ",W?.name||"active wallet"]}),(0,b.jsx)("em",{children:"ACTIVE"}),n&&(0,b.jsx)("em",{children:"HEDGE"})]}),(0,b.jsx)("span",{children:s.map((e,t)=>(0,b.jsxs)("small",{className:String(e.outcome||"").toLowerCase(),children:[(0,b.jsx)("b",{children:String(e.outcome||"").toUpperCase()})," ",tP(Number(e.size||0))," @ ",tR(Number(e.avgPrice||0))]},`${e.asset||e.outcome}-${t}`))})]}),l.map(e=>(0,b.jsxs)("div",{className:"wx-watch-position",title:`@${e.handle} \xb7 ${e.positions.map(e=>`${e.outcome.toUpperCase()} ${tP(e.size)} at ${tR(e.avg_price)} average`).join(" · ")}`,children:[(0,b.jsxs)("div",{children:[(0,b.jsxs)("a",{href:e.profile_url,target:"_blank",rel:"noreferrer",children:["@",e.handle]}),e.hedged&&(0,b.jsx)("em",{children:"HEDGE"})]}),(0,b.jsx)("span",{children:e.positions.map(e=>(0,b.jsxs)("small",{className:e.outcome.toLowerCase(),children:[(0,b.jsx)("b",{children:e.outcome.toUpperCase()})," ",tP(e.size)," @ ",tR(e.avg_price)]},`${e.outcome}-${e.avg_price}`))})]},e.handle)),!s.length&&!l.length&&(0,b.jsx)("small",{className:`wx-watch-empty ${E}`,children:"joining"===I?"checking your active wallet…":"joining"===E?"checking watchlist…":"error"===I&&"error"===E?"positions unavailable":"no_wallet"===I?"no watched position · active wallet not set":"no active-wallet or watched position"})]}),(0,b.jsxs)("div",{className:"wx-volume",children:[(0,b.jsx)("b",{children:tF(e.volume_24h)}),(0,b.jsxs)("small",{children:[tF(e.liquidity)," liq"]})]}),(0,b.jsx)("a",{href:e.url||ec.url,target:"_blank",rel:"noreferrer",title:`Open ${e.label} on Polymarket`,children:"↗"})]},e.market_id)})]})}),ek&&(ek.read.edge||0)>=.04&&(0,b.jsxs)("div",{className:`wx-best-call ${ek.read.strength}`,children:[(0,b.jsx)("span",{children:"WIDEST LIVE GAP"}),(0,b.jsxs)("b",{children:[ek.read.action," ",ek.bucket.label," at ",tA(ek.read.entry)]}),(0,b.jsx)("em",{children:tT(ek.read.edge)}),(0,b.jsx)("small",{children:ep?.source_pending?"Resolution tape is pending: gap remains visible for manual analysis, but paper execution is blocked.":"Model discrepancy only. The paper autopilot requires a stricter 10¢ depth-adjusted gap; no live execution path exists."})]})]}),(0,b.jsxs)("section",{className:"wx-section wx-model-board",children:[(0,b.jsxs)("div",{className:"wx-section-head",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{children:"MODEL DESK"}),(0,b.jsxs)("b",{children:["Station-adjusted daily ",ec.kind]})]}),(0,b.jsx)("small",{children:"live residual bias decays through the forecast horizon"})]}),(0,b.jsx)("div",{className:"wx-model-strip",children:ec.forecast.models.map(e=>(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{children:e.name}),(0,b.jsxs)("b",{children:[e.forecast.toFixed(+(ec.precision<1)),"°",ec.unit]}),(0,b.jsxs)("small",{children:["raw ",e.raw_forecast.toFixed(+(ec.precision<1)),"° · ",e.temporal_resolution_minutes,"m · live bi
4as ",e.live_bias_c>=0?"+":"",e.live_bias_c.toFixed(1),"°C/",e.live_bias_samples," obs",e.archive_calibration_c?` \xb7 archive ${e.archive_calibration_c>=0?"+":""}${e.archive_calibration_c.toFixed(1)}\xb0C`:""]})]},e.id))})]}),(0,b.jsxs)("footer",{className:"wx-audit-strip",children:[(0,b.jsxs)("span",{children:["SOURCE PRECISION ",(0,b.jsxs)("b",{children:[ec.precision<1?"0.1":"1","°",ec.unit]})]}),(0,b.jsxs)("span",{children:["BUCKET COVERAGE ",(0,b.jsx)("b",{children:tE(ec.bucket_coverage,1)})]}),(0,b.jsxs)("span",{children:["GRID ELEVATION FIX ",(0,b.jsxs)("b",{children:[Math.round(ec.station.elevation_m||0),"m station"]})]}),(0,b.jsxs)("span",{children:["STATION CLOCK ",(0,b.jsxs)("b",{children:[ep?.profile.sample_days||0," source days · ",ep?.calibration_as_of||"uncalibrated"]})]}),(0,b.jsxs)("span",{children:["MODEL FETCH ",(0,b.jsx)("b",{children:ec.forecast.model_run?.fetched_at?function(e,t){if(!e)return"no station fix";let a=Math.max(0,Math.floor((t-new Date(e).getTime())/1e3));return a<10?"now":a<60?`${a}s ago`:a<3600?`${Math.floor(a/60)}m ago`:`${Math.floor(a/3600)}h ago`}(ec.forecast.model_run.fetched_at,H):"run time unavailable"})]}),(0,b.jsxs)("span",{children:["CALIBRATION ",(0,b.jsx)("b",{children:r?.model.calibration})]})]})]}):(0,b.jsxs)("div",{className:"wx-empty wx-detail-empty",children:[(0,b.jsx)("b",{children:ec.error||"Forecast feed unavailable"}),(0,b.jsx)("span",{children:"The contract remains on the board while OpenPoly retries the station and model feeds."})]})]}):(0,b.jsxs)("div",{className:"wx-empty wx-detail-empty",children:[(0,b.jsx)("b",{children:m?"Weather board unavailable.":"No weather contracts returned."}),(0,b.jsx)("span",{children:m||"Retry the feed; OpenPoly will keep following the active Polymarket weather page."}),(0,b.jsx)("button",{onClick:()=>Y(!0),children:"Retry weather feed"})]})})]})]})}var tq=e.i(72826);function tV(e){return String(Number.isFinite(e)?Math.max(0,Math.floor(e)):0).replace(/\B(?=(\d{3})+(?!\d))/g,",")}let tG=new Set([0,408,429,502,503,504]),tJ=["body_min","body_max","body_ratio","body_size","min_body","max_body","bodyratio"],tY=["wick","shadow","tail"],tK=["sim_tol","similar","tolerance","_tol","tol_"],tX=["expansion","expand","body_mult","bodymult"],tZ=["streak","consec","consecutive","run_len","runlen"],tQ=["volume","vol_mult","vol_min","vol_ratio"],t0=["lookback","period","len_","_len","length","count","num_","_num","n_bars","bars_"];function t1(e,t){for(let a of t)if(e.includes(a))return!0;return!1}function t2(e,t){let a=new Set,s=e.match(/_(\d+)$/);if(s){let e=parseInt(s[1],10);Number.isFinite(e)&&e>0&&e<20&&a.add(e)}let r=e.match(/(?:^|_)(?:c|bar|candle)(\d+)(?:_|$)/i);if(r){let e=r[1];if(e.length<=6)if(1===e.length){let t=parseInt(e,10);t>0&&a.add(t)}else for(let t of e){let e=parseInt(t,10);Number.isFinite(e)&&e>0&&e<10&&a.add(e)}}if(t){let e,s=/(?:bars?|candles?|c)?\s*#?\s*(\d+)\s*(?:-|–|—|to|through|thru)\s*(?:bars?|candles?|c)?\s*#?\s*(\d+)/gi;for(;null!=(e=s.exec(t));){let t=parseInt(e[1],10),s=parseInt(e[2],10);if(Number.isFinite(t)&&Number.isFinite(s)&&t>0&&s>0&&t<20&&s<20){let e=Math.min(t,s),r=Math.max(t,s);for(let t=e;t<=r;t+=1)a.add(t)}}let r=/(?:bars?|candles?|c)\s*#?\s*(\d+)/gi;for(;null!=(e=r.exec(t));){let t=parseInt(e[1],10);Number.isFinite(t)&&t>0&&t<20&&a.add(t)}let n=/(\d+)(?:st|nd|rd|th)\b/gi;for(;null!=(e=n.exec(t));){let t=parseInt(e[1],10);Number.isFinite(t)&&t>0&&t<20&&a.add(t)}}return Array.from(a).sort((e,t)=>e-t)}function t5(e){if(0===e.length)return"all";if(1===e.length)return`c${e[0]}`;let t=[...e].sort((e,t)=>e-t),a=!0;for(let e=1;e<t.length;e+=1)if(t[e]!==t[e-1]+1){a=!1;break}return a?`c${t[0]}–c${t[t.length-1]}`:t.map(e=>`c${e}`).join(",")}function t4(e,t,a){let s=e.toLowerCase(),r=(t.label||"").toLowerCase(),n=`${s} ${r}`;if("bool"===t.type)return{category:"bool",affects:[],affectsLabel:""};let l=Array.isArray(t.affects)&&t.affects.length>0?t.affects.filter(e=>Number.isFinite(e)&&e>0&&e<20):null;if(t1(n,tQ)){let a=l??t2(e,t.label);return{category:"volume",affects:a,affectsLabel:t5(a)}}let i=[];for(let[e,t]of Object.entries(a)){let a=Array.isArray(t?.affects)&&t.affects.length>0?t.affects.filter(e=>Number.isFinite(e)&&e>0&&e<20):null;if(a&&a.length>0)for(let e of a)i.push(e);else for(let a of t2(e,t?.label))i.push(a)}let o=i.length>0?Math.max(...i):0,c=l??t2(e,t.label);if(t1(n,tY)){let e=c.length>0?c:[1];return{category:"wick",affects:e,affectsLabel:t5(e)}}if(t1(n,tJ)||/\bbody\b/.test(n)){let e=c.length>0?c:[1];return{category:"body",affects:e,affectsLabel:t5(e)}}if(t1(n,tX)){let e=c.length>0?c:[Math.max(o,4)];return{category:"expansion",affects:e,affectsLabel:t5(e)}}if(t1(n,tK)){let e=c;if(0===e.length){let t=Math.max(o>0?o-1:0,3);e=[];for(let a=1;a<=t;
4a+=1)e.push(a)}return{category:"similarity",affects:e,affectsLabel:t5(e)}}return t1(n,tZ)?{category:"streak",affects:c,affectsLabel:c.length?t5(c):"all"}:t1(n,t0)||"int"===t.type?{category:"count",affects:c,affectsLabel:c.length?t5(c):"all"}:{category:"unknown",affects:c,affectsLabel:c.length?t5(c):""}}let t3="#9499a2",t6="#f6c849",t8="#3a3f49";function t9(e,t,a){return Math.min(a,Math.max(t,e))}function t7(e,t){if(!e||t<1)return null;let a=e.match(/\/\/\s*@candle_directions\s*(.+?)\s*$/im);if(!a)return null;let s=a[1].trim().toLowerCase();if("all_down"===s||"all-down"===s||"alldown"===s)return Array(t).fill("down");if("all_up"===s||"all-up"===s||"allup"===s)return Array(t).fill("up");if("reversal_to_up"===s||"bull_reversal"===s||"bullish_reversal"===s)return[...Array(Math.max(0,t-1)).fill("down"),"up"];if("reversal_to_down"===s||"bear_reversal"===s||"bearish_reversal"===s)return[...Array(Math.max(0,t-1)).fill("up"),"down"];let r=s.replace(/^\[|\]$/g,"").trim();if(!r)return null;let n=r.split(/[,\s]+/).filter(Boolean);if(0===n.length)return null;let l=[];for(let e of n)if("up"===e||"u"===e||"bull"===e||"bullish"===e||"green"===e)l.push("up");else if("down"===e||"d"===e||"bear"===e||"bearish"===e||"red"===e)l.push("down");else{if("either"!==e&&"any"!==e&&"*"!==e&&"-"!==e)return null;l.push("either")}for(;l.length<t;)l.push("either");return l.slice(0,t)}function ae(e){if(!e)return null;let t=Number(e.length);if(!Number.isFinite(t)||t<1)return null;let a=e.candles;if(!a||"object"!=typeof a)return null;let s=[];for(let e=1;e<=t;e+=1){let t=a[`c${e}`],r=t?.direction;"bullish"===r?s.push("up"):"bearish"===r?s.push("down"):s.push("either")}return s}let at=/\b(streak|stair|consecutive|continuation|in.a.row|in.row|sequence|run|trend|cascade)\b/i,aa=/\b(reversal|reverse|engulfing|engulf|piercing|morning\s+star|evening\s+star|harami|tweezer|abandoned\s+baby)\b/i;function as(e,t){let a=`${e||""} ${t||""}`;return at.test(a)?"continuation":aa.test(a)?"reversal":"unknown"}function ar(e,t,a,s,r,n,l,i,o,c){let d;if(0===Object.keys(e).length&&!o)return{candles:[],count:0,minLow:0,maxHigh:1};let u=0;for(let[t,a]of Object.entries(e))for(let e of(Array.isArray(a?.affects)&&a.affects.length>0?a.affects.filter(e=>Number.isFinite(e)&&e>0&&e<20):null)??t2(t,a?.label))e>u&&(u=e);let h=0;for(let[a,s]of Object.entries(e)){let r=t[a];if("streak"===t4(a,s,e).category){let e=Math.round(Number(r));Number.isFinite(e)&&e>h&&(h=e)}}if(h>u&&(u=h),o&&Number.isFinite(o.length)){let e=Math.round(o.length);e>=1&&(u=e)}u<1&&(u=4),u=Math.min(u,8);let p=new Set;if(s&&e[s]){let t=t4(s,e[s],e);if(t.affects.length>0)for(let e of t.affects)p.add(e);else for(let e=1;e<=u;e+=1)p.add(e)}if(r&&r.length>0)for(let e of r)Number.isFinite(e)&&e>=1&&e<=u&&p.add(e);let m=function(e,t,a,s,r,n){let l="bullish"===t?"up":"bearish"===t?"down":"up",i="neutral"===t,o=ae(n);if(o)return o.slice(0,e).concat(Array(Math.max(0,e-o.length)).fill("either")).map(e=>"either"===e?i?"either":l:e);let c=t7(r,e);if(c)return c.map(e=>"either"===e?i?"either":l:e);let d="reversal"===as(a,s),u="up"===l?"down":"up",h=[];for(let t=1;t<=e;t+=1)d&&e>=2&&t<e?h.push(u):h.push(l);return h}(u,a,n,l,i,o),x=Array(u).fill(.45),g=Array(u).fill(.15),f=Array(u).fill(.15),b=Array(u).fill(null);if(o&&c){let e=(e,t,a)=>{if(null==e)return a;
4if("number"==typeof e)return e;if(Array.isArray(e)&&2===e.length)return(e[0]+e[1])/2;if("string"==typeof e){let a=t[e];if(a)return(a[0]+a[1])/2}return a};for(let t=1;t<=u;t+=1){let a=o.candles?.[`c${t}`];if(!a)continue;let s=a.shape?c.shapes[a.shape]:void 0,r=a.body??s?.body??null,n=a.upper_wick??s?.upper_wick??null,l=a.lower_wick??s?.lower_wick??null,i=a.close_position??s?.close_position??null;x[t-1]=t9(e(r,c.body.all,.45),.05,.95),g[t-1]=t9(e(n,c.wick.all,.15),0,.9),f[t-1]=t9(e(l,c.wick.all,.15),0,.9),null!=i&&(b[t-1]=t9(e(i,c.close_position.all,.5),.02,.98))}}for(let e=0;e<u;e+=1){let t=b[e];if(null==t)continue;let a=m[e],s=x[e];"up"===a||"either"===a?(s>t&&(s=Math.max(.05,t-.02)),f[e]=t9(t-s,0,.95),g[e]=t9(1-t,0,.95)):(t+s>1&&(s=Math.max(.05,1-t-.02)),f[e]=t9(t,0,.95),g[e]=t9(1-t-s,0,.95)),x[e]=s}let _=null,v=null,y=null,j=null;for(let[a,s]of Object.entries(e)){let r=t[a],n=t4(a,s,e);if("bool"===n.category||"volume"===n.category)continue;let l=Number(r);if("body"===n.category)for(let e of n.affects)e>=1&&e<=u&&(x[e-1]=t9(l,.05,.95));else if("wick"===n.category)for(let e of n.affects)e>=1&&e<=u&&(g[e-1]=t9(l,0,.9),f[e-1]=t9(l,0,.9));else if("expansion"===n.category){for(let e of(_=t9(l,.2,5),n.affects))e>=1&&e<=u&&(v=e);null==v&&(v=u)}else"similarity"===n.category&&(y=t9(l,0,1),j=n.affects.length>0?n.affects.filter(e=>e>=1&&e<=u):Array.from({length:u},(e,t)=>t+1))}if(null!=y&&j&&j.length>0){let e=j.reduce((e,t)=>e+x[t-1],0)/j.length;for(let t=0;t<j.length;t+=1){let a=j[t],s=(t%2==0?1:-1)*y*.2*(t%3+1)/3;x[a-1]=t9(e+s,.08,.95)}}if(null!=_&&v){let e=v-1;x[e]=t9(x[e]*_,.08,1.6)}let w=Array.from({length:u},()=>null);if(o?.relations&&Array.isArray(o.relations)){let e=e=>{let t=/^c(\d+)$/i.exec(e);return t?parseInt(t[1],10):-1};for(let t of o.relations){let a=e(t.by),s=e(t.of);if(a<1||a>u||s<1||s>u)continue;let r=w[a-1]??{};"engulfs"===t.kind?r.engulfsIdx=s:"inside"===t.kind?r.insideIdx=s:"outside"===t.kind?r.outsideIdx=s:"gap_up"===t.kind?r.gap="up":"gap_down"===t.kind&&(r.gap="down"),w[a-1]=r}}for(let e=0;e<u;e+=1){let t=w[e];if(t){if(null!=t.engulfsIdx){let a=x[t.engulfsIdx-1];x[e]=t9(Math.max(x[e],1.7*a),.1,1.5)}else if(null!=t.insideIdx){let a=x[t.insideIdx-1];x[e]=Math.min(x[e],.55*a),g[e]=Math.min(g[e],.08),f[e]=Math.min(f[e],.08)}else if(null!=t.outsideIdx){let a=x[t.outsideIdx-1];x[e]=t9(Math.max(x[e],1.5*a),.1,1.5),g[e]=Math.max(g[e],.25),f[e]=Math.max(f[e],.25)}}}let N=ae(o)??t7(i,u);if(N&&N.length>=2){let e=N[N.length-1],t=N.slice(0,-1).filter(e=>"either"!==e);d=t.length>0&&t.every(t=>t!==e)}else d="reversal"===as(n,l);let k=[],S=100;for(let e=1;e<=u;e+=1){let t,a,s=m[e-1],r=10*x[e-1],n=10*g[e-1]*.55,l=10*f[e-1]*.55,i=w[e-1];if(i?.gap&&k.length>0){let e=k[k.length-1],t=Math.max(e.high-e.low,4);S="up"===i.gap?e.high+.35*t:e.low-.35*t}let o="up"===s||"either"===s;if(d&&e===u&&u>=2){let e=Math.abs(100-(t=S))+.5*r;a=o?t+e:t-e}else if(i?.engulfsIdx!=null&&k.length>=i.engulfsIdx){let e=k[i.engulfsIdx-1],s=Math.max(e.open,e.close),n=Math.min(e.open,e.close),l=.15*r;o?(t=n-l,a=s+(r-(s-n))+l):(t=s+l,a=n-(r-(s-n))-l)}else t=S,a=o?t+r:t-r;let c=Math.max(t,a)+n,b=Math.min(t,a)-l;S=a;let _=0===h||e<=h;k.push({open:t,high:c,low:b,close:a,direction:s,highlight:p.has(e),active:_})}let $=1/0,C=-1/0;for(let e of k)e.low<$&&($=e.low),e.high>C&&(C=e.high);$===1/0&&($=0,C=1);let M=(C-$)*.05;return{candles:k,count:u,minLow:$-M,maxHigh:C+M}}function an({pineParams:e,values:t,direction:a,patternName:s,patternDescription:r,patternPineSource:n,patternSpec:l,cpsVocabulary:i,focusedKnob:o,focusedCandles:c,size:d="md"}){let{candles:u,count:h,minLow:p,maxHigh:m}=ar(e,t,a,o,c,s,r,n,l,i);if(0===h)return null;let x="sm"===d?110:240,g=44+60*h+(h-1)*18,f=x-44-16,_=Math.max(m-p,1e-9),v=e=>22+(m-e)/_*f;return(0,b.jsx)("svg",{width:g,height:x,viewBox:`0 0 ${g} ${x}`,"aria-hidden":!0,style:{display:"block"},children:u.map((e,t)=>{let a=22+78*t,s=a+30,r=v(e.high),n=v(e.low),l=v(e.open),i=v(e.close),o=Math.min(l,i),c=Math.max(3,Math.max(l,i)-o),d=e.active?"either"===e.direction?e.highlight?t3:"#9499a244":"up"===e.direction?e.highlight?"#15b097":"#15b09744":e.highlight?"#e84957":"#e8495744":t8,u=e.active?d:t8;return(0,b.jsxs)("g",{children:[e.highlight&&(0,b.jsx)("rect",{x:a-5,y:r-5,width:70,height:n-r+10,rx:6,fill:"none",stroke:t6,strokeWidth:2,opacity:.85}),(0,b.jsx)("line",{x1:s,x2:s,y1:r,y2:n,stroke:u,strokeWidth:2.5}),(0,b.jsx)("rect",{x:a+6,y:o,width:48,height:c,fill:d,opacity:e.active?1:.5,rx:1.5}),(0,b.jsxs)("text",{x:s,y:x-4,textAnchor:"middle",fontSize:"13",fill:e.highlight?t6:"#9499a2",fontFamily:"monospace",fontWeight:e.highlight?600:4
400,children:["c",t+1]}),"either"===e.direction&&e.active&&(0,b.jsx)("text",{x:s,y:r-6,textAnchor:"middle",fontSize:"11",fill:t3,fontFamily:"monospace",fontWeight:600,children:"↕"})]},t)})})}let al=null;function ai(){return al||(al=(0,er.authGetJson)("/api/cps/vocabulary").then(e=>e.data).catch(e=>{throw al=null,e})),al}function ao(e,t,a){let s=a.atoms.length;if(0===e&&t===s-1)return null;if(e===t)return a.atoms[e];if(0===e)return`${a.atoms[t]}_or_smaller`;if(t===s-1)return`${a.atoms[e]}_or_larger`;if(t-e==1){for(let s of[`${a.atoms[e]}_or_${a.atoms[t]}`,`${a.atoms[t]}_or_${a.atoms[e]}`])if(a.all[s])return s}return[a.all[a.atoms[e]]?.[0]??0,a.all[a.atoms[t]]?.[1]??1]}function ac(e,t){let a,s,r=t.atoms.length;if(null==e)return[0,r-1];if("string"==typeof e){let n=t.atoms.indexOf(e);if(n>=0)return[n,n];let l=t.all[e];if(!l)return[0,r-1];[a,s]=l}else{if(!Array.isArray(e)||2!==e.length)return[0,r-1];[a,s]=e}let n=0,l=r-1,i=1/0,o=1/0;for(let e=0;e<r;e+=1){let r=t.all[t.atoms[e]];if(!r)continue;let c=Math.abs(r[0]-a),d=Math.abs(r[1]-s);c<i&&(i=c,n=e),d<o&&(o=d,l=e)}return[Math.min(n,l),Math.max(n,l)]}function ad({label:e,axis:t,value:a,onChange:s,pending:r,disabled:n}){let l,i=t.atoms,o=i.length,[c,d]=(0,_.useState)(()=>ac(a,t)[0]),[u,h]=(0,_.useState)(()=>ac(a,t)[1]),p=(0,_.useRef)(a);(0,_.useEffect)(()=>{let[e,s]=ac(a,t),[r,n]=ac(p.current,t);(e!==r||s!==n)&&(d(e),h(s),p.current=a)},[a,t]);let m=(l=t.atoms.length,0===c&&u===l-1?"any":c===u?t.atoms[c]:0===c?`${t.atoms[u]} or smaller`:u===l-1?`${t.atoms[c]} or larger`:`${t.atoms[c]} to ${t.atoms[u]}`),x=0===c&&u===o-1,g=c/Math.max(1,o-1)*100,f=u/Math.max(1,o-1)*100;return(0,b.jsxs)("div",{className:`cps-band-slider${r?" saving":""}${x?" unset":""}`,children:[(0,b.jsxs)("div",{className:"cps-band-slider-head",children:[(0,b.jsx)("span",{className:"cps-band-slider-label",children:e}),(0,b.jsx)("span",{className:"cps-band-slider-value",children:m})]}),(0,b.jsxs)("div",{className:"cps-band-range-track-wrap",children:[(0,b.jsx)("div",{className:"cps-band-range-track-base"}),(0,b.jsx)("div",{className:"cps-band-range-track-fill",style:{left:`${g}%`,right:`${100-f}%`}}),(0,b.jsx)("input",{type:"range",min:0,max:o-1,step:1,value:c,disabled:n,onChange:e=>(e=>{let a=Math.min(Math.max(0,e),u);if(a===c)return;d(a);let r=ao(a,u,t);p.current=r,s(r)})(parseInt(e.target.value,10)),className:"cps-band-range-thumb cps-band-range-thumb-lo",style:{zIndex:c===u&&0===c?1:3},"aria-label":`${e} minimum`}),(0,b.jsx)("input",{type:"range",min:0,max:o-1,step:1,value:u,disabled:n,onChange:e=>(e=>{let a=Math.min(Math.max(c,e),o-1);if(a===u)return;h(a);let r=ao(c,a,t);p.current=r,s(r)})(parseInt(e.target.value,10)),className:"cps-band-range-thumb cps-band-range-thumb-hi",style:{zIndex:c===u&&0===c?3:2},"aria-label":`${e} maximum`})]}),(0,b.jsx)("div",{className:"cps-band-slider-stops",children:i.map((e,a)=>(0,b.jsx)("span",{className:`cps-band-slider-stop${a>=c&&a<=u?" active":""}`,title:e,onClick:()=>!n&&s(ao(a,a,t)),children:e},e))})]})}let au=[{value:"default",label:"default",tooltip:"Use the pattern's own direction"},{value:"follow_confirmation",label:"follow trigger",tooltip:"Same direction as the trigger candle"},{value:"opposite_confirmation",label:"opposite trigger",tooltip:"Opposite direction of the trigger candle"},{value:"fixed_up",label:"always up",tooltip:"Always trade UP regardless of pattern"},{value:"fixed_down",label:"always down",tooltip:"Always trade DOWN regardless of pattern"},{value:"follow_streak",label:"follow streak",tooltip:"Follow the direction of the prior streak"}];function ah({patternKey:e,patternSpec:t,onPatternUpdated:a,onCandleHover:s,onSpecOptimistic:r,directionRule:n,asset:l,tf:i,onDirectionRuleSaved:o}){let[c,d]=(0,_.useState)(null),[u,h]=(0,_.useState)(null),[p,m]=(0,_.useState)({}),[x,g]=(0,_.useState)(new Set),[f,v]=(0,_.useState)(null),y=(0,_.useRef)(null);(0,_.useEffect)(()=>{let e=!0;return ai().then(t=>{e&&d(t)}).catch(t=>{e&&h(t instanceof Error?t.message:String(t))}),()=>{e=!1}},[]);let j=(0,_.useCallback)(async()=>{m(t=>{if(0===Object.keys(t).length)return t;let s={},r=[];for(let[e,a]of Object.entries(t)){if(s[a.candle]||(s[a.candle]={}
4),"base"===a.slot)s[a.candle][a.field]=a.value;else{let e=a.slot,t=s[a.candle][e]||{};t[a.field]=a.value,s[a.candle][e]=t}r.push(e)}return g(new Set(r)),v(null),(async()=>{try{let t=await (0,er.authFetch)(`/api/patterns/${e}/spec`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({spec_patch:{candles:s},intent:"positive"})}),r=await t.json().catch(()=>({}));if(t.ok&&r?.ok){let e=r?.data?.pattern;e&&a&&a(e)}else{let e=r?.message||r?.error||`HTTP ${t.status}`;v(e)}}catch(e){v(e instanceof Error?e.message:String(e))}finally{g(new Set)}})(),{}})},[e,a]),w=(0,_.useCallback)((e,a,s,n)=>{let l=`${e}.${a}.${s}`;m(i=>{let o={...i,[l]:{candle:e,slot:a,field:s,value:n}};if(r){let e={...t.candles??{}};for(let t of Object.values(o)){let a=e[t.candle]??{};if("base"===t.slot){let{shape:s,...r}=a;e[t.candle]={...r,[t.field]:t.value}}else{let s=t.slot,{shape:r,...n}=a[s]||{};e[t.candle]={...a,[s]:{...n,[t.field]:t.value}}}}r({...t,candles:e})}return o}),y.current&&clearTimeout(y.current),y.current=setTimeout(()=>{j()},300)},[j,r,t]),N=["body","upper_wick","lower_wick","close_position"],k=(0,_.useCallback)((s,n)=>{let l,i;g(e=>new Set([...e,`${s}.__split`])),v(null);let o=(t.candles??{})[s]??{},c=o.if_bull??{},d=o.if_bear??{};if(n){let e={},t={};for(let a of N){let s=o[a];null!=s&&(e[a]=s,t[a]=null)}l={...t,if_bull:{...e},if_bear:{...e}},i={...o,...t,if_bull:{...e},if_bear:{...e}}}else{let e=Object.keys(c).length>0?c:d,t={};for(let a of N){let s=e[a];null!=s&&(t[a]=s)}l={...t,if_bull:null,if_bear:null},i={...o,...t,if_bull:null,if_bear:null}}if(r){let e={...t.candles??{}};e[s]=i,r({...t,candles:e})}(async()=>{try{let t=await (0,er.authFetch)(`/api/patterns/${e}/spec`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({spec_patch:{candles:{[s]:l}},intent:"positive"})}),r=await t.json().catch(()=>({}));if(t.ok&&r?.ok){let e=r?.data?.pattern;e&&a&&a(e)}else v(r?.message||r?.error||`HTTP ${t.status}`)}catch(e){v(e instanceof Error?e.message:String(e))}finally{g(e=>{let t=new Set(e);return t.delete(`${s}.__split`),t})}})()},[e,a,r,t]),[S,$]=(0,_.useState)({});(0,_.useEffect)(()=>()=>{y.current&&clearTimeout(y.current)},[]);let C=(0,_.useMemo)(()=>{let e=t.length,a=[];for(let t=1;t<=e;t+=1)a.push(`c${t}`);return a},[t.length]);if(u)return(0,b.jsxs)("div",{className:"cps-band-panel-error",children:["Vocabulary load failed: ",u]});if(!c)return(0,b.jsx)("div",{className:"cps-band-panel-loading",children:"Loading band vocabulary…"});let M=[{field:"body",label:"Body",axis:c.body},{field:"upper_wick",label:"Upper wick",axis:c.wick},{field:"lower_wick",label:"Lower wick",axis:c.wick},{field:"close_position",label:"Close lands",axis:c.close_position}],E=(n||"default").toLowerCase(),A=x.has("__entry_rule");return(0,b.jsxs)("div",{className:"cps-band-panel",children:[(0,b.jsxs)("div",{className:"cps-band-panel-entry-rule",children:[(0,b.jsx)("span",{className:"cps-band-panel-entry-rule-label",children:"Entry rule:"}),(0,b.jsx)("div",{className:`cps-band-panel-entry-rule-buttons${A?" saving":""}`,children:au.map(t=>(0,b.jsx)("button",{type:"button",className:`cps-entry-rule-btn${E===t.value?" active":""}`,onClick:()=>{var a;(a=t.value)!==(n||"default").toLowerCase()&&(g(e=>new Set([...e,"__entry_rule"])),v(null),(async()=>{try{let t=await (0,er.authFetch)(`/api/patterns/${e}/strategy`),s=await t.json().catch(()=>({})),r={...s?.data?.params||{},direction_rule_override:"default"===a?"":a},n=await (0,er.authFetch)(`/api/patterns/${e}/strategy`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({params:r,asset:l,tf:i})}),c=await n.json().catch(()=>({}));if(!n.ok||!c?.ok)return void v(c?.message||c?.error||`HTTP ${n.status}`);o&&o("default"===a?"":a)}catch(e){v(e instanceof Error?e.message:String(e))}finally{g(e=>{let t=new Set(e);return t.delete("__entry_rule"),t})}})())},disabled:A,title:t.tooltip,children:t.label},t.value))})]}),f&&(0,b.jsxs)("div",{className:"cps-band-panel-error",children:["Save failed: ",f]}),(0,b.jsx)("div",{className:"cps-band-panel-rows",children:C.map((e,a)=>{let r=a+1,n=t.candles?.[e]??{},l="bullish"===n.direction?"bull":"bearish"===n.direction?"bear":"any",i=n.shape?` \xb7 ${n.shape}`:"",o=()=>s?.(r),c=()=>s?.(null),d=null!=n.if_bull,u=null!=n.if_bear,h=d||u,m=x.has(`${e}.__split`),g=S[e]||(h?"bull":"shared"),f="shared"===g?"base":"bull"===g?"if_bull":"if_bear",_="base"===f?n:"if_bull"===f?n.if_bull??{}:n.if_bear??{};return(0,b.jsxs)("div",{className:"cps-band-panel-row",onMouseEnter:o,onMouseLeave:c,onFocus:o,onBlur:c,children:[(0,b.jsxs)("div",{className:"cps-band-panel-row-head",children:[(0,b.jsx)("strong",{children:e}),(0,b.jsxs)("span",{className:"muted",children:[l,i]}),(0,b.jsx)("span",{className:"cps-band-panel-row-spacer"}),(0,b.jsxs)("div",{className:`cps-split-toggle${m?" saving":""}`,children:[(0,b.jsx)("button",{type:"button",className:`cps-split-btn${!h?" active":""}`,onClick:()=>h&&k(e,!1),disabled:m,title:"Single set of sliders applies to both directions",children:"shared"}),(0,b.jsx)("button",{type:"button",className:`cps-split-btn${h?" active":""}`,onClick:()=>!h&&k(e,!0),disabled:m,title:"Separate slider sets for bull vs bear matches",children:"split"})]})]}),h&&(0,b.jsxs)("div",{className:"cps-tab-strip",children:[(0,b.jsx)("button",{type:"button",className:`cps-tab-btn cps-tab-bull${"bull"===g?" active":""}`,onClick:()=>$(t=>({...t,[e]:"bull"})),children:"when bull"}),(0,b.jsx)("button",{type:"button",className:`cps-tab-btn cps-tab-bear${"bear"===g?" active":""}`,onClick:()=>$(t=>({...t,[e]:"bear"})),children:"when bear"})]}),(0,b.jsx)("div",{className:"cps-band-panel-row-sliders",children:M.map(({field:t,label:a,axis:s})=>{let r=`${e}.${f}.${t}`,n=p[r]?.value,l=_[t],i=r in p?n:l;return(0,b.jsx)(ad,{label:a,axis:s,value:i,pending:x.has(r)||null!=p[r],onChange:a=>w(e,f,String(t),a)},t)})})]},e)})})]})}let ap=/^\s*(abs\(c\d+\.\w+\s*-\s*[\d.]+\)\s*\+\s*){3,}abs\(c\d+\.\w+\s*-\s*[\d.]+\)\s*<=\s*[\d.]+\s*$/;function am({patternKey:e,patternSpec:t,onPatternUpdated:a,onSpecOptimistic:s}){let[r,n]=(0,_.useState)(null),[l,i]=(0,_.useState)(null),o=(0,_.useMemo)(()=>{let e=[];for(let[a,s]of Object.entries(t.candles||{})){let t=s?.shape;"string"==typeof t&&t&&e.push({candleKey:a,shape:t})}return e},[t.candles]),c=(0,_.useMemo)(()=>Array.isArray(t.relations)?t.relations:[],[t.relations]),d=(0,_.useMemo)(()=>{let e=t.cross_constraints||[],a=[];return e.forEach((e,t)=>{"string"==typeof e&&e.trim()&&!ap.test(e)&&a.push({expr:e,realIdx:t})}),a},[t.cross_constraints]),u=(0,_.useMemo)(()=>Array.isArray(t.streaks)?t.streaks:[],[t.streaks]);if(!(o.length>0||c.length>0||d.length>0||u.length>0))return(0,b.jsx)("div",{className:"pattern-lab-refine-notes",style:{marginTop:12,fontSize:11,color:"var(--fg-muted)",fontStyle:"italic"},children:"Spec inspector: no shapes / relations / cross-constraints / streaks on this pattern. These show up here when the agent (or auto-tune) adds them."});let h=async(t,r,l)=>{n(t),i(null),s&&s(l);try{let t=await (0,er.authFetch)(`/api/patterns/${e}/spec`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({spec_patch:r,intent:"positive"})}),s=await t.json().catch(()=>({}));if(t.ok&&s?.ok){let e=s?.data?.pattern;e&&a&&a(e)}else i(s?.message||s?.error||`HTTP ${t.status}`)}catch(e){i(e?.message||String(e))}finally{n(null)}},p={marginTop:12},m={fontSize:10,fontWeight:600,color:"var(--fg-muted)",textTransform:"uppercase",letterSpacing:.5,marginBottom:4},x={display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,padding:"4px 8px",background:"rgba(255,255,255,0.02)",border:"1px solid var(--border-subtle)",borderRadius:4,marginBottom:4,fontSize:11,fontFamily:"var(--font-mono)"},g=(e,t)=>(0,b.jsx)("button",{type:"button",onClick:t,disabled:r===e,title:"Remove this constraint",style:{background:"transparent",border:"1px solid var(--border-subtle)",color:"var(--danger)",cursor:"pointer",padding:"0 6px",fontSize:13,borderRadius:3,opacity:r===e?.5:1},children:"×"});return(0,b.jsxs)("div",{className:"pattern-lab-refine-preview",style:{marginTop:12},children:[(0,b.jsxs)("div",{className:"pattern-lab-refine-preview-head",children:[(0,b.jsx)("strong",{children:"Spec inspector"}),(0,b.jsx)("span",{style:{color:"var(--fg-muted)"},children:"constraints not covered by sliders / Playground — remove with ×"})]}),l?(0,b.jsx)("div",{className:"pattern-lab-params-error",children:l}):null,o.length>0?(0,b.jsxs)("div",{style:p,children:[(0,b.jsxs)("div",{style:m,children:["Per-candle shapes (",o.length,")"]}),o.map(({candleKey:e,shape:a})=>(0,b.jsxs)("div",{style:x,children:[(0,b.jsxs)("span",{children:[(0,b.jsx)("strong",{children:e}),".shape ="," ",(0,b.jsx)("span",{style:{color:"#f6c849"},children:a})]}),g(`shape:${e}`,()=>{let a,s;return a={...t},void((s={...t.candles||{}})[e]={...s[e]||{},shape:null},a.candles=s,h(`shape:${e}`,{candles:{[e]:{shape:null}}},a))})]},`shape-${e}`))]}):null,c.length>0?(0,b.jsxs)("div",{style:p,children:[(0,b.jsxs)("div",{style:m,children:["Relations (",c.length,")"]}),c.map((e,a)=>(0,b.jsxs)("div",{style:x,children:[(0,b.jsxs)("span",{children:[(0,b.jsx)("strong",{children:e?.by??"?"})," ",(0,b.jsx)("span",{style:{color:"#f6c849"},children:e?.kind??"?"})," ",(0,b.jsx)("strong",{children:e?.of??"?"})]}),g(`rel:${a}`,()=>{let e,s;return e=c.filter((e,t)=>
4t!==a),s={...t,relations:e},void h(`rel:${a}`,{relations:e},s)})]},`rel-${a}`))]}):null,d.length>0?(0,b.jsxs)("div",{style:p,children:[(0,b.jsxs)("div",{style:m,children:["Cross-constraints (",d.length,")"]}),d.map(({expr:e,realIdx:a})=>(0,b.jsxs)("div",{style:x,children:[(0,b.jsx)("code",{style:{wordBreak:"break-word"},children:e}),g(`cx:${a}`,()=>{let e,s;return e=(t.cross_constraints||[]).filter((e,t)=>t!==a),s={...t,cross_constraints:e},void h(`cx:${a}`,{cross_constraints:e},s)})]},`cx-${a}`))]}):null,u.length>0?(0,b.jsxs)("div",{style:p,children:[(0,b.jsxs)("div",{style:m,children:["Streaks (",u.length,")"]}),u.map((e,a)=>{let s=[`${e?.from??"?"} → ${e?.to??"?"}`,e?.direction?`dir=${e.direction}`:null,e?.same_direction?"same_direction":null,e?.monotonic?`monotonic=${e.monotonic}`:null].filter(Boolean).join(" · ");return(0,b.jsxs)("div",{style:x,children:[(0,b.jsx)("span",{children:s}),g(`streak:${a}`,()=>{let e,s;return e=u.filter((e,t)=>t!==a),s={...t,streaks:e},void h(`streak:${a}`,{streaks:e},s)})]},`streak-${a}`)})]}):null]})}let ax={tight:.3,default:.6,loose:1.2},ag=["body","upper_wick","lower_wick","close_position"];function af(e){return e.toFixed(4).replace(/\.?0+$/,"")||"0"}let ab=/^\s*(abs\(c\d+\.\w+\s*-\s*[\d.]+\)\s*\+\s*){3,}abs\(c\d+\.\w+\s*-\s*[\d.]+\)\s*<=\s*[\d.]+\s*$/,a_="#f6c849",av={O:"#7fb6ff",H:"#15b097",L:"#e84957",C:"#f6c849"};function ay(e,t,a,s){let r={O:"Open",H:"High",L:"Low",C:"Close"};return["O","H","L","C"].map((n,l)=>(0,b.jsxs)("span",{children:[l>0&&" / ",(0,b.jsx)("button",{type:"button",onClick:()=>{null==a&&t(1),e(n)},style:{display:"inline-block",padding:"0 6px",margin:"0 1px",border:`1px solid ${s===n?av[n]:"var(--border-subtle)"}`,background:s===n?`${av[n]}1f`:"transparent",color:s===n?av[n]:"var(--text-primary)",borderRadius:4,cursor:"pointer",fontWeight:600,fontSize:"inherit",fontFamily:"inherit"},title:`Pick ${r[n]} to drag`,children:r[n]})]},n))}function aj({patternKey:e,patternSpec:t,cpsVocabulary:a,onPatternUpdated:s,onSpecOptimistic:r}){let n=(0,_.useMemo)(()=>ar({},{},t.direction||"neutral",null,null,void 0,void 0,void 0,t,a),[t,a]),[l,i]=(0,_.useState)(n.candles),o=(0,_.useRef)(null);(0,_.useEffect)(()=>{o.current||(i(n.candles),$.current=n.candles,M(!1))},[e]);let[c,d]=(0,_.useState)(null),[u,h]=(0,_.useState)(null),{minLow:p,maxHigh:m,count:x}=(0,_.useMemo)(()=>{let e=1/0,t=-1/0;for(let a of l)a.low<e&&(e=a.low),a.high>t&&(t=a.high);isFinite(e)||(e=0,t=1);let a=(t-e)*.05;return{minLow:e-a,maxHigh:t+a,count:l.length}},[l]),g=44+60*x+(x-1)*18,f=Math.max(m-p,1e-9),v=(0,_.useCallback)(e=>22+(m-e)/f*220,[m,f,220]);(0,_.useCallback)(e=>m-(e-22)/220*f,[m,f,220]);let[y,j]=(0,_.useState)(!1),[w,N]=(0,_.useState)(null),[k,S]=(0,_.useState)(()=>{let e=window.localStorage.getItem("openpoly.playgroundSensitivity");return"tight"===e||"default"===e||"loose"===e?e:"default"});(0,_.useEffect)(()=>{window.localStorage.setItem("openpoly.playgroundSensitivity",k)},[k]);let $=(0,_.useRef)(n.candles),[C,M]=(0,_.useState)(!1),E=(0,_.useMemo)(()=>(function(e,t=[],a={}){let s=a.minGapPct??.5,r=["open","high","low","close"],n=[],l=new Set(t.map(e=>e.replace(/\s+/g,""))),i=(t,a,r,i)=>{let o=e[t][r],c=e[a][i];if(!isFinite(o)||!isFinite(c)||o<=0||c<=0)return;let d=(o+c)/2;if(d<=0)return;let u=(c-o)/d*100;if(Math.abs(u)<s)return;let h=c>o?">":"<",p=`c${a+1}.${i} ${h} c${t+1}.${r}`;l.has(p.replace(/\s+/g,""))||n.push({label:`c${a+1}.${i} ${h} c${t+1}.${r}`,expression:p,ratio:u})};for(let t=0;t<e.length;t+=1)for(let a=0;a<e.length;a+=1)if(t!==a){for(let e of r)i(t,a,e,e);a>t&&(i(t,a,"high","close"),i(t,a,"low","close"))}let o=new Map;for(let e of n){let t=function(e){let t=/^c(\d+)\.(\w+)\s*([<>])\s*c(\d+)\.(\w+)$/.exec(e.replace(/\s+/g,""));if(!t)return e;let[,a,s,,r,n]=t,l=`${a}.${s}`,i=`${r}.${n}`,[o,c]=l<i?[l,i]:[i,l];return`${o}::${c}`}(e.expression),a=o.get(t);(!a||Math.abs(e.ratio)>Math.abs(a.ratio))&&o.set(t,e)}return Array.from(o.values()).sort((e,t)=>Math.abs(t.ratio)-Math.abs(e.ratio))})(l,t.cross_constraints||[]),[l,t.cross_constraints]),A=(0,_.useMemo)(()=>(function(e){let t=[],a=new Set;for(let s=0;s<e.length;s+=1)for(let r=0;r<e.length;r+=1){if(s===r)continue;let n=e[s],l=e[r];l.high>n.high&&l.low<n.low&&(t.push({label:`c${r+1} engulfs c${s+1}`,kind:"engulfs",by:`c${r+1}`,of:`c${s+1}`}),a.add(`${r}:${s}`)),l.high<n.high&&l.low>n.low&&!a.has(`${s}:${r}`)&&t.push({label:`c${r+1} inside c${s+1}`,kind:"inside",by:`c${r+1}`,of:`c${s+1}`}),r===s+1&&(l.close>n.high&&t.push({label:`c${r+1} breaks above c${s+1}'s high`,kind:"breaks_above",by:`c${r+1}`,of:`c${s+1}`}),l.close<n.low&&t.push({label:`c${r+1} breaks below c${s+1}'s low`,kind:"breaks_below",by:`c${r+1}`,of:`c${s+1}`}))}return t})(l),[l]),T=(0,_.useMemo)(()=>(function(e){let t=[],a=e.map(e=>e.close>e.open?"bullish":e.close<e.open?"bearish":"any"),s=0;for(let r=1;r<=e.length;r+=1){if(r!==e.length&&a[r]===a[s]&&"any"!==a[s])continue;let n=r-s,l=a[s];n>=3&&("bullish"===l||"bearish"===l)&&t.push(function(e,t,a,s){let r=!0,n=!0,l=!0;for(let i=t+1;i<=a;i+=1){let t=e[i-1],a=e[i];"bullish"===s?(a.close<=t.close&&(r=!1),a.high<=t.high&&(n=!1),a.low<=t.low&&(l=!1)):(a.close>=t.close&&(r=!1),a.high>=t.high&&(n=!1),a.low>=t.low&&(l=!1))}let i=r?"closes":n?"highs":l?"lows":null,o=i?`, monotonic ${i}`:"";return{label:`c${t+1}→c${a+1} all ${s}${o}`,from:`c${t+1}`,to:`c${a+1}`,direction:s,same_direction:!0,monotonic:i}}(e,s,r-1,l)),s=r}return t})(l),[l]),[F,P]=(0,_.useState)(new Set);(0,_.useEffect)(()=>{P(new Set)},[E.length,A.length,T.length]);let R=e=>P(t=>{let a=new Set(t);return a.has(e)?a.delete(e):a.add(e),a}),O=E.length+A.length+T.length,L=F.size,[I,D]=(0,_.useState)(!1),[z,B]=(0,_.useState)(null),[W,U]=(0,_.useState)(!1),H=(0,_.useCallback)(async()=>
4{if(!I&&0!==F.size){D(!0),B(null);try{let a=(t.cross_constraints||[]).slice();for(let e of E)F.has(`price:${e.expression}`)&&!a.includes(e.expression)&&a.push(e.expression);let r=Array.isArray(t.relations)?t.relations.slice():[];for(let e of A){let t=`rel:${e.kind}:${e.by}:${e.of}`;F.has(t)&&(r.find(t=>t?.kind===e.kind&&t?.by===e.by&&t?.of===e.of)||r.push({kind:e.kind,by:e.by,of:e.of}))}let n=Array.isArray(t.streaks)?t.streaks.slice():[];for(let e of T){let t=`streak:${e.from}:${e.to}:${e.direction}:${e.monotonic??""}`;if(F.has(t)&&!n.find(t=>t?.from===e.from&&t?.to===e.to&&t?.direction===e.direction)){let t={from:e.from,to:e.to,direction:e.direction,same_direction:!0};e.monotonic&&(t.monotonic=e.monotonic),n.push(t)}}let l=await (0,er.authFetch)(`/api/patterns/${e}/spec`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({spec_patch:{cross_constraints:a,relations:r,streaks:n},intent:"positive"})}),i=await l.json().catch(()=>({}));if(!l.ok||!i?.ok)return void B(i?.message||i?.error||`HTTP ${l.status}`);i?.data?.pattern&&s&&s(i.data.pattern),P(new Set)}catch(e){B(e?.message||"Apply failed")}finally{D(!1)}}},[I,F,t,e,E,A,T,s]),q=(0,_.useCallback)(()=>{M(!0)},[]),V=(0,_.useCallback)(async()=>{if(y)return;let a=function(e,t){let a=[],s=[];for(let t=0;t<e.length;t+=1){let r=e[t],n=Math.max(r.high-r.low,1e-9),l=Math.max(r.open,r.close),i=Math.min(r.open,r.close),o={body:(l-i)/n,upper_wick:(r.high-l)/n,lower_wick:(i-r.low)/n,close_position:(r.close-r.low)/n},c=`c${t+1}`;for(let e of ag)a.push(`abs(${c}.${e} - ${af(o[e])})`);s.push(r.close>r.open?"bullish":r.close<r.open?"bearish":"any")}return{expression:`${a.join(" + ")} <= ${af(t)}`,directions:s,threshold:t}}(l,ax[k]),r={};for(let e=0;e<l.length;e+=1)r[`c${e+1}`]={direction:a.directions[e],shape:null,body:null,upper_wick:null,lower_wick:null,close_position:null};let n=(t.cross_constraints||[]).slice(),i=function(e){for(let t=0;t<e.length;t+=1)if(ab.test(e[t]))return t;return -1}(n);i>=0&&n.splice(i,1);let o=[...n,a.expression];j(!0),N(null);try{let t=await (0,er.authFetch)(`/api/patterns/${e}/spec`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({spec_patch:{candles:r,cross_constraints:o},intent:"positive"})}),a=await t.json().catch(()=>({}));if(!t.ok||!a?.ok)return void N(a?.message||a?.error||`HTTP ${t.status}`);a?.data?.pattern&&s&&s(a.data.pattern),$.current=l.slice(),M(!1)}catch(e){N(e?.message||"Save failed")}finally{j(!1)}},[y,k,l,t,e,s]),G=(0,_.useCallback)(()=>{i($.current.slice()),M(!1),N(null)},[]),J=(0,_.useCallback)(e=>{if(null==c||null==u)return;e.preventDefault(),e.target.setPointerCapture(e.pointerId);let t=l[c-1];if(!t)return;let a="O"===u?t.open:"H"===u?t.high:"L"===u?t.low:t.close;o.current={candleIdx:c-1,handle:u,startY:e.clientY,startPrice:a}},[c,u,l]),Y=(0,_.useCallback)(e=>{let t=o.current;if(!t)return;let a=-(f/220*(e.clientY-t.startY)),s=t.startPrice+a;q(),i(e=>{let a=e.slice(),r={...a[t.candleIdx]};return"O"===t.handle?(r.open=s,r.high=Math.max(r.high,r.open,r.close),r.low=Math.min(r.low,r.open,r.close)):"C"===t.handle?(r.close=s,r.high=Math.max(r.high,r.open,r.close),r.low=Math.min(r.low,r.open,r.close)):"H"===t.handle?r.high=Math.max(s,r.open,r.close):"L"===t.handle&&(r.low=Math.min(s,r.open,r.close)),r.direction=r.close>r.open?"up":r.close<r.open?"down":r.direction,a[t.candleIdx]=r,a})},[f,220]),K=(0,_.useCallback)(e=>{o.current&&(e.target.releasePointerCapture?.(e.pointerId),o.current=null)},[]);return(0,b.jsxs)("div",{className:"cps-playground",children:[(0,b.jsxs)("div",{className:"cps-playground-toolbar",children:[(0,b.jsxs)("div",{className:"cps-playground-toolbar-group",children:[(0,b.jsx)("span",{className:"cps-playground-toolbar-label",children:"Candle"}),l.map((e,t)=>{let a=t+1;return(0,b.jsxs)("button",{type:"button",className:`cps-playground-candle-btn${c===a?" active":""}`,onClick:()=>d(a),children:["c",a]},a)})]}),(0,b.jsxs)("div",{className:"cps-playground-toolbar-group",children:[(0,b.jsx)("span",{className:"cps-playground-toolbar-label",children:"Drag"}),["O","H","L","C"].map(e=>(0,b.jsx)("button",{type:"button",className:`cps-playground-handle-btn cps-playground-handle-${e.toLowerCase()}${u===e?" active":""}`,onClick:()=>{null==c&&d(1),h(e)},title:"O"===e?"Drag the open price":"H"===e?"Drag the high":"L"===e?"Drag the low":"Drag the close price",children:"O"===e?"Open":"H"===e?"High":"L"===e?"Low":"Close"},e))]})]}),(0,b.jsx)("div",{className:"cps-playground-svg-wrap",children:(0,b.jsx)("svg",{width:g,height:280,viewBox:`0 0 ${g} 280`,"aria-hidden":!0,style:{display:"block",touchAction:"none"},children:l.map((e,t)=>{let a,s,r=t+1,n=22+78*t,l=n+30,i=v(e.high),o=v(e.low),h=v(e.open),p=v(e.close),m=Math.min(h,p),x=Math.max(3,Math.max(h,p)-m),g=c===r,f=null!=c&&!g,_="either"===e.direction?"#9499a2":"up"===e.direction?"#15b097":"#e84957";return(0,b.jsxs)("g",{opacity:f?.4:1,children:[(0,b.jsx)("rect",{x:n-6,y:i-6,width:72,height:o-i+12,fill:"transparent",style:{cursor:g&&u?"ns-resize":"pointer"},onClick:()=>{g||d(r)},onPointerDown:g?J:void 0,onPointerMove:g?Y:void 0,onPointerUp:g?K:void 0,onPointerCancel:g?K:void 0}),g&&(0,b.jsx)("rect",{x:n-5,y:i-5,width:70,height:o-i+10,rx:6,fill:"none",stroke:a_,strokeWidth:2,opacity:.85,pointerEvents:"none"}),(0,b.jsx)("line",{x1:l,x2:l,y1:i,y2:o,stroke:_,strokeWidth:2.5,pointerEvents:"none"}),(0,b.jsx)("rect",{x:n+6,y:m,width:48,height:x,fill:_,rx:1.5,opacity:.9,pointerEvents:"none"}),g&&u&&(a="O"===u?h:"H"===u?i:"L"===u?o:p,s=av[u],(0,b.jsxs)("g",{pointerEvents:"none",children:[(0,b.jsx)("line",{x1:n-4,x2:n+60+4,y1:a,y2:a,stroke:s,strokeWidth:2,strokeDasharray:"4 3",opacity:.9}),(0,b.jsx)("text",{x:n+60+8,y:a+4,fontSize:"11",fill:s,fontFamily:"monospace",fontWeight:700,children:u})]})),(0,b.jsxs)("text",{x:l,y:276,textAnchor:"middle",fontSize:"13",fill:g?a_:"#9499a2",fontFamily:"monospace",fontWeight:g?600:400,pointerEvents:"none",children:["c",r]})]},t)})})}),(0,b.jsxs)("div",{className:"cps-playground-status",children:[(0,b.jsxs)("span",{className:"muted cps-playground-status-hint",children:[null==c&&null==u&&(0,b.jsxs)(b.Fragment,{children:["Tap a candle above, then pick ",ay(h,d,c,u),", then drag."]}),null!=c&&null==u&&(0,b.jsxs)(b.Fragment,{children:["c",c," ready — now pick ",ay(h,d,c,u)," to pick what to drag."]}),null==c&&null!=u&&(0,b.jsxs)(b.Fragment,{children:[u," ready — now tap a candle ",(0,b.jsxs)("strong",{children:["c1..c",x]})," in the toolbar above to pick what to drag."]}),null!=c&&null!=u&&(0,b.jsxs)(b.Fragment,{children:["Drag the ",(0,b.jsxs)("strong",{children:["c",c]})," candle vertically to move its ",(0,b.jsx)("strong",{children:"O"===u?"Open":"H"===u?"High":"L"===u?"Low":"Close"}),"."]})]}),w&&(0,b.jsx)("span",{className:"cps-playground-error",children:w}),(0,b.jsxs)("div",{className:"cps-playground-status-actions",children:[(0,b.jsx)("button",{type:"button",className:"btn btn-ghost",onClick:G,disabled:!C||y,title:"Throw away your unsaved drags",children:"Discard"}),(0,b.jsx)("button",{type:"button",className:"btn btn-primary",onClick:()=>{V()},disabled:!C||y,title:"Save the current drawing to the pattern spec",children:y?"Saving…":C?"Save":"Saved"})]})]}),(0,b.jsxs)("div",{className:"cps-playground-sensitivity",children:[(0,b.jsx)("span",{className:"cps-playground-sensitivity-label",children:"Match similarity:"}),["tight","default","loose"].map(e=>(0,b.jsx)("button",{type:"button",className:`cps-playground-sensitivity-btn${k===e?" active":""}`,onClick:()=>S(e),title:"tight"===e?"Only candles very close to your drawing match (few detections, high precision)":"default"===e?"Balanced — candles broadly similar to your drawing match":"Spirit-of-shape matches (lots of detections, lower precision)",children:"tight"===e?"Tight":"default"===e?"Default":"Loose"},e)),(0,b.jsx)("span",{className:"cps-playground-sensitivity-hint muted",children:"Re-save after changing to apply."})]}),O>0&&(0,b.jsxs)("div",{className:"pattern-lab-refine-preview",style:{marginTop:12},children:[(0,b.jsxs)("button",{type:"button",onClick:()=>U(e=>!e),style:{all:"unset",cursor:"pointer",display:"flex",alignItems:"center",gap:8,width:"100%",padding:"4px 0"},title:W?"Hide suggestions":"Show suggestions inferred from your drawing",children:[(0,b.jsx)("span",{style:{color:"var(--text-secondary)",fontSize:12},children:W?"▾":"▸"}),(0,b.jsx)("strong",{children:"Suggested constraints from your drawing"}),(0,b.jsxs)("span",{style:{color:"var(--fg-muted)",marginLeft:"auto"},children:[O," found",L>0?` \xb7 ${L} checked`:""]})]}),W?null:(0,b.jsx)("div",{style:{marginTop:4,fontSize:11,color:"var(--fg-muted)",fontStyle:"italic"},children:"Click to expand. Inferred from your drawing — opt-in checkboxes for price comparisons / relations / streaks that the candle Save alone wouldn't capture."}),W?(0,b.jsxs)(b.Fragment,{children:[z?(0,b.jsx)("div",{className:"pattern-lab-params-error",children:z}):null,E.length>0?(0,b.jsxs)("div",{style:{marginTop:10},children:[(0,b.jsxs)("div",{style:{fontSize:10,fontWeight:600,color:"var(--fg-muted)",textTransform:"uppercase",letterSpacing:.5,marginBottom:4},children:["Price comparisons (",E.length,")"]}),E.map(e=>{let t=`price:${e.expression}`,a=F.has(t);return(0,b.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,padding:"3px 6px",cursor:"pointer",fontSize:11,borderRadius:3,background:a?"rgba(21,176,151,0.06)":"transparent"},children:[(0,b.jsx)("input",{type:"checkbox",checked:a,onChange:()=>R(t)}),(0,b.jsx)("code",{style:{fontFamily:"var(--font-mono)"},children:e.expression}),(0,b.jsxs)("span",{style:{color:"var(--fg-muted)",fontSize:10,marginLeft:"auto"},children:[Math.abs(e.ratio).toFixed(2),"% gap"]}
4)]},t)})]}):null,A.length>0?(0,b.jsxs)("div",{style:{marginTop:10},children:[(0,b.jsxs)("div",{style:{fontSize:10,fontWeight:600,color:"var(--fg-muted)",textTransform:"uppercase",letterSpacing:.5,marginBottom:4},children:["Named relations (",A.length,")"]}),A.map(e=>{let t=`rel:${e.kind}:${e.by}:${e.of}`,a=F.has(t);return(0,b.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,padding:"3px 6px",cursor:"pointer",fontSize:11,borderRadius:3,background:a?"rgba(21,176,151,0.06)":"transparent"},children:[(0,b.jsx)("input",{type:"checkbox",checked:a,onChange:()=>R(t)}),(0,b.jsxs)("span",{children:[(0,b.jsx)("strong",{children:e.by})," ",(0,b.jsx)("span",{style:{color:"#f6c849"},children:e.kind})," ",(0,b.jsx)("strong",{children:e.of})]})]},t)})]}):null,T.length>0?(0,b.jsxs)("div",{style:{marginTop:10},children:[(0,b.jsxs)("div",{style:{fontSize:10,fontWeight:600,color:"var(--fg-muted)",textTransform:"uppercase",letterSpacing:.5,marginBottom:4},children:["Streaks (",T.length,")"]}),T.map(e=>{let t=`streak:${e.from}:${e.to}:${e.direction}:${e.monotonic??""}`,a=F.has(t);return(0,b.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:8,padding:"3px 6px",cursor:"pointer",fontSize:11,borderRadius:3,background:a?"rgba(21,176,151,0.06)":"transparent"},children:[(0,b.jsx)("input",{type:"checkbox",checked:a,onChange:()=>R(t)}),(0,b.jsx)("span",{children:e.label})]},t)})]}):null,(0,b.jsxs)("div",{style:{marginTop:12,display:"flex",justifyContent:"flex-end",gap:8},children:[(0,b.jsx)("button",{type:"button",className:"btn btn-ghost",onClick:()=>P(new Set),disabled:0===L||I,children:"Clear selection"}),(0,b.jsx)("button",{type:"button",className:"btn btn-primary",onClick:()=>{H()},disabled:0===L||I,children:I?"Applying…":`Apply ${L} checked`})]})]}):null]})]})}function aw({size:e="md",style:t,className:a=""}){return(0,b.jsx)("span",{className:`spinner spinner-${e} ${a}`.trim(),style:t,"aria-hidden":"true"})}function aN({busy:e,label:t,busyLabel:a,size:s="sm"}){return e?(0,b.jsxs)("span",{className:"spinner-inline",children:[(0,b.jsx)(aw,{size:s}),(0,b.jsx)("span",{children:a??t})]}):(0,b.jsx)(b.Fragment,{children:t})}function ak({children:e="Loading…"}){return(0,b.jsxs)("div",{className:"loading-pad",children:[(0,b.jsx)(aw,{size:"md"}),(0,b.jsx)("span",{children:e})]})}class aS{_data;constructor(e){this._data=e}draw(e){let t=e.context;if(!t)return;let a=this._data.paneHeight;for(let e of this._data.highlights){let s=Math.max(.45*e.barSpacing,6),r=e.color,n=.25;"correct"===e.feedback?(r="#00d4aa",n=.3):"incorrect"===e.feedback&&(r="#555555",n=.08);let l=0,i=0,o=0;r.startsWith("#")&&r.length>=7&&(l=parseInt(r.slice(1,3),16),i=parseInt(r.slice(3,5),16),o=parseInt(r.slice(5,7),16));let c=e.x-s,d=2*s;t.fillStyle=`rgba(${l},${i},${o},${n})`,t.fillRect(c,0,d,a),t.fillStyle=`rgba(${l},${i},${o},${n+.15})`,t.fillRect(c,0,d,3),t.fillRect(c,a-3,d,3),t.fillStyle=`rgba(${l},${i},${o},${n+.25})`,t.fillRect(c,0,1.5,a),t.fillRect(c+d-1.5,0,1.5,a)}}}class a${_highlights;_chart;constructor(e,t){this._highlights=e,this._chart=t}renderer(){let e=this._chart.timeScale(),t=e.options?.()?.barSpacing??e.barSpacing?.()??6,a=[];for(let s of this._highlights){let r=e.timeToCoordinate(s.time);null!=r&&a.push({x:Math.round(r),color:s.color,feedback:s.feedback,barSpacing:t})}if(0===a.length)return null;let s=this._chart.chartElement?.();return new aS({highlights:a,paneHeight:s?s.clientHeight-30:400})}}class aC{_highlights=[];_chart=null;_requestUpdate;attached(e){this._chart=e.chart,this._requestUpdate=e.requestUpdate}detached(){this._chart=null,this._requestUpdate=void 0}setHighlights(e){this._highlights=e,this._requestUpdate?.()}paneViews(){return this._highlights.length&&this._chart?[new a$(this._highlights,this._chart)]:[]}}class aM{_data;constructor(e){this._data=e}draw(e){let t=e.context;if(!t)return;let a=this._data.paneHeight;for(let e of this._data.ranges){let s=Math.min(e.x1,e.x2),r=Math.max(1,Math.max(e.x1,e.x2)-s);t.fillStyle="rgba(59,130,246,0.14)",t.fillRect(s,0,r,a),t.strokeStyle="rgba(59,130,246,0.45)",t.lineWidth=1,t.strokeRect(s+.5,.5,Math.max(0,r-1),Math.max(0,a-1))}}}class aE{_ranges;_chart;constructor(e,t){this._ranges=e,this._chart=t}renderer(){if(!this._chart||!this._ranges.length)return null;let e=this._chart.timeScale(),t=[];for(let a of this._ranges){let s=e.timeToCoordinate(a.startTime),r=e.timeToCoordinate(a.endTime);null!=s&&null!=r&&t.push({x1:Number(s),x2:Number(r)})}if(!t.length)return null;let a=this._chart.chartElement?.();return new aM({ranges:t,paneHeight:a?a.clientHeight-30:400})}}class aA{_ranges=[];_chart=null;_requestUpdate;attached(e){this._chart=e.chart,this._requestUpdate=e.requestUpdate}detached(){this._chart=null,this._requestUpdate=void 0}setRanges(e){this._ranges=[...e],this._requestUpdate?.()}paneViews(){return this._chart&&this._ranges.length?[new aE(this._ranges,this._chart)]:[]}}let aT=(0,_.forwardRef)(function({candles:e,realtimeCandle:t,subframeCandles:a,showSubframeOverlay:s=!1,markers:r,priceLines:n,overlayLines:l,patternHighlights:i,selectionMode:o=!1,selectionRanges:c=[],onSelectionRangesChange:d,onCandleClick:u,title:h,subtitle:p,onLoadMore:m,activeIndicatorCount:x,onOpenIndicators:g},f){let v=(0,_.useRef)(null),y=(0,_.useRef)(null),j=(0,_.useRef)(null),w=(0,_.useRef)(null),N=(0,_.useRef)(null),k=(0,_.useRef)(null),$=(0,_.useRef)(!1),C=(0,_.useRef)(null),M=(0,_.useRef)(null),E=(0,_.useRef)(null),F=(0,_.useRef)(0),P=(0,_.useRef)(0),R=(0,_.useRef)(null),[O,L]=(0,_.useState)(null),I=(0,_.useCallback)(t=>{if(!e.length)return -1;let a=e.findIndex(e=>e.time===t);if(a>=0)return a;let s=Number(t);if(!Number.isFinite(s))return -1;let r=0,n=e.length-1;for(;r<n;){let t=r+n>>>1;Number(e[t].time)<s?r=t+1:n=t}let l=r;return l<=0?0:l>=e.length?e.length-1:Math.abs(s-Number(e[l-1].time))<=Math.abs(Number(e[l].time)-s)?l-1:l},[e]),D=(0,_.useMemo)(()=>(e||[]).map(e=>({time:e.time,value:e.close})),[e]);(0,_.useImperativeHandle)(f,()=>({scrollToTime(e){if(!y.current)return;let t=y.current.timeScale(),a=t.options?.()?.barSpacing??6,s=Math.max(6,Math.floor(Math.max(12,Math.floor((v.current?.clientWidth??800)/a))/2)),r=I(e);r>=0&&t.setVisibleLogicalRange({from:r-s,to:r+s})},focusTime(e,t=18){if(!y.current)return;let a=y.current.timeScale(),s=I(e);s>=0&&a.setVisibleLogicalRange({from:s-Math.max(6,t),to:s+Math.max(6,t)})}}),[I]),(0,_.useEffect)(()=>
4{if(!v.current)return;let e=(0,A.createChart)(v.current,{...(0,T.makeChartOptions)(400),autoSize:!0,handleScroll:!0,handleScale:!0}),t=e.addSeries(A.CandlestickSeries,{upColor:T.CHART_COLORS.candleUp,downColor:T.CHART_COLORS.candleDown,wickUpColor:T.CHART_COLORS.candleUp,wickDownColor:T.CHART_COLORS.candleDown,borderVisible:!1,priceLineVisible:!1}),a=e.addSeries(A.AreaSeries,{lineColor:T.CHART_COLORS.areaLine,topColor:T.CHART_COLORS.areaTop,bottomColor:T.CHART_COLORS.areaBottom,lineWidth:1,priceLineVisible:!1,lastValueVisible:!1}),s=e.addSeries(A.LineSeries,{color:"rgba(245, 197, 66, 0.95)",lineWidth:1,lineStyle:2,crosshairMarkerVisible:!1,lastValueVisible:!1,priceLineVisible:!1});y.current=e,j.current=t,w.current=a,N.current=s,e.subscribeCrosshairMove(e=>{e?.time&&e.seriesData?L(e.seriesData.get(t)||null):L(null)});let r=new ResizeObserver(()=>{e.applyOptions({width:v.current.clientWidth})});return r.observe(v.current),k.current=r,()=>{r.disconnect(),e.remove(),y.current=null,j.current=null,w.current=null,N.current=null,C.current=null,M.current=null,E.current=null,$.current=!1}},[]);let z=(0,_.useCallback)(t=>{if(!y.current||!v.current||!e.length)return null;let a=t-v.current.getBoundingClientRect().left,s=y.current.timeScale(),r=null;if("function"==typeof s.coordinateToLogical){let e=s.coordinateToLogical(a);null!=e&&Number.isFinite(e)&&(r=Math.round(Number(e)))}if(null==r&&"function"==typeof s.coordinateToTime){let t=s.coordinateToTime(a);if(null!=t){let a=Number(t),s=0,n=e.length-1;for(;s<n;){let t=s+n>>>1;Number(e[t].time)<a?s=t+1:n=t}r=s}}return null==r?null:(r<0&&(r=0),r>=e.length&&(r=e.length-1),r)},[e]),B=(0,_.useCallback)((t,a)=>{if(!d||!e.length)return;let s=Math.max(0,Math.min(t,e.length-1)),r=Number(e[s].time);if(!Number.isFinite(r))return;let n=[...c],l=n.findIndex(e=>{let t=Math.min(e.startTime,e.endTime),a=Math.max(e.startTime,e.endTime);return t===r&&a===r});if(l>=0){n.splice(l,1),d(n);return}let i=a?n:[];i.push({id:`sel-${r}-${r}-${i.length+1}`,startTime:r,endTime:r}),d(i)},[e,d,c]),W=(0,_.useRef)([]);(0,_.useEffect)(()=>{let e=j.current;if(e){for(let t of W.current)try{e.removePriceLine(t)}catch{}for(let t of(W.current=[],n||[]))Number.isFinite(t.price)&&W.current.push(e.createPrice
4Line({price:t.price,color:t.color||"#f5a524",lineWidth:1,lineStyle:2*!!t.dashed,axisLabelVisible:!0,title:t.title||""}))}},[n]);let U=(0,_.useRef)([]);(0,_.useEffect)(()=>{let e=y.current;if(e){for(let t of U.current)try{e.removeSeries(t)}catch{}for(let t of(U.current=[],l||[])){if(!t.points||t.points.length<2)continue;let a=e.addSeries(A.LineSeries,{color:t.color||"#b17bdb",lineWidth:1,lineStyle:2*!!t.dashed,priceLineVisible:!1,lastValueVisible:!1,crosshairMarkerVisible:!1});a.setData(t.points.slice().sort((e,t)=>Number(e.time)-Number(t.time))),U.current.push(a)}}},[l]),(0,_.useEffect)(()=>{if(!y.current||!m)return;let e=y.current.timeScale(),t=e=>{e&&e.from<10&&m()};return e.subscribeVisibleLogicalRangeChange(t),()=>e.unsubscribeVisibleLogicalRangeChange(t)},[m]),(0,_.useEffect)(()=>{if(!j.current||!w.current||!N.current)return;j.current.setData(e||[]),w.current.setData(D||[]),s&&Array.isArray(a)&&a.length>0?N.current.setData(a.map(e=>({time:e.time,value:e.close}))):N.current.setData([]),Array.isArray(r)&&r.length>0?"function"==typeof A.createSeriesMarkers?C.current?C.current.setMarkers(r):C.current=(0,A.createSeriesMarkers)(j.current,r):"function"==typeof j.current.setMarkers&&j.current.setMarkers(r):C.current?C.current.setMarkers([]):"function"==typeof j.current?.setMarkers&&j.current.setMarkers([]);let t=Array.isArray(r)?r.length:0,n=t>0!=F.current>0;F.current=t;let l=e?.[0]?.close??0,i=P.current>0&&l>0&&Math.abs(l-P.current)/P.current>.3;P.current=l,e?.length>0&&y.current&&(!$.current||n||i)&&(y.current.timeScale().fitContent(),$.current=!0)},[e,D,r,s,a]),(0,_.useEffect)(()=>{t&&j.current&&w.current&&(j.current.update(t),w.current.update({time:t.time,value:t.close}))},[t]),(0,_.useEffect)(()=>{j.current&&y.current&&(i&&i.length>0?(R.current||(R.current=new aC,j.current.attachPrimitive(R.current)),R.current.setHighlights(i)):R.current&&R.current.setHighlights([]))},[i]),(0,_.useEffect)(()=>{if(j.current)if(i&&i.length>0){let e=i.map(e=>{let t="#00d4aa"===e.color,a=e.color,s=t?"arrowUp":"arrowDown";return"correct"===e.feedback?(a="#00d4aa",s="circle"):"incorrect"===e.feedback&&(a="#555555",s="circle"),{time:e.time,position:t?"belowBar":"aboveBar",color:a,shape:s,text:"correct"===e.feedback?"OK":"incorrect"===e.feedback?"X":e.label||"",size:1.5}});e.sort((e,t)=>("number"==typeof e.time?e.time:0)-("number"==typeof t.time?t.time:0)),"function"==typeof A.createSeriesMarkers&&(M.current?M.current.setMarkers(e):M.current=(0,A.createSeriesMarkers)(j.current,e))}else M.current&&M.current.setMarkers([])},[i]),(0,_.useEffect)(()=>{j.current&&(E.current||(E.current=new aA,j.current.attachPrimitive(E.current)),E.current.setRanges(c||[]))},[c]);let H=(0,_.useCallback)(e=>{o&&e.preventDefault()},[o]),q=(0,_.useCallback)(t=>{let a=z(t.clientX);if(null!=a){if(u){let t=e[a];t&&u(t,a)}o&&B(a,!0)}},[z,B,o,u,e]),V=o||!!u,G=t||(e?.length?e[e.length-1]:null),J=O||G;return(0,b.jsxs)("div",{style:{display:"flex",flexDirection:"column",height:"100%"},children:[(0,b.jsxs)("div",{className:"primary-chart-head",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{className:"primary-chart-title",children:h}),p&&(0,b.jsx)("span",{style:{marginLeft:8,fontSize:"var(--fs-xs)",color:"var(--text-tertiary)"},children:p})]}),(0,b.jsxs)("div",{className:"primary-chart-ohlc",children:[(0,b.jsxs)("span",{children:[(0,b.jsx)("span",{children:"O"})," ",(0,S.fmtFloat)(J?.open,J?.open>=100?2:4)]}),(0,b.jsxs)("span",{children:[(0,b.jsx)("span",{children:"H"})," ",(0,S.fmtFloat)(J?.high,J?.high>=100?2:4)]}),(0,b.jsxs)("span",{children:[(0,b.jsx)("span",{children:"L"})," ",(0,S.fmtFloat)(J?.low,J?.low>=100?2:4)]}),(0,b.jsxs)("span",{children:[(0,b.jsx)("span",{children:"C"})," ",(0,S.fmtFloat)(J?.close,J?.close>=100?2:4)]})]}),g&&(0,b.jsxs)("button",{className:"chart-indicators-btn",onClick:g,children:[(0,b.jsx)(tl.SlidersHorizontal,{size:14,className:"chart-indicators-btn-icon"}),"Indicators",null!=x&&x>0&&(0,b.jsx)("span",{className:"chart-indicators-btn-count",children:x})]})]}),(0,b.jsxs)("div",{className:"primary-chart-shell",children:[(0,b.jsx)("div",{ref:v,className:"primary-chart-container"}),(0,b.jsx)("div",{className:`primary-chart-selection-layer${V?" active":""}${o?" selecting":""}`,onMouseDown:H,onClick:q})]})]})}),aF=["2018","2019","2020","2021","2022","2023","2024","2025","2026","polymarket_4m","all"];function aP(e){let t=Array.from(new Set((Array.isArray(e)?e:"string"==typeof e?e.split(",").map(e=>
4e.trim()).filter(Boolean):[]).map(e=>String(e))));if(t.includes("all"))return["all"];let a=aF.filter(e=>"all"!==e&&t.includes(e));return a.length?a:["all"]}function aR(e){return"native"===e?"native":"hourly"}function aO(e){if(!Array.isArray(e))return[];let t=[];for(let a of e){let e=null,s=null;if(Array.isArray(a)&&a.length>=2?(e=Number(a[0]),s=Number(a[1])):a&&"object"==typeof a&&(Number.isFinite(Number(a.ts_ms))&&Number.isFinite(Number(a.equity_usd))?(e=Math.floor(Number(a.ts_ms)/1e3),s=Number(a.equity_usd)):Number.isFinite(Number(a.ts))&&Number.isFinite(Number(a.equity))?(e=Number(a.ts),s=Number(a.equity)):Number.isFinite(Number(a.time))&&Number.isFinite(Number(a.value))&&(e=Number(a.time),s=Number(a.value))),!Number.isFinite(Number(e))||!Number.isFinite(Number(s)))continue;let r=Number(e)>1e12?Math.floor(Number(e)/1e3):Number(e);Number.isFinite(r)&&!(r<=0)&&Number.isFinite(Number(s))&&t.push({ts:r,equity:Number(s)})}t.sort((e,t)=>e.ts-t.ts);let a=[],s=-1;for(let e of t)e.ts<=s||(a.push(e),s=e.ts);return a}function aL(e){let t=aI(e);if(!t||"object"!=typeof t)return null;let a=t.data&&"object"==typeof t.data?t.data:t,s=Array.isArray(a.trades)?a.trades:[],r=aO(a.hourly),n=aO(a.series_native??a.native??a.equity_curve??[]);if(0===r.length&&0===n.length&&s.length){let e=function(e,t){if(!Array.isArray(e)||0===e.length)return[];let a=Number.isFinite(Number(t))?Number(t):2e3,s=[];for(let t of[...e].filter(e=>e&&"object"==typeof e).sort((e,t)=>Number(e?.exit_ts??e?.entry_ts??0)-Number(t?.exit_ts??t?.entry_ts??0))){let e=Number(t?.exit_ts??t?.entry_ts??0),r=Number(t?.pnl_usd??0);Number.isFinite(e)&&!(e<=0)&&Number.isFinite(r)&&(a+=r,s.push({ts:e,equity:a}))}return aO(s)}(s,Number(a?.summary?.start_equity??a?.summary?.initial_equity??2e3));e.length&&(r=e,n=e)}else 0===r.length&&n.length>0&&(r=n),0===n.length&&r.length>0&&(n=r);return{ok:!1!==a.ok,asset:String(a.asset||""),tf:String(a.tf||""),warnings:Array.isArray(a.warnings)?a.warnings:[],summary:a.summary&&"object"==typeof a.summary?a.summary:{},hourly:r,series_native:n,trades:s,trades_total:Number.isFinite(Number(a.trades_total))?Number(a.trades_total):s.length,error:"string"==typeof a.error?a.error:void 0}}function aI(e){if(e&&"object"==typeof e)return e;if("string"==typeof e)try{return JSON.parse(e)}catch{}return null}function aD(e){if(Array.isArray(e)){let t=e.map(e=>Number(e)).filter(e=>Number.isFinite(e));return t.length?t:null}if("string"!=typeof e)return null;let t=e.split(",").map(e=>e.trim()).filter(Boolean);if(!t.length)return null;let a=[];for(let e of t){let t=Number(e);if(!Number.isFinite(t))return null;a.push(t)}return a.length?a:null}function az(e,t=!1){if("boolean"==typeof e)return e;if("number"==typeof e)return 0!==e;if("string"==typeof e){let t=e.trim().toLowerCase();if(["1","true","yes","on"].includes(t))return!0;if(["0","false","no","off"].includes(t))return!1}return t}function aB(e,t){let a=Number(e);return Number.isFinite(a)?a:t}function aW(e){let t=String(e??"default").trim().toLowerCase();return"default"===t||"both"===t||"down_streak_only"===t||"up_streak_only"===t?t:"short_only"===t?"down_streak_only":"long_only"===t?"up_streak_only":"default"}function aU(e){let t="default"===e.hours_et||"all"===e.hours_et?e.hours_et:Array.isArray(e.hours_et)?e.hours_et.join(","):"default",a="all"===e.months?"all":Array.isArray(e.months)?e.months.join(","):"all",s="on"===e.confidence_require_wick_opp_mode?"true":"off"===e.confidence_require_wick_opp_mode?"false":"default";return{lookback_days:e.lookback_days,chart_resolution:e.chart_resolution,selected_windows:aP(e.selected_windows),base_mode:e.base_mode,base_usd_text:String(e.base_usd),base_pct_percent_text:String(e.base_pct_percent),base_cap_usd_text:e.base_cap_usd>0?String(e.base_cap_usd):"",take_profit_percent_text:e.take_profit_percent>0?String(e.take_profit_percent):"",take_profit_fixed_usd_text:e.take_profit_fixed_usd>0?String(e.take_profit_fixed_usd):"",take_profit_after_usd_text:e.take_profit_after_usd>0?String(e.take_profit_after_usd):"",topup_mode:e.topup_mode,topup_drawdown_percent_text:String(e.topup_drawdown_percent),topup_percent_text:String(e.topup_percent),fill_price_min_text:String(e.fill_price_min),fill_price_max_text:String(e.fill_price_max),fill_price_mode:e.fill_price_mode,fill_source:e.fill_source,clob_apply_on:e.clob_apply_on,clob_exclude_unfilled:!!e.clob_exclude_unfilled,clob_entry_window_seconds_text:e.clob_entry_window_seconds>0?String(e.clob_entry_window_seconds):"",clob_fidelity_minutes_text:String(e.clob_fidelity_minutes),ladder_fill_price_min_text:String(e.ladder_fill_price_min),ladder_fill_price_max_text:String(e.ladder_fill_price_max),ladder_fill_price_mode:e.ladder_fill_price_mode,capital_usd_text:String(e.capital_usd),ladder_text:(e.ladder||[]).join(","),streak_override_text:e.streak_override>0?String(e.streak_override):"",streak_move_min_pct_text:e.streak_move_min_pct>0?String(e.streak_move_min_pct):"",streak_move_max_pct_text:e.streak_move_max_pct>0?String(e.streak_move_max_pct):"",exact_override_enabled:!!e.exact_override_enabled,exact_override_value:!!e.exact_override_value,feature_lab_enabled:!!e.feature_lab_enabled,feature_ret1_min_pct_text:0!==e.feature_ret1_min_pct?String(e.feature_ret1_min_pct):"",feature_ret1_max_pct_text:0!==e.feature_ret1_max_pct?String(e.feature_ret1_max_pct):"",feature_retn_lookback_text:String(Math.max(1,Math.floor(e.feature_retn_lookback||4))),feature_retn_min_pct_text:0!==e.feature_retn_min_pct?String(e.feature_retn_min_pct):"",feature_retn_max_pct_text:0!==e.feature_retn_max_pct?String(e.feature_retn_max_pct):"",feature_atr14_min_pct_text:0!==e.feature_atr14_min_pct?String(e.feature_atr14_min_pct):"",feature_atr14_max_pct_text:0!==e.feature_atr14_max_pct?String(e.feature_atr14_max_pct):"",feature_ema20_gap_min_pct_text:0!==e.feature_ema20_gap_min_pct?String(e.feature_ema20_gap_min_pct):"",feature_ema20_gap_max_pct_text:0!==e.feature_ema20_gap_max_pct?String(e.feature_ema20_gap_max_pct):"",feature_wick_o
4pp_max_text:e.feature_wick_opp_max>0?String(e.feature_wick_opp_max):"",feature_vol_ratio_min_text:e.feature_vol_ratio_min>0?String(e.feature_vol_ratio_min):"",feature_vol_ratio_max_text:e.feature_vol_ratio_max>0?String(e.feature_vol_ratio_max):"",feature_rsi14_min_text:e.feature_rsi14_min>0?String(e.feature_rsi14_min):"",feature_rsi14_max_text:e.feature_rsi14_max>0?String(e.feature_rsi14_max):"",confidence_override_mode:e.confidence_override_mode,confidence_multiplier_text:String(e.confidence_multiplier),confidence_min_score_text:String(e.confidence_min_score),confidence_atr_cap_text:String(e.confidence_atr_cap),confidence_ret1_ext_text:String(e.confidence_ret1_ext),confidence_ema_ext_text:String(e.confidence_ema_ext),confidence_m1_ret_ext_text:String(e.confidence_m1_ret_ext),confidence_require_wick_opp_mode:s,confidence_wick_opp_cap_text:String(e.confidence_wick_opp_cap),confidence_sizing_mode:e.confidence_sizing_mode,confidence_sizing_denominator_text:String(e.confidence_sizing_denominator),confidence_sizing_tiers_text:String(e.confidence_sizing_tiers_text||""),pattern_side_override:e.pattern_side_override,entry_timing_override:e.entry_timing_override,direction_rule_override:e.direction_rule_override,signal_engine_override:e.signal_engine_override,neutral_default_side_override:e.neutral_default_side_override,weekday_mult_text:(e.weekday_base_multipliers||[]).join(","),choppy_week_enabled:!!e.choppy_week_enabled,choppy_week_score_threshold_text:String(e.choppy_week_score_threshold),choppy_week_day_mult_text:(e.choppy_week_day_multipliers||[]).join(","),choppy_week_btc_ret_sum_threshold_text:String(e.choppy_week_btc_ret_sum_threshold),choppy_week_btc_wick_body_threshold_text:String(e.choppy_week_btc_wick_body_threshold),choppy_week_vol_ratio_threshold_text:String(e.choppy_week_vol_ratio_threshold),hours_et_text:t,months_text:a,pair_eth_multiplier_text:String(e.pair_eth_multiplier),pair_xrp_multiplier_text:"1",cps_param_overrides:{...e.cps_param_overrides||{}},use_polybacktest_snapshots:!1,include_snapshot_trade_log:!1}}function aH(e){let t=aI(e)??{};if(t&&"object"==typeof t&&["base_usd_text","capital_usd_text","ladder_text","weekday_mult_text","hours_et_text","months_text"].some(e=>Object.prototype.hasOwnProperty.call(t,e)))return function(e){let t={...aq};t.chart_resolution=aR(e.chart_resolution??t.chart_resolution),t.selected_windows=aP(e.selected_windows??e.windows??e.window??t.selected_windows),t.lookback_days=Math.max(0,Math.floor(aB(e.lookback_days,t.lookback_days)));let a=String(e.base_mode??t.base_mode).toLowerCase();t.base_mode="percent"===a?"percent":"fixed",t.capital_usd=aB(e.capital_usd_text??e.capital_usd,t.capital_usd),t.base_usd=aB(e.base_usd_text??e.base_usd,t.base_usd),t.base_pct_percent=aB(e.base_pct_percent_text??e.base_pct_percent,t.base_pct_percent),t.base_cap_usd=aB(e.base_cap_usd_text??e.base_cap_usd,t.base_cap_usd),t.take_profit_percent=aB(e.take_profit_percent_text??e.take_profit_percent,t.take_profit_percent),t.take_profit_fixed_usd=aB(e.take_profit_fixed_usd_text??e.take_profit_fixed_usd,t.take_profit_fixed_usd),t.take_profit_after_usd=aB(e.take_profit_after_usd_text??e.take_profit_after_usd,t.take_profit_after_usd),t.stop_loss_percent=aB(e.stop_loss_percent,t.stop_loss_percent),t.max_hold_bars=Math.max(0,Math.floor(aB(e.max_hold_bars,t.max_hold_bars)));let s=String(e.topup_mode??t.topup_mode).trim().toLowerCase();t.topup_mode="percent"===s||"back_to_initial_cap"===s?s:"off",t.topup_drawdown_percent=aB(e.topup_drawdown_percent_text??e.topup_drawdown_percent,t.topup_drawdown_percent),t.topup_percent=aB(e.topup_percent_text??e.topup_percent,t.topup_percent),t.fill_price_min=aB(e.fill_price_min_text??e.fill_price_min,t.fill_price_min),t.fill_price_max=aB(e.fill_price_max_text??e.fill_price_max,t.fill_price_max),t.fill_price_mode="fixed_avg"===String(e.fill_price_mode??t.fill_price_mode).toLowerCase()?"fixed_avg":"variation";let r=String(e.fill_source??t.fill_source).trim().toLowerCase();t.fill_source="clob_history"===r||"clob"===r?"clob_history":"synthetic";let n=String(e.clob_apply_on??t.clob_apply_on).trim().toLowerCase();t.clob_apply_on="step1_only"===n||"step1"===n?"step1_only":"all_steps",t.clob_exclude_unfilled=az(e.clob_exclude_unfilled,t.clob_exclude_unfilled),t.clob_entry_window_seconds=Math.max(0,Math.floor(aB(e.clob_entry_window_seconds_text??e.clob_entry_window_seconds,t.clob_entry_window_seconds))),t.clob_fidelity_minutes=Math.max(1,Math.floor(aB(e.clob_fidelity_minutes_text??e.clob_fidelity_minutes,t.clob_fidelity_minutes))),t.ladder_fill_price_min=aB(e.ladder_fill_price_min_text??e.ladder_fill_price_min,t.ladder_fill_price_min),t.ladder_fill_price_max=aB(e.ladder_fill_price_max_text??e.ladder_fill_price_max,t.ladder_fill_price_max),t.ladder_fill_price_mode="fixed_avg"===String(e.ladder_fill_price_mode??t.ladder_fill_price_mode).toLowerCase()?"fixed_avg":"variation";let l=aD(e.ladder_text??e.ladder);if(l&&l.length){let e=l.filter(e=>e>=0);e.some(e=>e>0)&&(t.ladder=e)}t.streak_override=Math.max(0,Math.floor(aB(e.streak_override_text??e.streak_override,t.streak_override))),t.streak_move_min_pct=aB(e.streak_move_min_pct_text??e.streak_move_min_pct,t.streak_move_min_pct),t.streak_move_max_pct=aB(e.streak_move_max_pct_text??e.streak_move_max_pct,t.streak_move_max_pct),t.exact_override_enabled=az(e.exact_override_enabled,t.exact_override_enabled),t.exact_override_value=az(e.exact_override_value,t.exact_override_value),t.feature_lab_enabled=az(e.feature_lab_enabled,t.feature_lab_enabled),t.feature_ret1_min_pct=aB(e.feature_ret1_min_pct_text??e.feature_ret1_min_pct,t.feature_ret1_min_pct),t.feature_ret1_max_pct=aB(e.feature_ret1_max_pct_text??e.feature_ret1_max_pct,t.feature_ret1_max_pct),t.feature_retn_lookback=Math.max(1,Math.floor(aB(e.feature_retn_lookback_text??e.feature_retn_lookback,t.feature_retn_lookback))),t.feature_retn_min_pct=aB(e.feature_retn_min_pct_text??e.feature_retn_min_pct,t.feature_retn_min_pct),t.feature_retn_max_pct=aB(e.feature_retn_max_pct_text??e.feature_retn_max_pct,t.feature_retn_max_pct),t.feature_atr14_min_pct=aB(e.feature_atr14_min_pct_text??e.feature_atr14_min_pct,t.feature_atr14_min_pct),t.feature_atr14_max_pct=aB(e.feature_atr14_max_pct_text??e.feature_atr14_max_pct,t.feature_atr14_max_pct),t.feature_ema20_gap_min_pct=aB(e.feature_ema20_gap_min_pct_text??e.feature_ema20_gap_min_pct,t.feature_ema20_gap_min_pct),t.feature_ema20_gap_max_pct=aB(e.feature_ema20_gap_max_pct_text??e.feature_ema20_gap_max_pct,t.feature_ema20_gap_max_pct),t.feature_wick_o
4pp_max=aB(e.feature_wick_opp_max_text??e.feature_wick_opp_max,t.feature_wick_opp_max),t.feature_vol_ratio_min=aB(e.feature_vol_ratio_min_text??e.feature_vol_ratio_min,t.feature_vol_ratio_min),t.feature_vol_ratio_max=aB(e.feature_vol_ratio_max_text??e.feature_vol_ratio_max,t.feature_vol_ratio_max),t.feature_rsi14_min=aB(e.feature_rsi14_min_text??e.feature_rsi14_min,t.feature_rsi14_min),t.feature_rsi14_max=aB(e.feature_rsi14_max_text??e.feature_rsi14_max,t.feature_rsi14_max);let i=String(e.confidence_override_mode??t.confidence_override_mode).trim().toLowerCase();t.confidence_override_mode="on"===i||"off"===i?i:"default",t.confidence_multiplier=aB(e.confidence_multiplier_text??e.confidence_multiplier,t.confidence_multiplier),t.confidence_min_score=aB(e.confidence_min_score_text??e.confidence_min_score,t.confidence_min_score),t.confidence_atr_cap=aB(e.confidence_atr_cap_text??e.confidence_atr_cap,t.confidence_atr_cap),t.confidence_ret1_ext=aB(e.confidence_ret1_ext_text??e.confidence_ret1_ext,t.confidence_ret1_ext),t.confidence_ema_ext=aB(e.confidence_ema_ext_text??e.confidence_ema_ext,t.confidence_ema_ext),t.confidence_m1_ret_ext=aB(e.confidence_m1_ret_ext_text??e.confidence_m1_ret_ext,t.confidence_m1_ret_ext);let o=String(e.confidence_require_wick_opp_mode??t.confidence_require_wick_opp_mode).trim().toLowerCase();"true"===o||"on"===o?t.confidence_require_wick_opp_mode="on":"false"===o||"off"===o?t.confidence_require_wick_opp_mode="off":t.confidence_require_wick_opp_mode="default",t.confidence_wick_opp_cap=aB(e.confidence_wick_opp_cap_text??e.confidence_wick_opp_cap,t.confidence_wick_opp_cap);let c=String(e.confidence_sizing_mode??t.confidence_sizing_mode).trim().toLowerCase();t.confidence_sizing_mode="exact"===c?"exact":"ranges"===c?"ranges":"off",t.confidence_sizing_denominator=Math.max(1e-9,aB(e.confidence_sizing_denominator_text??e.confidence_sizing_denominator,t.confidence_sizing_denominator));let d=e.confidence_sizing_tiers_text??e.confidence_sizing_tiers??t.confidence_sizing_tiers_text;Array.isArray(d)?t.confidence_sizing_tiers_text=d.map(e=>{let t=Number(e?.threshold??e?.min??0),a=Number(e?.multiplier??e?.mult??1);return`${t}%=${100*a}%`}).join(","):t.confidence_sizing_tiers_text=String(d??"").trim(),t.pattern_side_override=aW(e.pattern_side_override);let u=String(e.entry_timing_override??t.entry_timing_override).trim().toLowerCase();t.entry_timing_override="next_candle_close"===u?"next_candle_close":"after_confirmation_close"===u?"after_confirmation_close":"default";let h=String(e.direction_rule_override??t.direction_rule_override).trim().toLowerCase();t.direction_rule_override="opposite_confirmation"===h?"opposite_confirmation":"follow_confirmation"===h?"follow_confirmation":"default";let p=String(e.signal_engine_override??t.signal_engine_override).trim().toLowerCase();t.signal_engine_override="streak_parity"===p?"streak_parity":"calc_py"===p?"calc_py":"auto";let m=String(e.neutral_default_side_override??t.neutral_default_side_override).trim().toLowerCase();t.neutral_default_side_override="up"===m?"up":"down"===m?"down":"auto";let x=aD(e.weekday_mult_text??e.weekday_base_multipliers);x&&7===x.length&&(t.weekday_base_multipliers=x.map(e=>Math.max(0,e))),t.choppy_week_enabled=az(e.choppy_week_enabled,t.choppy_week_enabled),t.choppy_week_score_threshold=Math.max(0,Math.floor(aB(e.choppy_week_score_threshold_text??e.choppy_week_score_threshold,t.choppy_week_score_threshold)));let g=aD(e.choppy_week_day_mult_text??e.choppy_week_day_multipliers);g&&4===g.length&&(t.choppy_week_day_multipliers=g.map(e=>Math.max(0,e))),t.choppy_week_btc_ret_sum_threshold=aB(e.choppy_week_btc_ret_sum_threshold_text??e.choppy_week_btc_ret_sum_threshold??e.choppy_week_btc_mw_ret_sum_threshold,t.choppy_week_btc_ret_sum_threshold),t.choppy_week_btc_wick_body_threshold=aB(e.choppy_week_btc_wick_body_threshold_text??e.choppy_week_btc_wick_body_threshold??e.choppy_week_btc_mw_wick_body_ratio_threshold,t.choppy_week_btc_wick_body_threshold),t.choppy_week_vol_ratio_threshold=aB(e.choppy_week_vol_ratio_threshold_text??e.choppy_week_vol_ratio_threshold??e.choppy_week_mw_vol_ratio_eth_btc_threshold,t.choppy_week_vol_ratio_threshold),t.hours_et=function(e){if(Array.isArray(e)){let t=e.map(e=>Number(e)).filter(e=>Number.isInteger(e)&&e>=0&&e<=23);return t.length?Array.from(new Set(t)).sort((e,t)=>
4e-t):"all"}let t=String(e??"").trim().toLowerCase();if(!t||"default"===t)return"default";if("all"===t)return"all";let a=aD(t);if(!a)return"default";let s=a.filter(e=>Number.isInteger(e)&&e>=0&&e<=23);return s.length?Array.from(new Set(s)).sort((e,t)=>e-t):"all"}(e.hours_et_text??e.hours_et),t.months=function(e){if(Array.isArray(e)){let t=e.map(e=>Number(e)).filter(e=>Number.isInteger(e)&&e>=1&&e<=12);return t.length?Array.from(new Set(t)).sort((e,t)=>e-t):"all"}let t=String(e??"").trim().toLowerCase();if(!t||"all"===t)return"all";let a=aD(t);if(!a)return"all";let s=a.filter(e=>Number.isInteger(e)&&e>=1&&e<=12);return s.length?Array.from(new Set(s)).sort((e,t)=>e-t):"all"}(e.months_text??e.months),t.pair_eth_multiplier=aB(e.pair_eth_multiplier_text??e.pair_eth_multiplier,t.pair_eth_multiplier),t.fee_bps_per_side=aB(e.fee_bps_per_side,t.fee_bps_per_side);let f=e.cps_param_overrides??e.cps_params;if(f&&"object"==typeof f&&!Array.isArray(f)){let e={};for(let[t,a]of Object.entries(f)){let s=Number(a);Number.isFinite(s)&&(e[String(t)]=s)}t.cps_param_overrides=e}else t.cps_param_overrides={};return aH(t)}(t);let a={...aq,...t||{}};return a.chart_resolution=aR(t?.chart_resolution??a.chart_resolution),a.selected_windows=aP(t?.selected_windows??a.selected_windows),Array.isArray(a.ladder)&&0!==a.ladder.length||(a.ladder=[...aq.ladder]),Array.isArray(a.weekday_base_multipliers)&&7===a.weekday_base_multipliers.length||(a.weekday_base_multipliers=[...aq.weekday_base_multipliers]),Array.isArray(a.choppy_week_day_multipliers)&&4===a.choppy_week_day_multipliers.length||(a.choppy_week_day_multipliers=[...aq.choppy_week_day_multipliers]),Array.isArray(a.hours_et)||"default"===a.hours_et||"all"===a.hours_et||(a.hours_et="default"),Array.isArray(a.months)||"all"===a.months||(a.months="all"),a.feature_retn_lookback=Math.max(1,Math.floor(Number(a.feature_retn_lookback||4))),a.pattern_side_override=aW(a.pattern_side_override),a}let aq={lookback_days:0,chart_resolution:"hourly",selected_windows:["all"],capital_usd:2e3,base_mode:"fixed",base_usd:50,base_pct_percent:2,base_cap_usd:0,take_profit_percent:0,take_profit_fixed_usd:0,take_profit_after_usd:0,stop_loss_percent:0,max_hold_bars:0,topup_mode:"off",topup_drawdown_percent:50,topup_percent:25,fill_price_min:.55,fill_price_max:.55,fill_price_mode:"variation",fill_source:"synthetic",clob_apply_on:"all_steps",clob_exclude_unfilled:!0,clob_entry_window_seconds:0,clob_fidelity_minutes:1,ladder_fill_price_min:.55,ladder_fill_price_max:.55,ladder_fill_price_mode:"variation",ladder:[1,2,4],streak_override:0,streak_move_min_pct:0,streak_move_max_pct:0,exact_override_enabled:!1,exact_override_value:!0,feature_lab_enabled:!1,feature_ret1_min_pct:0,feature_ret1_max_pct:0,feature_retn_lookback:4,feature_retn_min_pct:0,feature_retn_max_pct:0,feature_atr14_min_pct:0,feature_atr14_max_pct:0,feature_ema20_gap_min_pct:0,feature_ema20_gap_max_pct:0,feature_wick_opp_max:0,feature_vol_ratio_min:0,feature_vol_ratio_max:0,feature_rsi14_min:0,feature_rsi14_max:0,confidence_override_mode:"default",confidence_multiplier:1.5,confidence_min_score:3,confidence_atr_cap:.008,confidence_ret1_ext:.003,confidence_ema_ext:.0025,confidence_m1_ret_ext:.002,confidence_require_wick_opp_mode:"default",confidence_wick_opp_cap:.15,confidence_sizing_mode:"off",confidence_sizing_denominator:100,confidence_sizing_tiers_text:"",pattern_side_override:"default",entry_timing_override:"default",direction_rule_override:"default",signal_engine_override:"auto",neutral_default_side_override:"auto",weekday_base_multipliers:[1,1,1,1,1,1,1],choppy_week_enabled:!1,choppy_week_score_threshold:2,choppy_week_day_multipliers:[1,1,1,1],choppy_week_btc_ret_sum_threshold:.0269268903,choppy_week_btc_wick_body_threshold:.9785169356,choppy_week_vol_ratio_threshold:1.4451694008,hours_et:"default",months:"all",pair_eth_multiplier:1,fee_bps_per_side:0,cps_param_overrides:{}};function aV(e){return null==e||Number.isNaN(Number(e))?"-":Number(e).toLocaleString(void 0,{maximumFractionDigits:2})}function aG(e){return null==e||Number.isNaN(Number(e))?"-":Number(e).toFixed(3)}function aJ(e){return null==e||Number.isNaN(Number(e))?"-":Number(e).toLocaleStr
4ing(void 0,{maximumFractionDigits:6})}function aY(e){if(!e)return"-";let t=new Date(1e3*e),a=t.getUTCFullYear(),s=String(t.getUTCMonth()+1).padStart(2,"0"),r=String(t.getUTCDate()).padStart(2,"0"),n=String(t.getUTCHours()).padStart(2,"0"),l=String(t.getUTCMinutes()).padStart(2,"0");return`${a}-${s}-${r} ${n}:${l}`}function aK(e){let t=String(e?.strategy_slot||"").trim(),a=String(e?.strategy_key||"").trim();return t||a?t&&a?`${t}:${a}`:t||a:""}function aX({c:e,minLow:t,maxHigh:a,onClick:s}){let r=Number(e?.open),n=Number(e?.high),l=Number(e?.low),i=Number(e?.close);if(![r,n,l,i].every(e=>Number.isFinite(e)))return null;let o=Math.max(a-t,1e-9),c=e=>1+(a-e)/o*54,d=c(n),u=c(l),h=c(r),p=c(i),m=Math.min(h,p),x=Math.max(3,Math.abs(p-h)),g=i>=r?"#1fbf87":"#e66161",f=String(e?.role||"");return(0,b.jsxs)("div",{role:s?"button":void 0,tabIndex:s?0:void 0,onClick:s,onKeyDown:s?e=>{("Enter"===e.key||" "===e.key)&&(e.preventDefault(),s())}:void 0,style:{width:12,height:56,position:"relative",display:"inline-block",marginRight:3,borderRadius:2,border:`1px solid ${"entry"===f?"#8fb8ff":"detect"===f?"#f7c86a":"transparent"}`,cursor:s?"pointer":"default"},children:[(0,b.jsx)("div",{style:{position:"absolute",left:"50%",top:`${d}px`,height:`${Math.max(1,u-d)}px`,width:1,transform:"translateX(-50%)",background:"#9aa3b2"}}),(0,b.jsx)("div",{style:{position:"absolute",left:2,right:2,top:`${m}px`,height:`${x}px`,background:g,borderRadius:1}})]})}let aZ=["2018","2019","2020","2021","2022","2023","2024","2025","2026","polymarket_4m","all"];function aQ(e){return null!=e&&Number.isFinite(e)?`${e<0?"-":""}$${Math.abs(e).toLocaleString(void 0,{maximumFractionDigits:2})}`:"-"}function a0(e){return null!=e&&Number.isFinite(e)?`${e.toFixed(2)}%`:"-"}function a1(e,t=2){if(null==e||!Number.isFinite(e))return"-";let a=Number(e),s=a>0?"+":"";return`${s}${a.toFixed(t)}`}function a2(e){let t=e.split(",").map(e=>e.trim()).filter(Boolean);if(!t.length)return null;let a=[];for(let e of t){let t=Number(e);if(!Number.isFinite(t))return null;a.push(t)}return a}function a5({label:e,value:t,format:a,parse:s,onCommit:r,validate:n,placeholder:l}){let[i,o]=(0,_.useState)(a(t)),[c,d]=(0,_.useState)(!1);return(0,_.useEffect)(()=>{o(a(t)),d(!1)},[t]),(0,b.jsx)(a6,{label:e,children:(0,b.jsx)("input",{type:"text",value:i,placeholder:l,className:`ps-input${c?" invalid":""}`,onChange:e=>{o(e.target.value),c&&d(!1)},onBlur:()=>{let e=s(i);null===e||n&&!n(e)?d(!0):(d(!1),r(e))},onKeyDown:e=>{"Enter"===e.key&&e.target.blur()}})})}function a4({pattern:e,onClose:t,onChanged:a}){var s,r;let n=function(e){let[t,a]=(0,_.useState)(aq),[s,r]=(0,_.useState)("BTC"),[n,l]=(0,_.useState)("15m"),[i,o]=(0,_.useState)(!1),[c,d]=(0,_.useState)(null),[u,h]=(0,_.useState)(null),[p,m]=(0,_.useState)(!1),[x,g]=(0,_.useState)(!1),[f,b]=(0,_.useState)(!1),[v,y]=(0,_.useState)(null),[j,w]=(0,_.useState)(!1),[N,k]=(0,_.useState)(!1),[S,$]=(0,_.useState)(null),C=(0,_.useRef)(aq),M=(0,_.useRef)("BTC"),E=(0,_.useRef)("15m"),A=(0,_.useRef)(null);(0,_.useEffect)(()=>{C.current=t},[t]),(0,_.useEffect)(()=>{M.current=s},[s]),(0,_.useEffect)(()=>{E.current=n},[n]),(0,_.useEffect)(()=>{A.current=c},[c]),(0,_.useEffect)(()=>{if(!e)return;let t=!1;return(async()=>{m(!0),$(null);try{let n=await (0,er.authGetJson)(`/api/patterns/${e}/strategy`);if(t)return;if(n.ok&&n.data){var s;o(n.data.exists);let e=(s=n.data.params,aH(s));C.current=e,a(e),M.current=n.data.asset||"BTC",r(M.current),E.current=n.data.tf||"15m",l(E.current),d(aL(n.data.last_backtest)),h(n.data.last_backtest_at)}}catch(e){t||$(e.message||"Failed to load strategy")}finally{t||m(!1)}})(),()=>{t=!0}},[e]);let T=(0,_.useCallback)((e,t)=>{a(a=>{let s={...a,[e]:t};return C.current=s,s})},[]),F=(0,_.useCallback)(e=>{let t=aH(e);C.current=t,a(t)},[]),P=(0,_.useCallback)(()=>{let e={...aq};C.current=e,a(e)},[]),[R,O]=(0,_.useState)([]),[L,I]=(0,_.useState)(!1),D=(0,_.useRef)(null),[z,B]=(0,_.useState)(null);(0,_.useEffect)(()=>{D.current=z},[z]);let[W,U]=(0,_.useState)(null),H=e=>`openpoly:loaded-preset:${e}`;(0,_.useEffect)(()=>{if(e)try{let t=H(e);z?window.localStorage.setItem(t,z):window.localStorage.removeItem(t)}catch{}},[e,z]);let q=(0,_.useCallback)(async()=>
4{if(e){I(!0),U(null);try{let t=await (0,er.authGetJson)(`/api/patterns/${e}/strategy/presets`);t.ok&&Array.isArray(t.data)&&O(t.data)}catch(e){U(e?.message||"Failed to load presets")}finally{I(!1)}}},[e]);(0,_.useEffect)(()=>{if(!e){O([]),B(null);return}B((e=>{try{let t=window.localStorage.getItem(H(e));return t&&t.trim()?t:null}catch{return null}})(e)),q()},[e,q]),(0,_.useEffect)(()=>{!z||L||0!==R.length&&(R.some(e=>e.name===z)||B(null))},[R,L,z]);let V=(0,_.useCallback)(async t=>{if(!e)return;let a=(t||"").trim();if(!a)return void U("Preset name is required");U(null);try{var s;let t=aU((s=C.current,aH(s))),r=await (0,er.authFetch)(`/api/patterns/${e}/strategy/presets/${encodeURIComponent(a)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({params:t,asset:M.current,tf:E.current})});if(!r.ok){let e=await r.json().catch(()=>({}));throw Error(e?.error||`Save failed: ${r.status}`)}await q(),B(a)}catch(e){U(e?.message||"Failed to save preset")}},[e,q]),G=(0,_.useCallback)(e=>{let t=R.find(t=>t.name===e);if(!t)return void U(`Preset "${e}" not found`);U(null);let s=aH(t.params);C.current=s,a(s),M.current=t.asset||M.current,r(M.current),E.current=t.tf||E.current,l(E.current),B(e)},[R]),J=(0,_.useCallback)(async t=>{if(e){U(null);try{let a=await (0,er.authFetch)(`/api/patterns/${e}/strategy/presets/${encodeURIComponent(t)}`,{method:"DELETE"});if(!a.ok){let e=await a.json().catch(()=>({}));throw Error(e?.error||`Delete failed: ${a.status}`)}await q()}catch(e){U(e?.message||"Failed to delete preset")}}},[e,q]),Y=(0,_.useCallback)(async()=>{if(e){k(!0),$(null);try{var t,s;let n=aU((t=C.current,aH(t))),i=await (0,er.authFetch)(`/api/patterns/${e}/strategy`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({params:n,asset:M.current,tf:E.current})});if(!i.ok)throw Error(`PUT failed: ${i.status}`);let c=await (0,er.authGetJson)(`/api/patterns/${e}/strategy`);if(c?.ok&&c.data){let e=(s=c.data.params,aH(s));C.current=e,a(e),M.current=c.data.asset||M.current,r(M.current),E.current=c.data.tf||E.current,l(E.current),d(aL(c.data.last_backtest)),h(c.data.last_backtest_at)}o(!0)}catch(e){$(e.message||"Failed to save")}finally{k(!1)}}},[e]),K=(0,_.useCallback)(async(t,a=50,s)=>{if(!e)return;let r=String(s??(A.current?.summary?.signal_rows_token||"")).trim();if(r){b(!0),y(null);try{let s=Math.max(1,Number(t)||1),n=Math.max(1,Math.min(500,Number(a)||50)),l=new URLSearchParams({token:r,page:String(s),page_size:String(n)}),i=await (0,er.authGetJson)(`/api/patterns/${e}/strategy/signal-rows?${l.toString()}`);if(!i?.ok||!i?.data)throw Error("Failed to load signal rows.");d(e=>{if(!e)return e;let t=String(e.summary?.signal_rows_token||"").trim();if(t&&t!==r)return e;let a={...e.summary||{}};a.signal_rows=Array.isArray(i.data.rows)?i.data.rows:[],a.signal_rows_total=Number(i.data.total||0),a.signal_rows_page=Number(i.data.page||1),a.signal_rows_page_size=Number(i.data.page_size||n),a.signal_rows_page_count=Number(i.data.page_count||1),a.signal_rows_token=String(i.data.token||r);let s={...e,summary:a};return A.current=s,s})}catch(e){y(e?.message||"Failed to load signal rows")}finally{b(!1)}}},[e]),X=(0,_.useCallback)(async()=>{if(e){w(!0),$(null),y(null);try{let t=await (0,er.authFetch)(`/api/patterns/${e}/strategy/cache/clear`,{method:"POST"});if(!t.ok){let e=await t.text();throw Error(`Clear cache failed: ${t.status} ${e.slice(0,200)}`)}d(e=>{if(!e)return e;let t={...e.summary||{}};t.signal_rows_token="",t.signal_rows_page=1,t.signal_rows_page_count=1;let a={...e,summary:t};return A.current=a,a}),y("Cache cleared. Run backtest again.")}catch(e){$(e.message||"Failed to clear backtest cache")}finally{w(!1)}}},[e]),Z=(0,_.useCallback)(async t=>{if(e){g(!0),$(null);try{var a,s;let r=aU((a=C.current,aH(a))),n=Array.isArray(t?.combine_with_pattern_keys)?t.combine_with_pattern_keys:[],l=Array.from(new Set(n.map(e=>String(e||"").trim()).filter(Boolean))),i=String(t?.combine_with_pattern_key||"").trim();i&&!l.includes(i)&&l.push(i);let c={method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({params:r,asset:M.current,tf:E.current,combine_with_pattern_key:i||void 0,combine_with_pattern_keys:l.length>0?l:void 0,persist:!1,include_trades:!1,include_signal_rows:!1,signal_rows_page:1,signal_rows_page_size:50})},u=e=>{let t=String(e?.message||""),a=String(e?.name||"");return"TypeError"===a||/Failed to fetch/i.test(t)||/NetworkError/i.test(t)||/Load failed/i.test(t)},p=e=>new Promise(t=>setTimeout(t,e)),m=null,x=null;for(let t=0;t<3;t++)try{m=await (0,er.authFetch)(`/api/patterns/${e}/strategy/backtest`,c),x=null;break}catch(e){if(x=e,!u(e)||t>=2)break;
4await p(500*(t+1))}if(!m){if(u(x))throw Error("Failed to fetch backtest API (network/drop). Please retry.");throw x||Error("Backtest request failed")}if(!m.ok){let e=await m.text();throw Error(`Backtest failed: ${m.status} ${e.slice(0,200)}`)}let g=await m.json();if(!g.ok)throw Error(g.error||"Backtest failed");let f=aL(g.data);d(f),h(new Date().toISOString()),o(!0);let b=String(f?.summary?.signal_rows_token||"").trim(),_=Number(f?.summary?.signal_rows_total||0);b&&_>0&&K(1,50,b);let v=D.current;if(v){let t=aU((s=C.current,aH(s))),a=Array.isArray(g.data?.equity_curve)?g.data.equity_curve:[],r=a;if(a.length>120){let e=Math.ceil(a.length/120);(r=a.filter((t,a)=>a%e==0))[r.length-1]!==a[a.length-1]&&r.push(a[a.length-1])}let n={summary:g.data?.summary||{},equity_curve_sample:r};(0,er.authFetch)(`/api/patterns/${e}/strategy/presets/${encodeURIComponent(v)}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({params:t,asset:M.current,tf:E.current,last_backtest:n})}).then(e=>{e.ok&&q()}).catch(()=>{})}}catch(e){$(e.message||"Backtest failed")}finally{g(!1)}}},[e,K,q]);return{params:t,setParam:T,setAllParams:F,resetDefaults:P,asset:s,setAsset:r,tf:n,setTf:l,exists:i,result:c,resultAt:u,loading:p,running:x,signalRowsLoading:f,signalRowsError:v,cacheClearing:j,saving:N,error:S,loadSignalRowsPage:K,clearBacktestCache:X,save:Y,run:Z,presets:R,presetsLoading:L,presetError:W,loadedPresetName:z,fetchPresets:q,savePreset:V,loadPreset:G,deletePreset:J}}(e.key),l=(0,_.useRef)(null),i=(0,_.useRef)(0),[o,c]=(0,_.useState)(!1),[d,u]=(0,_.useState)(null),[h,p]=(0,_.useState)(!1),[m,x]=(0,_.useState)(null),[g,f]=(0,_.useState)(null),[v,j]=(0,_.useState)("summary"),[w,N]=(0,_.useState)(""),[k,S]=(0,_.useState)(null),[$,C]=(0,_.useState)([]),[M,E]=(0,_.useState)(!1),[A,T]=(0,_.useState)([]),[F,P]=(0,_.useState)(""),[R,O]=(0,_.useState)(""),[L,I]=(0,_.useState)(""),[D,z]=(0,_.useState)(`${e.name} Copy`),[B,W]=(0,_.useState)(`${e.key}_copy`),[U,H]=(0,_.useState)(!1),[q,V]=(0,_.useState)(""),[G,J]=(0,_.useState)(1),[Y,K]=(0,_.useState)(!1),[X,Z]=(0,_.useState)("winrate"),[Q,ee]=(0,_.useState)([]),[et,ea]=(0,_.useState)(null),[es,en]=(0,_.useState)(""),[el,eo]=(0,_.useState)(null),[ec,ed]=(0,_.useState)(!1),[eu,eh]=(0,_.useState)(""),[ep,em]=(0,_.useState)(null),[ex,eg]=(0,_.useState)([]),[ef,eb]=(0,_.useState)(!1),[e_,ev]=(0,_.useState)(""),ey=(0,_.useMemo)(()=>{let t=(n.asset||"").toUpperCase().trim(),a=(n.tf||"").toLowerCase().trim(),s=(e.name||e.key||"").trim();return t&&a&&s?`${t}-${a} ${s}`:""},[n.asset,n.tf,e.name,e.key]),ej=(0,_.useMemo)(()=>!!n.presets.find(e=>e.name===ey),[n.presets,ey]),[ew,eN]=(0,_.useState)(!1),[ek,eS]=(0,_.useState)(""),[e$,eC]=(0,_.useState)(!1),[eM,eA]=(0,_.useState)(""),[eT,eF]=(0,_.useState)(null),[eP,eR]=(0,_.useState)([]),[eO,eL]=(0,_.useState)(null),[eI,eD]=(0,_.useState)({}),[ez,eB]=(0,_.useState)(["15m"]),[eW,eU]=(0,_.useState)({}),eH="bullish"===e.direction?"Bullish (long)":"bearish"===e.direction?"Bearish (short)":"Neutral",eq=n.result?.summary,eV=(0,_.useMemo)(()=>Array.isArray(eq?.signal_rows)?eq.signal_rows:[],[eq]),eG=(0,_.useMemo)(()=>eV.filter(e=>!String(e?.status||"").toLowerCase().startsWith("skipped_")),[eV]),eJ=Number(eq?.signal_rows_total??eV.length??0),eY=Math.max(0,eJ-eJ),eK=Number(eq?.signal_rows_page_count??Math.max(1,Math.ceil(eJ/50))),eX=Number(eq?.signal_rows_page??Math.min(Math.max(G,1),eK));(0,_.useEffect)(()=>{J(1)},[n.resultAt,n.running,n.asset,n.tf]),(0,_.useEffect)(()=>{eB([n.tf])},[n.tf]),(0,_.useEffect)(()=>{let e=String(eq?.signal_rows_token||""),t=Number(eq?.signal_rows_total||0),a=Array.isArray(eq?.signal_rows)&&eq.signal_rows.length>0;!e||t<=0||a||n.signalRowsLoading||n.loadSignalRowsPage(1,50,e)},[eq,n.signalRowsLoading,n.loadSignalRowsPage]);let eZ=(0,_.useMemo)(()=>{if(!n.result)return[];let e=Array.isArray(n.result.series_native)?n.result.series_native:[],t=Array.isArray(n.result.hourly)?n.result.hourly:[];return"native"===n.params.chart_resolution?e.length?e:t:t.length?t:e},[n.result,n.params.chart_resolution]),eQ=(0,_.useMemo)(()=>{let e={};for(let t of(eZ.length>0&&(e[n.tf]=eZ),Object.keys(eI))){let a=eI[t];Array.isArray(a)&&a.length>0&&(e[t]=a)}return e},[eZ,n.tf,eI]),e0=n.exists&&!n.result&&!n.running&&!n.loading,e1=async()=>{i.current=Date.now();let e=M?Array.from(new Set((A||[]).map(e=>
4String(e||"").trim()).filter(Boolean))):[];eD({}),eB([n.tf]),eU({}),await n.run({combine_with_pattern_keys:e.length>0?e:void 0,combine_with_pattern_key:e[0]||void 0}),a?.()};(0,_.useEffect)(()=>{let t=!1;return(async()=>{try{let a=await (0,er.authGetJson)("/api/patterns");if(!a?.ok||t)return;let s=(a.data||[]).filter(t=>t.has_strategy&&t.key!==e.key).map(e=>({key:e.key,name:e.name||e.key})).sort((e,t)=>e.name.localeCompare(t.name));C(s),O(e=>e&&s.some(t=>t.key===e)?e:s[0]?.key||""),P(e=>e&&s.some(t=>t.key===e)?e:s[0]?.key||""),T(e=>e.filter(e=>s.some(t=>t.key===e)))}catch{t||(C([]),O(""),P(""),T([]),E(!1))}})(),()=>{t=!0}},[e.key]),(0,_.useEffect)(()=>{z(`${e.name} Copy`),W(`${e.key}_copy`),V("")},[e.key,e.name]);let e2=async()=>{if(R)try{I("Loading…");let e=await (0,er.authGetJson)(`/api/patterns/${R}/strategy`);if(!e?.ok||!e?.data?.exists)throw Error("No strategy");let t=aH(e.data.params||{});n.setAllParams(t),e.data.asset&&n.setAsset(String(e.data.asset)),e.data.tf&&n.setTf(String(e.data.tf)),I("Loaded"),window.setTimeout(()=>I(""),1500)}catch(e){I(e?.message||"Load failed"),window.setTimeout(()=>I(""),2200)}},e5=async()=>{let t=String(D||"").trim(),s=String(B||"").trim();if(!t)return void V("Name required");try{H(!0),V("Duplicating…");let r=await (0,er.authPostJson)(`/api/patterns/${e.key}/strategy/duplicate`,{new_name:t,new_key:s||void 0,copy_last_backtest:!1});if(!r?.ok||!r?.data)throw Error(r?.error||"Duplicate failed");V(`Created ${r.data.name} (${r.data.key})`),C(e=>e.some(e=>e.key===r.data.key)?e:[{key:r.data.key,name:r.data.name},...e].sort((e,t)=>e.name.localeCompare(t.name))),a?.()}catch(e){V(e?.message||"Duplicate failed")}finally{H(!1),window.setTimeout(()=>V(e=>"Duplicating…"===e?"":e),1600)}},e4=n.params.selected_windows??["all"];(0,_.useEffect)(()=>{u(null),f(null),x(null),j("summary"),N(""),S(null)},[n.result]),(0,_.useEffect)(()=>{if(!eO)return;let e=window.requestAnimationFrame(()=>{l.current?.focusTime(eO.focusTime,14)});return()=>window.cancelAnimationFrame(e)},[eO]),(0,_.useEffect)(()=>{if(!eO)return;let e=e=>{"Escape"===e.key&&eL(null)};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[eO]);let e3=async()=>{if(d&&e?.key){p(!0),x(null),N(""),S(null);try{let t=await (0,er.authPostJson)(`/api/patterns/${e.key}/strategy/segment-analysis`,{asset:n.asset,tf:n.tf,selection:d});if(!t?.ok||!t?.data)throw Error(t?.error||"Insight failed");f(t.data),j("summary")}catch(e){x(e?.message||"Insight failed")}finally{p(!1)}}},e6=(e,t)=>{if(!e||"object"!=typeof e)return void N("No patch available.");let a={...n.params,...e};n.setAllParams(a);let s=t||"rule patch";N(`Applied patch: ${s}`),S({label:s,patch:e})},e8=(e,t)=>"winrate"===t?1e3*e.campaign_winrate_pct+10*e.winrate_pct+.001*e.pnl-5e-4*e.maxdd:e.pnl-.35*e.maxdd+100*e.campaign_winrate_pct,e9=async(t,a)=>{let s=aU(aH(t)),r=!!a?.includeSignalRows,l=Math.max(50,Math.min(500,Number(a?.signalRowsPageSize||250))),i=Array.isArray(a?.combineKeys)?Array.from(new Set((a?.combineKeys||[]).map(e=>String(e||"").trim()).filter(Boolean))):[],o=JSON.stringify({params:s,asset:n.asset,tf:a?.tfOverride||n.tf,combine_with_pattern_key:i[0]||void 0,combine_with_pattern_keys:i.length>0?i:void 0,persist:!1,include_trades:!1,include_signal_rows:r,signal_rows_page:1,signal_rows_page_size:l}),c=e=>new Promise(t=>window.setTimeout(t,e)),d=null;for(let t=0;t<3;t++)try{let t=await (0,er.authFetch)(`/api/patterns/${e.key}/strategy/backtest`,{method:"POST",headers:{"Content-Type":"application/json"},body:o});if(!t.ok){let e=await t.text();throw Error(`Backtest failed: ${t.status} ${e.slice(0,200)}`)}let a=await t.json();if(!a?.ok||!a?.data)throw Error(a?.error||"Backtest failed");return a.data}catch(e){d=e,t<2&&await c(400*(t+1))}throw d||Error("Grid scan backtest failed")},e7=async t=>{if(!e?.key||Y||n.running)return;let a=t?.objectiveOverride||X,s=Math.max(1,Math.min(24,Number(t?.topN||12)));K(!0),eo(null),ee([]),ea(null),en("Preparing baseline…");try{var r;let e,t,l,i={...e=aH(n.params),feature_lab_enabled:!0,feature_ret1_min_pct:0,feature_ret1_max_pct:0,feature_retn_lookback:Math.max(1,Math.floor(Number(e.feature_retn_lookback||4))),feature_retn_min_pct:0,feature_retn_max_pct:0,feature_atr14_min_pct:0,feature_atr14_max_pct:0,feature_ema20_gap_min_pct:0,feature_ema20_gap_max_pct:0,feature_wick_o
4pp_max:0,feature_vol_ratio_min:0,feature_vol_ratio_max:0,feature_rsi14_min:0,feature_rsi14_max:0},o=await e9(i),c=o?.summary||{},d={label:"baseline (feature filters off)",patch:{},score:0,campaign_winrate_pct:Number(c.campaign_winrate_pct||0),winrate_pct:Number(c.winrate_pct||0),pnl:Number(c.pnl||0),maxdd:Number(c.maxdd||0),end_equity:Number(c.end_equity||0),bets:Number(c.bets||0),campaigns:Number(c.campaigns||0)};d.score=e8(d,a),ea(d);let u=(r=i.feature_retn_lookback,t=Math.max(1,Math.floor(Number(r||4))),[{label:"ret1>=0.03%",patch:{feature_ret1_min_pct:.03}},{label:"ret1>=0.05%",patch:{feature_ret1_min_pct:.05}},{label:"ret1>=0.08%",patch:{feature_ret1_min_pct:.08}},{label:"ret1<=0.25%",patch:{feature_ret1_max_pct:.25}},{label:"ret1<=0.35%",patch:{feature_ret1_max_pct:.35}},{label:`ret${t}>=0.08%`,patch:{feature_retn_lookback:t,feature_retn_min_pct:.08}},{label:`ret${t}>=0.12%`,patch:{feature_retn_lookback:t,feature_retn_min_pct:.12}},{label:`ret${t}>=0.18%`,patch:{feature_retn_lookback:t,feature_retn_min_pct:.18}},{label:`ret${t}<=0.35%`,patch:{feature_retn_lookback:t,feature_retn_max_pct:.35}},{label:`ret${t}<=0.50%`,patch:{feature_retn_lookback:t,feature_retn_max_pct:.5}},{label:"atr14<=0.25%",patch:{feature_atr14_max_pct:.25}},{label:"atr14<=0.35%",patch:{feature_atr14_max_pct:.35}},{label:"atr14<=0.50%",patch:{feature_atr14_max_pct:.5}},{label:"oppWick<=0.35",patch:{feature_wick_opp_max:.35}},{label:"oppWick<=0.45",patch:{feature_wick_opp_max:.45}},{label:"oppWick<=0.60",patch:{feature_wick_opp_max:.6}},{label:"volRatio>=0.90",patch:{feature_vol_ratio_min:.9}},{label:"volRatio>=1.10",patch:{feature_vol_ratio_min:1.1}},{label:"volRatio<=1.40",patch:{feature_vol_ratio_max:1.4}},{label:"volRatio<=1.80",patch:{feature_vol_ratio_max:1.8}},{label:"RSI14 30..70",patch:{feature_rsi14_min:30,feature_rsi14_max:70}},{label:"RSI14 35..65",patch:{feature_rsi14_min:35,feature_rsi14_max:65}},{label:"EMA gap -0.20..0.30%",patch:{feature_ema20_gap_min_pct:-.2,feature_ema20_gap_max_pct:.3}},{label:"EMA gap -0.10..0.20%",patch:{feature_ema20_gap_min_pct:-.1,feature_ema20_gap_max_pct:.2}}]),h=[];for(let e=0;e<u.length;e++){let t=u[e];en(`Scanning ${e+1}/${u.length} \xb7 ${t.label}`);let s=aH({...i,...t.patch,feature_lab_enabled:!0}),r=await e9(s),n=r?.summary||{},l={label:t.label,patch:t.patch,score:0,campaign_winrate_pct:Number(n.campaign_winrate_pct||0),winrate_pct:Number(n.winrate_pct||0),pnl:Number(n.pnl||0),maxdd:Number(n.maxdd||0),end_equity:Number(n.end_equity||0),bets:Number(n.bets||0),campaigns:Number(n.campaigns||0)};l.score=e8(l,a),h.push(l)}let p=((l=[...h]).sort((e,t)=>"winrate"===a?t.campaign_winrate_pct!==e.campaign_winrate_pct?t.campaign_winrate_pct-e.campaign_winrate_pct:t.winrate_pct!==e.winrate_pct?t.winrate_pct-e.winrate_pct:t.pnl!==e.pnl?t.pnl-e.pnl:e.maxdd-t.maxdd:t.pnl!==e.pnl?t.pnl-e.pnl:e.maxdd!==t.maxdd?e.maxdd-t.maxdd:t.campaign_winrate_pct!==e.campaign_winrate_pct?t.campaign_winrate_pct-e.campaign_winrate_pct:t.winrate_pct-e.winrate_pct),l).slice(0,s);return ee(p),en(`Done: ${p.length} best candidates ready.`),p}catch(e){return eo(e?.message||"Grid scan failed"),en(""),[]}finally{K(!1)}},te=async()=>{if(e?.key&&!e$&&!Y&&!ec&&!n.running){eC(!0),eF(null),eR([]),eA("Auto-tuning: scanning strategy params for highest winrate…");try{Z("winrate");let e=await e7({objectiveOverride:"winrate",topN:6});if(!e||0===e.length){eF("No auto-tune candidates found in this window."),eA("");return}eR(e),eA(`Done: ${e.length} winrate-focused suggestions ready below.`)}catch(e){eF(e?.message||"Auto-tune failed"),eA("")}finally{eC(!1)}}};return(0,b.jsxs)("div",{className:"ps-overlay",onClick:t,children:[(0,b.jsxs)("div",{className:"ps-shell",onClick:e=>e.stopPropagation(),children:[(0,b.jsxs)("div",{className:"ps-header",children:[(0,b.jsxs)("div",{className:"ps-title",children:[(0,b.jsx)("span",{className:"ps-title-label",children:"Strategy"}),(0,b.jsx)("span",{className:"ps-title-name",children:e.name}),(0,b.jsx)("span",{className:`ps-dir-badge ${e.direction}`,children:eH})]}),(0,b.jsxs)("div",{className:"ps-meta",children:[n.resultAt&&!e0&&(0,b.jsxs)("span",{className:"ps-meta-line",children:["Last run · ",new Date(n.resultAt).toLocaleStr
4ing()]}),e0&&(0,b.jsx)("span",{className:"ps-meta-warn",children:"Stale — pattern updated, re-run backtest"}),n.error&&(0,b.jsx)("span",{className:"ps-meta-warn",children:n.error})]}),(0,b.jsx)("button",{className:"ps-close btn btn-ghost",onClick:t,title:"Close",children:"×"})]}),(0,b.jsxs)("div",{className:"ps-body",children:[(0,b.jsxs)("div",{className:"panel ps-controls",children:[(0,b.jsxs)("div",{className:"panel-header",children:[(0,b.jsx)("span",{className:"panel-title",children:"Parameters"}),(0,b.jsxs)("span",{className:"panel-subtitle",children:[e.key," · ",n.asset,"/",n.tf]})]}),(0,b.jsxs)("div",{className:"panel-body",children:[(0,b.jsxs)("div",{className:"ps-controls-grid",children:[(0,b.jsxs)(a3,{title:"Window",children:[(0,b.jsx)(a6,{label:"Asset",children:(0,b.jsx)("select",{className:"ps-select",value:n.asset,onChange:e=>n.setAsset(e.target.value),children:y.ASSET_OPTIONS.map(e=>(0,b.jsx)("option",{value:e.key,children:e.label},e.key))})}),(0,b.jsx)(a6,{label:"Timeframe",children:(0,b.jsx)("select",{className:"ps-select",value:n.tf,onChange:e=>n.setTf(e.target.value),children:y.TIMEFRAME_OPTIONS.map(e=>(0,b.jsx)("option",{value:e,children:e},e))})}),(0,b.jsx)(a6,{label:"Chart resolution",children:(0,b.jsxs)("select",{className:"ps-select",value:n.params.chart_resolution,onChange:e=>n.setParam("chart_resolution",e.target.value),children:[(0,b.jsx)("option",{value:"hourly",children:"hourly"}),(0,b.jsx)("option",{value:"native",children:"native"})]})}),(0,b.jsxs)("div",{className:"ps-field-wide",children:[(0,b.jsx)("span",{className:"field-label",children:"Windows"}),(0,b.jsx)("div",{className:"ps-chips",children:aZ.map(e=>(0,b.jsx)("button",{type:"button",className:`ps-chip${e4.includes(e)?" active":""}`,onClick:()=>(e=>{let t=n.params.selected_windows??["all"];if("all"===e)return void n.setParam("selected_windows",["all"]);let a=t.filter(e=>"all"!==e);if(a.includes(e)){let t=a.filter(t=>t!==e);n.setParam("selected_windows",t.length?t:["all"])}else n.setParam("selected_windows",[...a,e])})(e),children:e},e))})]})]}),(0,b.jsxs)(a3,{title:"Sizing",children:[(0,b.jsx)(a6,{label:"Capital (USD)",children:(0,b.jsx)("input",{className:"ps-input",type:"number",value:n.params.capital_usd,onChange:e=>n.setParam("capital_usd",Number(e.target.value))})}),(0,b.jsx)(a6,{label:"Mode",children:(0,b.jsxs)("select",{className:"ps-select",value:n.params.base_mode,onCh
4ange:e=>n.setParam("base_mode",e.target.value),children:[(0,b.jsx)("option",{value:"fixed",children:"Fixed USD"}),(0,b.jsx)("option",{value:"percent",children:"% of equity"})]})}),(0,b.jsx)(a6,{label:"Base USD",children:(0,b.jsx)("input",{className:"ps-input",type:"number",value:n.params.base_usd,disabled:"fixed"!==n.params.base_mode,onChange:e=>n.setParam("base_usd",Number(e.target.value))})}),(0,b.jsx)(a6,{label:"Base %",children:(0,b.jsx)("input",{className:"ps-input",type:"number",step:"0.1",value:n.params.base_pct_percent,disabled:"percent"!==n.params.base_mode,onChange:e=>n.setParam("base_pct_percent",Number(e.target.value))})}),(0,b.jsx)(a6,{label:"Cap (USD; 0=off)",children:(0,b.jsx)("input",{className:"ps-input",type:"number",value:n.params.base_cap_usd,onChange:e=>n.setParam("base_cap_usd",Number(e.target.value))})}),(0,b.jsx)(a6,{label:"Fee bps / side",children:(0,b.jsx)("input",{className:"ps-input",type:"number",step:"0.5",value:n.params.fee_bps_per_side,onChange:e=>n.setParam("fee_bps_per_side",Number(e.target.value))})})]}),(0,b.jsxs)(a3,{title:"Take profit / Stop loss",children:[(0,b.jsx)(a6,{label:"TP %",children:(0,b.jsx)("input",{className:"ps-input",type:"number",step:"0.1",value:n.params.take_profit_percent,onChange:e=>n.setParam("take_profit_percent",Number(e.target.value))})}),(0,b.jsx)(a6,{label:"TP fixed USD",children:(0,b.jsx)("input",{className:"ps-input",type:"number",step:"0.1",value:n.params.take_profit_fixed_usd,onChange:e=>n.setParam("take_profit_fixed_usd",Number(e.target.value))})}),(0,b.jsx)(a6,{label:"TP after USD",children:(0,b.jsx)("input",{className:"ps-input",type:"number",step:"0.1",value:n.params.take_profit_after_usd,onChange:e=>n.setParam("take_profit_after_usd",Number(e.target.value))})}),(0,b.jsx)(a6,{label:"SL %",children:(0,b.jsx)("input",{className:"ps-input",type:"number",step:"0.1",value:n.params.stop_loss_percent,onChange:e=>n.setParam("stop_loss_percent",Number(e.target.value))})}),(0,b.jsx)(a6,{label:"Max hold bars",children:(0,b.jsx)("input",{className:"ps-input",type:"number",min:0,value:n.params.max_hold_bars,onChange:e=>n.setParam("max_hold_bars",Number(e.target.value))})})]}),(0,b.jsxs)(a3,{title:"Topup / rebalance",children:[(0,b.jsx)(a6,{label:"Mode",children:(0,b.jsxs)("select",{className:"ps-select",value:n.params.topup_mode,onChange:e=>n.setParam("topup_mode",e.target.value),children:[(0,b.jsx)("option",{value:"off",children:"Off"}),(0,b.jsx)("option",{value:"percent",children:"Percent"}),(0,b.jsx)("option",{value:"back_to_initial_cap",children:"Back to initial cap"})]})}),(0,b.jsx)(a6,{label:"Drawdown %",children:(0,b.jsx)("input",{className:"ps-input",type:"number",step:"1",value:n.params.topup_drawdown_percent,onChange:e=>n.setParam("topup_drawdown_percent",Number(e.target.value))})}),(0,b.jsx)(a6,{label:"Topup %",children:(0,b.jsx)("input",{className:"ps-input",type:"number",step:"1",value:n.params.topup_percent,onChange:e=>n.setParam("topup_percent",Number(e.target.value))})})]}),(0,b.jsxs)(a3,{title:"Fill price",children:[(0,b.jsx)(a6,{label:"Min",children:(0,b.jsx)("input",{className:"ps-input",type:"number",step:"0.01",value:n.params.fill_price_min,onChange:e=>n.setParam("fill_price_min",Number(e.target.value))})}),(0,b.jsx)(a6,{label:"Max",children:(0,b.jsx)("input",{className:"ps-input",type:"number",step:"0.01",value:n.params.fill_price_max,onChange:e=>n.setParam("fill_price_max",Number(e.target.value))})}),(0,b.jsx)(a6,{label:"Mode",children:(0,b.jsxs)("select",{className:"ps-select",value:n.params.fill_price_mode,onCh
4ange:e=>n.setParam("fill_price_mode",e.target.value),children:[(0,b.jsx)("option",{value:"variation",children:"variation"}),(0,b.jsx)("option",{value:"fixed_avg",children:"fixed_avg"})]})}),(0,b.jsx)(a6,{label:"Fill source",children:(0,b.jsxs)("select",{className:"ps-select",value:n.params.fill_source,onChange:e=>n.setParam("fill_source",e.target.value),children:[(0,b.jsx)("option",{value:"synthetic",children:"synthetic"}),(0,b.jsx)("option",{value:"clob_history",children:"clob_history"})]})}),(0,b.jsx)(a6,{label:"CLOB apply on",children:(0,b.jsxs)("select",{className:"ps-select",value:n.params.clob_apply_on,onChange:e=>n.setParam("clob_apply_on",e.target.value),disabled:"clob_history"!==n.params.fill_source,children:[(0,b.jsx)("option",{value:"all_steps",children:"all_steps"}),(0,b.jsx)("option",{value:"step1_only",children:"step1_only"})]})}),(0,b.jsx)(a6,{label:"Exclude unfilled step1",children:(0,b.jsxs)("select",{className:"ps-select",value:n.params.clob_exclude_unfilled?"true":"false",onChange:e=>n.setParam("clob_exclude_unfilled","true"===e.target.value),disabled:"clob_history"!==n.params.fill_source,children:[(0,b.jsx)("option",{value:"true",children:"true"}),(0,b.jsx)("option",{value:"false",children:"false"})]})}),(0,b.jsx)(a6,{label:"CLOB fidelity (min)",children:(0,b.jsx)("input",{className:"ps-input",type:"number",min:1,step:1,value:n.params.clob_fidelity_minutes,onChange:e=>n.setParam("clob_fidelity_minutes",Number(e.target.value)),disabled:"clob_history"!==n.params.fill_source})}),(0,b.jsx)(a6,{label:"Ladder fill min",children:(0,b.jsx)("input",{className:"ps-input",type:"number",step:"0.01",value:n.params.ladder_fill_price_min,onChange:e=>n.setParam("ladder_fill_price_min",Number(e.target.value)),disabled:"clob_history"!==n.params.fill_source||"step1_only"!==n.params.clob_apply_on})}),(0,b.jsx)(a6,{label:"Ladder fill max",children:(0,b.jsx)("input",{className:"ps-input",type:"number",step:"0.01",value:n.params.ladder_fill_price_max,onChange:e=>n.setParam("ladder_fill_price_max",Number(e.target.value)),disabled:"clob_history"!==n.params.fill_source||"step1_only"!==n.params.clob_apply_on})}),(0,b.jsx)(a6,{label:"Ladder fill mode",children:(0,b.jsxs)("select",{className:"ps-select",value:n.params.ladder_fill_price_mode,onCh
4ange:e=>n.setParam("ladder_fill_price_mode",e.target.value),disabled:"clob_history"!==n.params.fill_source||"step1_only"!==n.params.clob_apply_on,children:[(0,b.jsx)("option",{value:"variation",children:"variation"}),(0,b.jsx)("option",{value:"fixed_avg",children:"fixed_avg"})]})})]}),(0,b.jsx)(a3,{title:"Ladder",children:(0,b.jsx)(a5,{label:"Ladder (csv)",value:n.params.ladder,format:e=>e.join(","),parse:e=>a2(e),validate:e=>e.length>0&&e.every(e=>e>=0)&&e.some(e=>e>0),onCommit:e=>n.setParam("ladder",e)})}),(0,b.jsxs)(a3,{title:"Streak / exact (advanced)",children:[(0,b.jsx)(a6,{label:"Streak override",children:(0,b.jsx)("input",{className:"ps-input",type:"number",min:0,value:n.params.streak_override,onChange:e=>n.setParam("streak_override",Number(e.target.value))})}),(0,b.jsx)(a6,{label:"Streak min %",children:(0,b.jsx)("input",{className:"ps-input",type:"number",step:"0.001",value:n.params.streak_move_min_pct,onChange:e=>n.setParam("streak_move_min_pct",Number(e.target.value))})}),(0,b.jsx)(a6,{label:"Streak max %",children:(0,b.jsx)("input",{className:"ps-input",type:"number",step:"0.001",value:n.params.streak_move_max_pct,onChange:e=>n.setParam("streak_move_max_pct",Number(e.target.value))})}),(0,b.jsx)(a6,{label:"Exact override",children:(0,b.jsxs)("select",{className:"ps-select",value:n.params.exact_override_enabled?"on":"off",onChange:e=>n.setParam("exact_override_enabled","on"===e.target.value),children:[(0,b.jsx)("option",{value:"off",children:"off"}),(0,b.jsx)("option",{value:"on",children:"on"})]})}),(0,b.jsx)(a6,{label:"Exact value",children:(0,b.jsxs)("select",{className:"ps-select",value:n.params.exact_override_value?"true":"false",onChange:e=>n.setParam("exact_override_value","true"===e.target.value),disabled:!n.params.exact_override_enabled,children:[(0,b.jsx)("option",{value:"true",children:"true"}),(0,b.jsx)("option",{value:"false",children:"false"})]})})]}),(0,b.jsxs)(a3,{title:"Feature Lab (WR Filters)",children:[(0,b.jsx)(a6,{label:"Enabled",children:(0,b.jsxs)("select",{className:"ps-select",value:n.params.feature_lab_enabled?"on":"off",onChange:e=>n.setParam("feature_lab_enabled","on"===e.target.value),children:[(0,b.jsx)("option",{value:"off",children:"off"}),(0,b.jsx)("option",{value:"on",children:"on"})]})}),(0,b.jsx)(a6,{label:"Ret1 min %",children:(0,b.jsx)("input",{className:"ps-input",type:"number",step:"0.001",value:n.params.feature_ret1_min_pct,onChange:e=>n.setParam("feature_ret1_min_pct",Number(e.target.value)),disabled:!n.params.feature_lab_enabled})}),(0,b.jsx)(a6,{label:"Ret1 max %",children:(0,b.jsx)("input",{className:"ps-input",type:"number",step:"0.001",value:n.params.feature_ret1_max_pct,onChange:e=>n.setParam("feature_ret1_max_pct",Number(e.target.value)),disabled:!n.params.feature_lab_enabled})}),(0,b.jsx)(a6,{label:"RetN lookback",children:(0,b.jsx)("input",{className:"ps-input",type:"number",min:1,step:1,value:n.params.feature_retn_lookback,onChange:e=>n.setParam("feature_retn_lookback",Math.max(1,Math.floor(Number(e.target.value)))),disabled:!n.params.feature_lab_enabled})}),(0,b.jsx)(a6,{label:"RetN min %",children:(0,b.jsx)("input",{className:"ps-input",type:"number",step:"0.001",value:n.params.feature_retn_min_pct,onChange:e=>n.setParam("feature_retn_min_pct",Number(e.target.value)),disabled:!n.params.feature_lab_enabled})}),(0,b.jsx)(a6,{label:"RetN max %",children:(0,b.jsx)("input",{className:"ps-input",type:"number",step:"0.001",value:n.params.feature_retn_max_pct,onChange:e=>n.setParam("feature_retn_max_pct",Number(e.target.value)),disabled:!n.params.feature_lab_enabled})}),(0,b.jsx)(a6,{label:"ATR14 min %",children:(0,b.jsx)("input",{className:"ps-input",type:"number",step:"0.001",value:n.params.feature_atr14_min_pct,onChange:e=>n.setParam("feature_atr14_min_pct",Number(e.target.value)),disabled:!n.params.feature_lab_enabled})}),(0,b.jsx)(a6,{label:"ATR14 max %",children:(0,b.jsx)("input",{className:"ps-input",type:"number",step:"0.001",value:n.params.feature_atr14_max_pct,onChange:e=>n.setParam("feature_atr14_max_pct",Number(e.target.value)),disabled:!n.params.feature_lab_enabled})}),(0,b.jsx)(a6,{label:"EMA20 gap min %",children:(0,b.jsx)("input",{className:"ps-input",type:"number",step:"0.001",value:n.params.feature_ema20_gap_min_pct,onChange:e=>n.setParam("feature_ema20_gap_min_pct",Number(e.target.value)),disabled:!n.params.feature_lab_enabled})}),(0,b.jsx)(a6,{label:"EMA20 gap max %",children:(0,b.jsx)("input",{className:"ps-input",type:"number",step:"0.001",value:n.params.feature_ema20_gap_max_pct,onChange:e=>n.setParam("feature_ema20_gap_max_pct",Number(e.target.value)),disabled:!n.params.feature_lab_enabled})}),(0,b.jsx)(a6,{label:"Opp wick max ratio",children:(0,b.jsx)("input",{className:"ps-input",type:"number",step:"0.01",value:n.params.feature_wick_o
4pp_max,onChange:e=>n.setParam("feature_wick_opp_max",Number(e.target.value)),disabled:!n.params.feature_lab_enabled})}),(0,b.jsx)(a6,{label:"Vol ratio min",children:(0,b.jsx)("input",{className:"ps-input",type:"number",step:"0.01",value:n.params.feature_vol_ratio_min,onChange:e=>n.setParam("feature_vol_ratio_min",Number(e.target.value)),disabled:!n.params.feature_lab_enabled})}),(0,b.jsx)(a6,{label:"Vol ratio max",children:(0,b.jsx)("input",{className:"ps-input",type:"number",step:"0.01",value:n.params.feature_vol_ratio_max,onChange:e=>n.setParam("feature_vol_ratio_max",Number(e.target.value)),disabled:!n.params.feature_lab_enabled})}),(0,b.jsx)(a6,{label:"RSI14 min",children:(0,b.jsx)("input",{className:"ps-input",type:"number",step:"0.1",value:n.params.feature_rsi14_min,onChange:e=>n.setParam("feature_rsi14_min",Number(e.target.value)),disabled:!n.params.feature_lab_enabled})}),(0,b.jsx)(a6,{label:"RSI14 max",children:(0,b.jsx)("input",{className:"ps-input",type:"number",step:"0.1",value:n.params.feature_rsi14_max,onChange:e=>n.setParam("feature_rsi14_max",Number(e.target.value)),disabled:!n.params.feature_lab_enabled})})]}),(0,b.jsxs)(a3,{title:"Confidence (Legacy)",children:[(0,b.jsx)(a6,{label:"Mode",children:(0,b.jsxs)("select",{className:"ps-select",value:n.params.confidence_override_mode,onChange:e=>n.setParam("confidence_override_mode",e.target.value),children:[(0,b.jsx)("option",{value:"default",children:"default"}),(0,b.jsx)("option",{value:"on",children:"on"}),(0,b.jsx)("option",{value:"off",children:"off"})]})}),(0,b.jsx)(a6,{label:"Multiplier",children:(0,b.jsx)("input",{className:"ps-input",type:"number",step:"0.1",value:n.params.confidence_multiplier,onChange:e=>n.setParam("confidence_multiplier",Number(e.target.value))})}),(0,b.jsx)(a6,{label:"Min score",children:(0,b.jsx)("input",{className:"ps-input",type:"number",step:"0.05",value:n.params.confidence_min_score,onChange:e=>n.setParam("confidence_min_score",Number(e.target.value))})}),(0,b.jsx)(a6,{label:"ATR cap",children:(0,b.jsx)("input",{className:"ps-input",type:"number",step:"0.0005",value:n.params.confidence_atr_cap,onChange:e=>n.setParam("confidence_atr_cap",Number(e.target.value))})}),(0,b.jsx)(a6,{label:"Ret1 ext",children:(0,b.jsx)("input",{className:"ps-input",type:"number",step:"0.0005",value:n.params.confidence_ret1_ext,onChange:e=>n.setParam("confidence_ret1_ext",Number(e.target.value))})}),(0,b.jsx)(a6,{label:"EMA ext",children:(0,b.jsx)("input",{className:"ps-input",type:"number",step:"0.0005",value:n.params.confidence_ema_ext,onChange:e=>n.setParam("confidence_ema_ext",Number(e.target.value))})}),(0,b.jsx)(a6,{label:"M1 ret ext",children:(0,b.jsx)("input",{className:"ps-input",type:"number",step:"0.0005",value:n.params.confidence_m1_ret_ext,onChange:e=>n.setParam("confidence_m1_ret_ext",Number(e.target.value))})}),(0,b.jsx)(a6,{label:"Wick opp mode",children:(0,b.jsxs)("select",{className:"ps-select",value:n.params.confidence_require_wick_opp_mode,onChange:e=>n.setParam("confidence_require_wick_opp_mode",e.target.value),children:[(0,b.jsx)("option",{value:"default",children:"default"}),(0,b.jsx)("option",{value:"on",children:"on"}),(0,b.jsx)("option",{value:"off",children:"off"})]})}),(0,b.jsx)(a6,{label:"Wick opp cap",children:(0,b.jsx)("input",{className:"ps-input",type:"number",step:"0.01",value:n.params.confidence_wick_opp_cap,onChange:e=>n.setParam("confidence_wick_opp_cap",Number(e.target.value))})})]}),(0,b.jsxs)(a3,{title:"Confidence V2 (Sizing)",children:[(0,b.jsx)(a6,{label:"Mode",children:(0,b.jsxs)("select",{className:"ps-select",value:n.params.confidence_sizing_mode,onChange:e=>n.setParam("confidence_sizing_mode",e.target.value),children:[(0,b.jsx)("option",{value:"off",children:"off"}),(0,b.jsx)("option",{value:"exact",children:"exact"}),(0,b.jsx)("option",{value:"ranges",children:"ranges"})]})}),(0,b.jsx)(a6,{label:"Denominator",children:(0,b.jsx)("input",{className:"ps-input",type:"number",min:1e-6,step:"1",value:n.params.confidence_sizing_denominator,onChange:e=>n.setParam("confidence_sizing_denominator",Number(e.target.value))})}),(0,b.jsx)(a6,{label:"Range tiers (confidence% = size%)",children:(0,b.jsx)("input",{className:"ps-input",type:"text",value:n.params.confidence_sizing_tiers_text,onChange:e=>n.setParam("confidence_sizing_tiers_text",e.target.value),placeholder:"0%=50%,50%=100%,80%=150%",disabled:"ranges"!==n.params.confidence_sizing_mode})})]}),(0,b.jsxs)(a3,{title:"Direction",children:[(0,b.jsx)(a6,{label:"Side override",children:(0,b.jsxs)("select",{className:"ps-select",value:n.params.pattern_side_override,onChange:e=>n.setParam("pattern_side_override",e.target.value),children:[(0,b.jsxs)("option",{value:"default",children:["Default (",eH,")"]}),(0,b.jsx)("option",{value:"up_streak_only",children:"Up streak only"}),(0,b.jsx)("option",{value:"down_streak_only",children:"Down streak only"}),(0,b.jsx)("option",{value:"both",children:"Both"})]})}),(0,b.jsx)(a6,{label:"Entry timing",children:(0,b.jsxs)("select",{className:"ps-select",value:n.params.entry_timing_override,onChange:e=>n.setParam("entry_timing_override",e.target.value),children:[(0,b.jsx)("option",{value:"default",children:"default"}),(0,b.jsx)("option",{value:"after_confirmation_close",children:"after_confirmation_close"}),(0,b.jsx)("option",{value:"next_candle_close",children:"next_candle_close"})]})}),(0,b.jsx)(a6,{label:"Direction rule",children:(0,b.jsxs)("select",{className:"ps-select",value:n.params.direction_rule_override,onChange:e=>n.setParam("direction_rule_override",e.target.value),children:[(0,b.jsx)("option",{value:"default",children:"default"}),(0,b.jsx)("option",{value:"follow_confirmation",children:"follow_confirmation"}),(0,b.jsx)("option",{value:"opposite_confirmation",children:"opposite_confirmation"})]})}),(0,b.jsx)(a6,{label:"Signal engine",children:(0,b.jsxs)("select",{className:"ps-select",value:n.params.signal_engine_override,onChange:e=>n.setParam("signal_engine_override",e.target.value),children:[(0,b.jsx)("option",{value:"auto",children:"auto"}),(0,b.jsx)("option",{value:"streak_parity",children:"streak_parity"}),(0,b.jsx)("option",{value:"calc_py",children:"calc_py"})]})}),(0,b.jsx)(a6,{label:"Neutral fallback side",children:(0,b.jsxs)("select",{className:"ps-select",value:n.params.neutral_default_side_override,onChange:e=>n.setParam("neutral_default_side_override",e.target.value),children:[(0,b.jsx)("option",{value:"auto",children:"auto"}),(0,b.jsx)("option",{value:"up",children:"up"}),(0,b.jsx)("option",{value:"down",children:"down"})]})})]}),(0,b.jsx)(a3,{title:"Weekday multipliers (Mon..Sun)",children:(0,b.jsx)(a5,{label:"Multipliers (csv, 7)",value:n.params.weekday_base_multipliers,format:e=>e.join(","),parse:e=>a2(e),validate:e=>7===e.length&&e.every(e=>e>=0),onCommit:e=>n.setParam("weekday_base_multipliers",e)})}),(0,b.jsxs)(a3,{title:"Choppy week regime",children:[(0,b.jsx)(a6,{label:"Enabled",children:(0,b.jsxs)("select",{className:"ps-select",value:n.params.choppy_week_enabled?"on":"off",onChange:e=>n.setParam("choppy_week_enabled","on"===e.target.value),children:[(0,b.jsx)("option",{value:"off",children:"off"}),(0,b.jsx)("option",{value:"on",children:"on"})]})}),(0,b.jsx)(a6,{label:"Score threshold",children:(0,b.jsx)("input",{className:"ps-input",type:"number",min:0,max:3,value:n.params.choppy_week_score_threshold,onChange:e=>n.setParam("choppy_week_score_threshold",Number(e.target.value))})}),(0,b.jsx)(a5,{label:"Day mults Thu..Sun (csv, 4)",value:n.params.choppy_week_day_multipliers,format:e=>e.join(","),parse:e=>a2(e),validate:e=>4===e.length&&e.every(e=>e>=0),onCommit:e=>n.setParam("choppy_week_day_multipliers",e)}),(0,b.jsx)(a6,{label:"BTC ret_sum thr",children:(0,b.jsx)("input",{className:"ps-input",type:"number",step:"0.0001",value:n.params.choppy_week_btc_ret_sum_threshold,onChange:e=>n.setParam("choppy_week_btc_ret_sum_threshold",Number(e.target.value))})}),(0,b.jsx)(a6,{label:"BTC wick/body thr",children:(0,b.jsx)("input",{className:"ps-input",type:"number",step:"0.0001",value:n.params.choppy_week_btc_wick_body_threshold,onChange:e=>n.setParam("choppy_week_btc_wick_body_threshold",Number(e.target.value))})}),(0,b.jsx)(a6,{label:"Vol ratio thr",children:(0,b.jsx)("input",{className:"ps-input",type:"number",step:"0.0001",value:n.params.choppy_week_vol_ratio_threshold,onChange:e=>n.setParam("choppy_week_vol_ratio_threshold",Number(e.target.value))})})]}),(0,b.jsxs)(a3,{title:"Time gates",children:[(0,b.jsx)(a5,{label:"Hours ET (csv | default | all)",value:n.params.hours_et,format:e=>"default"===e||"all"===e?e:Array.isArray(e)?e.join(","):"default",parse:e=>(function(e){let t=e.trim().toLowerCase();if(!t||"default"===t)return"default";if("all"===t)return"all";let a=a2(e);
4if(!a)return null;for(let e of a)if(!Number.isInteger(e)||e<0||e>23)return null;return[...new Set(a)].sort((e,t)=>e-t)})(e),onCommit:e=>n.setParam("hours_et",e)}),(0,b.jsx)(a5,{label:"Months (csv | all)",value:n.params.months,format:e=>"all"===e?"all":Array.isArray(e)?e.join(","):"all",parse:e=>(function(e){let t=e.trim().toLowerCase();if(!t||"all"===t)return"all";let a=a2(e);if(!a)return null;for(let e of a)if(!Number.isInteger(e)||e<1||e>12)return null;return[...new Set(a)].sort((e,t)=>e-t)})(e),onCommit:e=>n.setParam("months",e)})]}),(0,b.jsx)(a3,{title:"Pair",children:(0,b.jsx)(a6,{label:"ETH multiplier",children:(0,b.jsx)("input",{className:"ps-input",type:"number",step:"0.1",value:n.params.pair_eth_multiplier,onChange:e=>n.setParam("pair_eth_multiplier",Number(e.target.value))})})})]}),(0,b.jsxs)("div",{className:"ps-actions",children:[(0,b.jsxs)("div",{className:"ps-copy-tools",children:[(0,b.jsx)("span",{className:"ps-copy-label",children:"Combine strategy"}),(0,b.jsxs)("select",{className:"ps-select ps-copy-select",value:M?"on":"off",onChange:e=>E("on"===e.target.value),children:[(0,b.jsx)("option",{value:"off",children:"off"}),(0,b.jsx)("option",{value:"on",children:"on"})]}),(0,b.jsx)("select",{className:"ps-select ps-copy-select",value:F,onChange:e=>P(e.target.value),disabled:!M||0===$.length,children:0===$.length?(0,b.jsx)("option",{value:"",children:"No other strategy"}):$.map(e=>(0,b.jsx)("option",{value:e.key,children:e.name},`combine-${e.key}`))}),(0,b.jsx)("button",{className:"btn btn-ghost",type:"button",onClick:()=>{let e=String(F||"").trim();e&&T(t=>t.includes(e)?t:[...t,e])},disabled:!M||!F,children:"Add"}),(0,b.jsx)("span",{className:`ps-copy-status${M?" show":""}`,children:M?A.length>0?`A + ${A.length} strategy${A.length>1?"ies":""}`:"A only (no secondary selected)":"single strategy"}),M&&A.length>0&&(0,b.jsx)("div",{className:"ps-inline-tags",children:A.map(e=>{let t=$.find(t=>t.key===e),a=t?t.name:e;return(0,b.jsxs)("button",{type:"button",className:"btn btn-ghost",onClick:()=>{T(t=>t.filter(t=>t!==e))},title:"Remove from combine set",children:[a," ×"]},`combine-chip-${e}`)})})]}),(0,b.jsxs)("div",{className:"ps-copy-tools",children:[(0,b.jsx)("span",{className:"ps-copy-label",children:"Copy exact params from"}),(0,b.jsx)("select",{className:"ps-select ps-copy-select",value:R,onChange:e=>O(e.target.value),disabled:0===$.length,children:0===$.length?(0,b.jsx)("option",{value:"",children:"No other strategy"}):$.map(e=>(0,b.jsx)("option",{value:e.key,children:e.name},e.key))}),(0,b.jsx)("button",{className:"btn btn-ghost",type:"button",onClick:e2,disabled:!R||0===$.length,children:"Apply"}),(0,b.jsx)("span",{className:`ps-copy-status${L?" show":""}`,children:L||"idle"})]}),(0,b.jsxs)("div",{className:"ps-copy-tools",style:{width:"100%",marginTop:8},children:[(0,b.jsx)("span",{className:"ps-copy-label",children:"Duplicate strategy as"}),(0,b.jsx)("input",{className:"ps-input",style:{minWidth:220,maxWidth:320},value:D,onChange:e=>z(e.target.value),placeholder:"New pattern name"}),(0,b.jsx)("input",{className:"ps-input",style:{minWidth:220,maxWidth:320},value:B,onChange:e=>W(e.target.value),placeholder:"new_pattern_key (optional)"}),(0,b.jsx)("button",{className:"btn btn-ghost",type:"button",onClick:e5,disabled:U||!D.trim(),children:U?"Duplicating…":"Duplicate"}),(0,b.jsx)("span",{className:`ps-copy-status${q?" show":""}`,children:q||"idle"})]}),(0,b.jsxs)("select",{className:"ps-select",value:n.loadedPresetName??"",onChange:e=>{let t=e.target.value;t&&n.loadPreset(t)},disabled:n.presetsLoading||0===n.presets.length,title:0===n.presets.length?"No presets saved yet":"Load a saved param preset",children:[(0,b.jsx)("option",{value:"",children:n.presetsLoading?"Loading presets…":0===n.presets.length?"No presets":`Choose preset…`}),n.presets.map(e=>{let t="number"==typeof e.last_backtest?.summary?.campaign_winrate_pct?e.last_backtest.summary.campaign_winrate_pct:"number"==typeof e.last_backtest?.summary?.winrate_pct?e.last_backtest.summary.winrate_pct:null,a="number"==typeof e.last_backtest?.summary?.pnl?e.last_backtest.summary.pnl:null,s=null!=t&&null!=a?` — ${t.toFixed(0)}% \xb7 ${a>=0?"+":""}$${Math.round(a)}`:" — no backtest yet";return(0,b.jsxs)("option",{value:e.name,children:[e.name,s]},e.name)})]}),n.loadedPresetName&&(()=>{let e,t=n.presets.find(e=>e.name===n.loadedPresetName);if(!t)return null;let a=t.last_backtest_at;if(a){let t=Math.max(0,(Date.now()-new Date(a).getTime())/1e3);e=t<60?`last backtested ${Math.floor(t)}s ago`:t<3600?`last backtested ${Math.floor(t/60)}m ago`:t<86400?`last backtested ${Math.floor(t/3600)}h ago`:`last backtested ${Math.floor(t/86400)}d ago`}else e="no backtest yet — Run will attach the first result";return(0,b.jsxs)("span",{style:{fontSize:"11px",color:"var(--text-secondary)",marginLeft:4},children:["✓ ",n.loadedPresetName," · ",e]})})(),ey&&(0,b.jsxs)("button",{className:"btn btn-ghost",type:"button",onClick:()=>{ey&&n.savePreset(ey)},disabled:n.running,title:ej?`Overwrite preset "${ey}" with the current form params`:`Create new preset "${ey}" from the current form params`,children:[ej?"Update preset":"Save preset",(0,b.jsxs)("span",{style:{color:"var(--text-secondary)",marginLeft:4,fontWeight:400},children:["→ ",ey]})]}),(0,b.jsx)("button",{className:"btn btn-ghost",type:"button",onClick:()=>{ev(ey||""),eb(!0)},disabled:n.running,title:"Save the current params as a new named preset (with a custom name)",children:"Save as new…"}),n.presets.length>0&&(0,b.jsx)("button",{className:"btn btn-ghost",type:"button",onClick:()=>eN(!0),disabled:n.running,title:"Delete a saved preset",children:"Delete preset…"}),(0,b.jsx)("button",{className:"btn btn-ghost",onClick:n.resetDefaults,children:"Reset defaults"}),(0,b.jsx)("button",{className:"btn",onClick:n.save,disabled:n.saving||n.running,children:(0,b.jsx)(aN,{busy:n.saving,label:"Save params",busyLabel:"Saving…"})}),(0,b.jsx)("button",{className:"btn btn-ghost",onClick:n.clearBacktestCache,disabled:n.cacheClearing||n.running,children:(0,b.jsx)(aN,{busy:n.cacheClearing,label:"Clear cache",busyLabel:"Clearing cache…"})}),(0,b.jsx)("button",{className:"btn btn-primary",onClick:e1,disabled:n.running,children:(0,b.jsx)(aN,{busy:n.running,label:"Run backtest",busyLabel:"Running backtest…"})}),(0,b.jsx)("button",{className:"btn btn-primary",type:"button",onClick:te,disabled:e$||Y||ec||n.running,title:"One-click scan to find highest winrate setups",children:e$?"Auto-tuning…":"Auto-tune winrate"}),ef&&(0,b.jsxs)("div",{className:"ps-copy-tools",style:{width:"100%",marginTop:8},children:[(0,b.jsx)("span",{className:"ps-copy-label",children:"New preset"}),(0,b.jsx)("input",{className:"ps-input",type:"text",placeholder:"e.g. aggressive, conservative…",value:e_,onChange:e=>ev(e.target.value),maxLength:80,autoFocus:!0,onKeyDown:e=>{"Enter"===e.key&&e_.trim()?(n.savePreset(e_.trim()),ev(""),eb(!1)):"Escape"===e.key&&(ev(""),eb(!1))}}),(0,b.jsx)("button",{className:"btn btn-primary",type:"button",onClick:()=>{let e=e_.trim();e&&(n.savePreset(e),ev(""),eb(!1))},disabled:!e_.trim(),children:"Save"}),(0,b.jsx)("button",{className:"btn btn-ghost",type:"button",onClick:()=>{ev(""),eb(!1)},children:"Cancel"})]}),ew&&(0,b.jsxs)("div",{className:"ps-copy-tools",style:{width:"100%",marginTop:8},children:[(0,b.jsx)("span",{className:"ps-copy-label",children:"Delete preset"}),(0,b.jsxs)("select",{className:"ps-select",value:ek,onChange:e=>eS(e.target.value),children:[(0,b.jsx)("option",{value:"",children:"Pick a preset…"}),n.presets.map(e=>(0,b.jsx)("option",{value:e.name,children:e.name},e.name))]}),(0,b.jsx)("button",{className:"btn",type:"button",onClick:()=>{!ek||confirm(`Delete preset "${ek}"? This cannot be undone.`)&&(n.deletePreset(ek),eS(""),eN(!1))},disabled:!ek,children:"Delete"}),(0,b.jsx)("button",{className:"btn btn-ghost",type:"button",onClick:()=>{eS(""),eN(!1)},children:"Cancel"})]}),n.presetError?(0,b.jsx)("div",{className:"ps-meta-warn",children:n.presetError}):null,eM?(0,b.jsx)("div",{className:"ps-copy-status show",children:eM}):null,eT?(0,b.jsx)("div",{className:"ps-meta-warn",children:eT}):null]})]})]}),n.result?.warnings&&n.result.warnings.length>0&&(0,b.jsx)("div",{className:"panel ps-warnings",children:(0,b.jsx)("div",{className:"panel-body",children:n.result.warnings.map((e,t)=>(0,b.jsxs)("div",{className:"ps-warning-line",children:["⚠ ",e]},t))})}),(0,b.jsxs)("div",{className:"panel ps-chart",children:[(0,b.jsxs)("div",{className:"panel-header",children:[(0,b.jsx)("span",{className:"panel-title",children:"Equity curve"}),(0,b.jsx)("span",{className:"panel-subtitle",children:eq?`${eq.bets} bets \xb7 ${eq.detections} detections \xb7 ${eq.candles} candles`:"no backtest yet"}),(0,b.jsxs)("div",{className:"ps-chart-actions",children:[(0,b.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",marginRight:10},children:y.TIMEFRAME_OPTIONS.map(e=>{let t=Array.isArray(eQ[e])&&eQ[e].length>0,a=e===n.tf,s=!!eW[e],r=ez.includes(e),l=s||!a&&n.running,o=a?`${e} (selected — always shown)`:s?`Loading ${e} backtest…`:t?`Toggle ${e} on the chart`:`Click to backtest ${e} and add it to the chart`;return(0,b.jsx)("button",{type:"button",className:`pill-btn${r?" active":""}`,onClick:()=>
4{if(l)return;if(t||a)return void eB(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]);eU(t=>({...t,[e]:!0}));let s=M?Array.from(new Set((A||[]).map(e=>String(e||"").trim()).filter(Boolean))):[],r=i.current;e9(n.params,{tfOverride:e,combineKeys:s}).then(t=>{if(i.current!==r)return;let a=(e=>{if(!e||"object"!=typeof e)return[];let t=Array.isArray(e.series_native)?e.series_native:[],a=Array.isArray(e.hourly)?e.hourly:[];return("native"===n.params.chart_resolution?t.length?t:a:a.length?a:t).map(e=>({ts:Number(e?.ts),equity:Number(e?.equity)})).filter(e=>Number.isFinite(e.ts)&&Number.isFinite(e.equity))})(t);a.length>0&&(eD(t=>({...t,[e]:a})),eB(t=>t.includes(e)?t:[...t,e]))}).catch(()=>void 0).finally(()=>{eU(t=>{let a={...t};return delete a[e],a})})},disabled:l,title:o,children:s?`${e}…`:e},e)})}),(0,b.jsx)("button",{className:`btn btn-ghost ${o?"active":""}`,onClick:()=>{c(e=>!e),u(null),f(null),x(null)},type:"button",children:o?"Selector: on":"Selector: off"}),(0,b.jsx)("button",{className:"btn btn-primary",type:"button",onClick:e3,disabled:!d||h,children:h?"Analyzing…":"Analyze Segment"})]})]}),(0,b.jsxs)("div",{className:"panel-body",style:{padding:0},children:[(0,b.jsx)("div",{style:{height:320},children:(0,b.jsx)(eE,{equityCurve:eZ,equityCurvesByTf:eQ,activeTfs:ez,height:320,compact:!0,selectionMode:o,onSelectionChange:u})}),o?(0,b.jsx)("div",{className:"ps-chart-selection",children:d?(0,b.jsxs)("span",{children:["Selected: ",aY(d.start_ts)," → ",aY(d.end_ts)," |"," ","PnL ",aQ(d.pnl_usd)," | Return ",a0(d.return_pct)," |"," ","Points ",aV(d.points)]}):(0,b.jsx)("span",{children:"Select a segment by drag-selecting on the curve."})}):null,m?(0,b.jsx)("div",{className:"ps-insight-error",children:m}):null,g?(0,b.jsxs)("div",{className:"ps-insight-box",children:[(0,b.jsxs)("div",{className:"ps-insight-head",children:[(0,b.jsx)("div",{className:"ps-insight-title",children:"Forensics Workspace"}),(0,b.jsxs)("div",{className:"ps-insight-tabs",children:[(0,b.jsx)("button",{className:`ps-tab${"summary"===v?" active":""}`,onClick:()=>j("summary"),type:"button",children:"Summary"}),(0,b.jsx)("button",{className:`ps-tab${"markers"===v?" active":""}`,onClick:()=>j("markers"),type:"button",children:"Markers"}),(0,b.jsx)("button",{className:`ps-tab${"whatif"===v?" active":""}`,onClick:()=>j("whatif"),type:"button",children:"What-if"}),(0,b.jsx)("button",{className:`ps-tab${"stability"===v?" active":""}`,onClick:()=>j("stability"),type:"button",children:"Stability"}),(0,b.jsx)("button",{className:`ps-tab${"actions"===v?" active":""}`,onClick:()=>j("actions"),type:"button",children:"Actions"})]})]}),"summary"===v&&(0,b.jsxs)("div",{className:"ps-forensics-grid",children:[(0,b.jsxs)("div",{className:"ps-forensics-card",children:[(0,b.jsx)("div",{className:"ps-forensics-card-title",children:"Segment"}),(0,b.jsxs)("p",{children:[aY(g.selection.start_ts)," → ",aY(g.selection.end_ts)]}),(0,b.jsxs)("p",{children:["PnL: ",aQ(g.selection.pnl_usd)," | Return: ",a0(g.selection.return_pct)]})]}),(0,b.jsxs)("div",{className:"ps-forensics-card",children:[(0,b.jsx)("div",{className:"ps-forensics-card-title",children:"Regime"}),(0,b.jsx)("p",{children:String((g.regime||{}).regime_label||"unknown")}),(0,b.jsxs)("p",{children:[n.asset," ret: ",a0((g.regime||{}).asset_metrics?.ret_pct)," | BTC ret: ",a0((g.regime||{}).btc_metrics?.ret_pct)]})]})]}),"summary"===v&&(0,b.jsx)("div",{className:"ps-insight-markdown chat-message-text",children:(0,b.jsx)(ei.MarkdownContent,{text:g.insight_text})}),"summary"===v&&g.sources?.length?(0,b.jsx)("div",{className:"ps-insight-sources",children:g.sources.map((e,t)=>(0,b.jsxs)("div",{className:"ps-insight-source",children:[(0,b.jsxs)("a",{href:e.url,target:"_blank",rel:"noreferrer",children:[t+1,". ",e.title||e.url]}),e.snippet?(0,b.jsx)("div",{className:"ps-insight-snippet",children:e.snippet}):null]},`${e.url}-${t}`))}):null,"markers"===v&&(0,b.jsx)("div",{className:"ps-markers-wrap",children:Array.isArray(g.markers)&&g.markers.length>0?(0,b.jsxs)("table",{className:"ps-markers-table",children:[(0,b.jsx)("thead",{children:(0,b.jsxs)("tr",{children:[(0,b.jsx)("th",{children:"Marker"}),(0,b.jsx)("th",{children:"Segment"}),(0,b.jsx)("th",{children:"Baseline"}),(0,b.jsx)("th",{children:"Delta"}),(0,b.jsx)("th",{children:"Status"})]})}),(0,b.jsx)("tbody",{children:g.markers.map(e=>(0,b.jsxs)("tr",{children:[(0,b.jsx)("td",{children:e.label}),(0,b.jsx)("td",{children:a1(e.segment_value,3)}),(0,b.jsx)("td",{children:a1(e.baseline_value,3)}),(0,b.jsx)("td",{children:a1(e.delta,3)}
4),(0,b.jsx)("td",{className:`ps-status-${String(e.status||"neutral")}`,children:String(e.status||"neutral")})]},e.key))})]}):(0,b.jsx)("div",{className:"ps-empty",children:"No marker data returned for this segment."})}),"whatif"===v&&(0,b.jsx)("div",{className:"ps-rules-list",children:Array.isArray(g.candidate_rules)&&g.candidate_rules.length>0?g.candidate_rules.map(e=>(0,b.jsxs)("div",{className:"ps-rule-card",children:[(0,b.jsxs)("div",{className:"ps-rule-top",children:[(0,b.jsx)("div",{className:"ps-rule-title",children:e.label}),(0,b.jsx)("span",{className:`ps-rule-priority ${String(e.priority||"low")}`,children:String(e.priority||"low")})]}),e.description?(0,b.jsx)("p",{children:e.description}):null,e.rationale?(0,b.jsx)("p",{className:"ps-rule-rationale",children:e.rationale}):null,(0,b.jsx)("pre",{className:"ps-rule-patch",children:JSON.stringify(e.params_patch||{},null,2)}),(0,b.jsx)("button",{className:"btn btn-ghost",type:"button",onClick:()=>e6(e.params_patch,e.label),children:"Apply this patch"})]},e.id)):(0,b.jsx)("div",{className:"ps-empty",children:"No candidate rules generated for this segment."})}),"stability"===v&&(0,b.jsx)("div",{className:"ps-stability-wrap",children:g.stability?.available?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)("div",{className:"ps-forensics-grid",children:(g.stability?.rule_stats||[]).map(e=>(0,b.jsxs)("div",{className:"ps-forensics-card",children:[(0,b.jsx)("div",{className:"ps-forensics-card-title",children:e.label}),(0,b.jsxs)("p",{children:["Trigger rate: ",a0(e.trigger_rate_pct)]}),(0,b.jsxs)("p",{children:["Ret when ON: ",a1(e.avg_ret_when_triggered_pct,2),"%"]}),(0,b.jsxs)("p",{children:["Ret when OFF: ",a1(e.avg_ret_when_not_triggered_pct,2),"%"]})]},e.id))}),(0,b.jsx)("div",{className:"ps-markers-wrap",children:(0,b.jsxs)("table",{className:"ps-markers-table",children:[(0,b.jsx)("thead",{children:(0,b.jsxs)("tr",{children:[(0,b.jsx)("th",{children:"Quarter"}),(0,b.jsx)("th",{children:"Return%"}),(g.stability?.rule_stats||[]).map(e=>(0,b.jsx)("th",{children:e.label},`stable-col-${e.id}`))]})}),(0,b.jsx)("tbody",{children:(g.stability?.quarters||[]).map(e=>(0,b.jsxs)("tr",{children:[(0,b.jsx)("td",{children:e.quarter}),(0,b.jsxs)("td",{children:[a1(e.ret_pct,2),"%"]}),(g.stability?.rule_stats||[]).map(t=>(0,b.jsx)("td",{children:e.rule_signals?.[t.id]?.triggered?"ON":"-"},`stable-cell-${e.quarter}-${t.id}`))]},e.quarter))})]})})]}):(0,b.jsx)("div",{className:"ps-empty",children:"No stability matrix available."})}),"actions"===v&&(0,b.jsxs)("div",{className:"ps-actions-panel",children:[(0,b.jsx)("p",{children:"Use this panel to apply a generated patch, save strategy params, and rerun quickly."}),(0,b.jsxs)("div",{className:"ps-actions-inline",children:[(0,b.jsx)("button",{className:"btn btn-ghost",type:"button",disabled:!g.candidate_rules?.[0],onClick:()=>e6(g.candidate_rules?.[0]?.params_patch,g.candidate_rules?.[0]?.label),children:"Apply top rule patch"}),(0,b.jsx)("button",{className:"btn",type:"button",onClick:n.save,disabled:n.saving||n.running,children:n.saving?"Saving…":"Save params"}),(0,b.jsx)("button",{className:"btn btn-primary",type:"button",onClick:e1,disabled:n.running,children:n.running?"Running…":"Run backtest"})]}),w?(0,b.jsx)("div",{className:"ps-patch-msg",children:w}):null,k?(0,b.jsxs)("div",{className:"ps-applied-patch",children:[(0,b.jsxs)("div",{className:"ps-forensics-card-title",children:["Current applied patch: ",k.label]}),(0,b.jsx)("pre",{className:"ps-rule-patch",children:JSON.stringify(k.patch,null,2)}),(0,b.jsx)("button",{className:"btn btn-ghost",type:"button",onClick:()=>{S(null),N("")},children:"Clear applied patch view"})]}):null]})]}):null]})]}),(0,b.jsxs)("div",{className:"ps-bottom",children:[(0,b.jsxs)("div",{className:"panel ps-stats",children:[(0,b.jsx)("div",{className:"panel-header",children:(0,b.jsxs)("span",{className:"panel-title",children:["Stats — ",e.name]})}),(0,b.jsx)("div",{className:"panel-body",children:eq?(0,b.jsxs)("div",{className:"ps-statcard",children:[(0,b.jsxs)("p",{children:["Base mode: ",eq.base_mode||"-"," | Base:"," ","percent"===eq.base_mode?`${aV(100*Number(eq.base_pct_used||0))}% (cap ${aV(eq.base_cap_usd_used)})`:aV(eq.base_usd_used)," ","| Ladder: [",(eq.ladder_used||[]).join(", "),"]"]}),Array.isArray(eq.ladder_step_stats)&&eq.ladder_step_stats.length>0&&(0,b.jsxs)("div",{className:"ps-logic-block",children:[(0,b.jsx)("div",{className:"ps-logic-title",children:"Ladder Step Stats"}),eq.ladder_step_stats.map(e=>(0,b.jsxs)("p",{children:["Step ",aV(e.step),": bets ",aV(e.bets)," | wins ",aV(e.wins)," | losses ",aV(e.losses)," | bet WR ",aV(e.winrate_pct),"% | campaign wins ",aV(e.campaign_wins)]},`ladder-step-${e.step}`))]}),(0,b.jsxs)("p",{children:["Fill range: ",aG(eq.fill_price_min_used)," - ",aG(eq.fill_price_max_used)," | Avg fill:"," ",aG(eq.avg_fill_price_used)," | Mode: ",eq.fill_price_mode_used||"-"]}
4),(0,b.jsxs)("p",{children:["Fill source: ",eq.fill_source_used||"-"," | Apply on: ",eq.clob_apply_on_used||"-"," | Exclude unfilled step1:"," ",null==eq.clob_exclude_unfilled_used?"-":String(eq.clob_exclude_unfilled_used)]}),(0,b.jsxs)("p",{children:["CLOB scope: full candle | Fidelity: ",aV(eq.clob_fidelity_minutes_used),"m | Ladder fallback:"," ",aG(eq.ladder_fill_price_min_used)," - ",aG(eq.ladder_fill_price_max_used)," (",eq.ladder_fill_price_mode_used||"-",")"]}),(0,b.jsxs)("p",{children:["CLOB fills checked/hit/no-data: ",aV(eq.clob_fill_checked_bets||0),"/",aV(eq.clob_fill_hit_bets||0),"/",aV(eq.clob_fill_no_data_bets||0)," | Excluded setups: ",aV(eq.clob_fill_miss_excluded_setups||0)," | Step1/ladder hits:"," ",aV(eq.clob_fill_used_step1_bets||0),"/",aV(eq.clob_fill_used_ladder_bets||0)]}),(0,b.jsxs)("p",{children:["Snapshot model: ",eq.snapshot_model_enabled?"on":"off"," | Snapshot fill bets: ",aV(eq.snapshot_fill_used_bets||0)," | Snapshot invalidations:"," ",aV(eq.snapshot_invalidation_triggered||0)," / ",aV(eq.snapshot_invalidation_checks||0)," checks | No-data:"," ",aV(eq.snapshot_invalidation_no_data||0)]}),(0,b.jsxs)("p",{children:["Take profit: ",eq.take_profit_mode_used||"off"," | %: ",aV(100*Number(eq.take_profit_ratio_used||0))," ","| Fixed USD: ",aV(eq.take_profit_fixed_usd_used)," | After USD: ",aV(eq.take_profit_after_usd_used)]}),(0,b.jsxs)("p",{children:["Topup: ",eq.topup_enabled?"on":"off"," | Mode: ",eq.topup_mode_used||"-"," | DD trigger:"," ",null!=eq.topup_drawdown_trigger_used?`${aV(100*Number(eq.topup_drawdown_trigger_used))}%`:"-"," ","| Percent:"," ",null!=eq.topup_percent_used?`${aV(100*Number(eq.topup_percent_used))}%`:"-"]}),(0,b.jsxs)("p",{children:["Topups: ",aV(eq.topup_count||0)," times | Topup fresh: ",aV(eq.topup_total||0)," | Topup external:"," ",aV(eq.topup_from_external_total||0)," | Topup total:"," ",aV((eq.topup_total_all??(eq.topup_total||0)+(eq.topup_from_external_total||0))||0)]}),(0,b.jsxs)("p",{children:["Streak used: ",aV(eq.streak_used)," | Exact used:"," ",null==eq.exact_used?"-":String(eq.exact_used)]}),(0,b.jsxs)("p",{children:["Entry timing used: ",eq.entry_timing_used||"-"," | Direction rule used: ",eq.direction_rule_used||"-"]}),(0,b.jsxs)("p",{children:["Signal engine used: ",eq.signal_engine_used||"-"," | Engine override: ",eq.signal_engine_override_used||"-"," | Neutral fallback:"," ",eq.neutral_default_side_used||"-"]}),(0,b.jsxs)("p",{children:["Neutral fallback used detections: ",aV(eq.neutral_fallback_used_detections||0)]}),(0,b.jsxs)("div",{className:"ps-logic-block",children:[(0,b.jsx)("div",{className:"ps-logic-title",children:"Compiled Logic"}),(0,b.jsx)("pre",{className:"ps-logic-text",children:eq.logic_human||"No compiled logic summary returned."}),Array.isArray(eq.logic_lints)&&eq.logic_lints.length>0&&(0,b.jsx)("div",{className:"ps-logic-lints",children:eq.logic_lints.map((e,t)=>(0,b.jsxs)("div",{children:["⚠ ",e]},`${t}-${e}`))})]}),eq.promotion_gate?.available?(0,b.jsxs)("div",{className:"ps-logic-block",children:[(0,b.jsx)("div",{className:"ps-logic-title",children:"Promotion Gate"}),(0,b.jsxs)("p",{children:["Pass: ",eq.promotion_gate.pass?"yes":"no"," | Checks:"," ",aV(eq.promotion_gate.checks_passed||0),"/",aV(eq.promotion_gate.checks_total||0)," | Failed:"," ",Array.isArray(eq.promotion_gate.failed_checks)&&eq.promotion_gate.failed_checks.length>0?eq.promotion_gate.failed_checks.join(", "):"-"]}),(0,b.jsxs)("p",{children:["DSR prob: ",aV(100*Number(eq.promotion_gate.dsr_prob||0)),"% | SPA p-value:"," ",aJ(eq.promotion_gate.spa_pvalue||0)," | Bootstrap prob(loss):"," ",aV(100*Number(eq.promotion_gate.bootstrap_prob_loss||0)),"%"]}),(0,b.jsxs)("p",{children:["Walk-forward pass: ",aV(100*Number(eq.promotion_gate.walk_forward_pass_rate||0)),"%"," ","(",aV(eq.promotion_gate.walk_forward_passes||0),"/",aV(eq.promotion_gate.walk_forward_tests||0),")"," ","| Sharpe ann: ",aV(eq.promotion_gate.sharpe_ann||0)," | Sortino ann: ",aV(eq.promotion_gate.sortino_ann||0)]}),(0,b.jsxs)("p",{children:["Calmar: ",aV(eq.promotion_gate.calmar||0)," | CAGR: ",aV(eq.promotion_gate.cagr_pct||0),"% | MaxDD: ",aV(eq.promotion_gate.maxdd_pct||0),"% | Trials est: ",aV(eq.promotion_gate.independent_trials_est||0)]})]}):(0,b.jsx)("p",{children:"Promotion gate: unavailable"}),(0,b.jsxs)("p",{children:["Streak move filter: min ",aJ(eq.streak_move_min_pct_used)," | max"," ",aJ(eq.streak_move_max_pct_used)," | checked/filtered/no-data: ",aV(eq.streak_move_checked_candidates||0),"/",aV(eq.streak_move_filtered_candidates||0),"/",aV(eq.streak_move_no_data_candidates||0)]}),(0,b.jsxs)("p",{children:["Feature lab: ",eq.feature_lab_enabled_used?"on":"off"," | checked/kept/filtered/no-data:"," ",aV(eq.feature_lab_checked_candidates||0),"/",aV(eq.feature_lab_kept_candidates||0),"/",aV(eq.feature_lab_filtered_candidates||0),"/",aV(eq.feature_lab_no_data_candidates||0)]}),(0,b.jsxs)("p",{children:["Feature ranges: ret1 ",aJ(eq.feature_ret1_min_pct_used),"..",aJ(eq.feature_ret1_max_pct_used)," | ret",aV(eq.feature_retn_lookback_used||4)," ",aJ(eq.feature_retn_min_pct_used),"..",aJ(eq.feature_retn_max_pct_used)," | atr14 ",aJ(eq.feature_atr14_min_pct_used),"..",aJ(eq.feature_atr14_max_pct_used)," | ema20 gap ",aJ(eq.feature_ema20_gap_min_pct_used),"..",aJ(eq.feature_ema20_gap_max_pct_used)," | vol ",aJ(eq.feature_vol_ratio_min_used),"..",aJ(eq.feature_vol_ratio_max_used)," | rsi ",aJ(eq.feature_rsi14_min_used),"..",aJ(eq.feature_rsi14_max_used)," | wick≤",aJ(eq.feature_wick_o
4pp_max_used)]}),(0,b.jsxs)("p",{children:["Confidence: ",null==eq.confidence_enabled_used?"-":String(eq.confidence_enabled_used)," | Mult"," ",aV(eq.confidence_multiplier_used)," | Min score ",aV(eq.confidence_min_score_used)]}),(0,b.jsxs)("p",{children:["Confidence thresholds: atr≤",aV(eq.confidence_atr_cap_used)," | ret1≥",aV(eq.confidence_ret1_ext_used)," | ema≥",aV(eq.confidence_ema_ext_used)," | m1≥",aV(eq.confidence_m1_ret_ext_used)," | wickReq"," ",null==eq.confidence_require_wick_opp_used?"-":String(eq.confidence_require_wick_opp_used)," ","| wickCap ",aV(eq.confidence_wick_opp_cap_used)]}),(0,b.jsxs)("p",{children:["Confidence V2 sizing: mode ",eq.confidence_sizing_mode_used||"off"," | denom ",aV(eq.confidence_sizing_denominator_used||100)," | scaled/skipped campaigns ",aV(eq.confidence_sizing_scaled_campaigns||0),"/",aV(eq.confidence_sizing_skipped_campaigns||0)," | avg mult ",aV(eq.confidence_sizing_avg_multiplier||1)]}),Array.isArray(eq.confidence_sizing_tiers_used)&&eq.confidence_sizing_tiers_used.length>0&&(0,b.jsxs)("p",{children:["Confidence tiers: ",eq.confidence_sizing_tiers_used.map(e=>`${aV(e?.threshold)}%=${aV(100*Number(e?.multiplier??1))}%`).join(", ")]}),(0,b.jsxs)("p",{children:["Pattern side used: ",eq.pattern_side_used||"-"]}),(0,b.jsxs)("p",{children:["Hours used: ",null==(s=eq.hours_et_used)?"-":"all"===s?"all":Array.isArray(s)?s.join(","):String(s)]}),(0,b.jsxs)("p",{children:["Months used: ",null==(r=eq.months_used)?"-":"all"===r?"all":Array.isArray(r)?r.join(","):String(r)]}),(0,b.jsxs)("p",{children:["Weekday multipliers: ",(eq.weekday_base_multipliers_used||[]).join(", ")||"-"]}),(0,b.jsxs)("p",{children:["Choppy model: ",eq.choppy_week_enabled?"on":"off"," | Score≥",aV(eq.choppy_week_score_threshold_used)," | Thu..Sun mult:"," ",Array.isArray(eq.choppy_week_thu_sun_day_multipliers_used)?eq.choppy_week_thu_sun_day_multipliers_used.join(", "):"-"]}),(0,b.jsxs)("p",{children:["Choppy thresholds: ret≥",aV(eq.choppy_week_btc_mw_ret_sum_threshold_used)," | wick/body≥",aV(eq.choppy_week_btc_mw_wick_body_ratio_threshold_used)," | volRatio≤",aV(eq.choppy_week_mw_vol_ratio_eth_btc_threshold_used)]}),(0,b.jsxs)("p",{children:["Choppy checked/no-data: ",aV(eq.choppy_week_checked_candidates||0),"/",aV(eq.choppy_week_no_data_candidates||0)," | flagged/adjusted campaigns:"," ",aV(eq.choppy_week_flagged_campaigns||0),"/",aV(eq.choppy_week_adjusted_campaigns||0)," | avg score:"," ",aV(eq.choppy_week_avg_score_started||0)]}),null!=eq.pair_eth_multiplier_used&&(0,b.jsxs)("p",{children:["Pair multiplier: ETH ",aV(eq.pair_eth_multiplier_used)]}),(0,b.jsxs)("p",{children:["Candle coverage (asset): ",eq.candle_source_asset||"-"," |"," ",aV(100*Number(eq.candle_coverage_asset||0)),"%"," ","(",aV(eq.candle_rows_asset),"/",aV(eq.candle_expected_asset),") | pg/sqlite/net:"," ",aV(eq.candle_postgres_rows_asset||0),"/",aV(eq.candle_sqlite_rows_asset||0),"/",aV(eq.candle_network_rows_asset||0)]}),(0,b.jsxs)("p",{children:["Candle coverage (BTC): ",eq.candle_source_btc||"-"," |"," ",eq.candle_expected_btc&&Number(eq.candle_expected_btc)>0?`${aV(100*Number(eq.candle_coverage_btc||0))}% (${aV(eq.candle_rows_btc)}/${aV(eq.candle_expected_btc)})`:"n/a"," ","| pg/sqlite/net: ",aV(eq.candle_postgres_rows_btc||0),"/",aV(eq.candle_sqlite_rows_btc||0),"/",aV(eq.candle_network_rows_btc||0)]}),(0,b.jsxs)("p",{children:["Campaign max exposure: ",aV(eq.campaign_max_exposure)]}),(0,b.jsxs)("p",{children:["Base-cap hit campaigns: ",aV(eq.base_cap_hit_campaigns)]}),(0,b.jsxs)("p",{children:["Total campaigns: ",aV(eq.campaigns)," | Total bets: ",aV(eq.bets)]}),(0,b.jsxs)("p",{children:["Campaign unresolved: ",aV(eq.campaign_unresolved||0)," | Skipped overlap:"," ",aV(eq.campaign_skipped_overlap||0)]}),(0,b.jsxs)("p",{children:["Avg campaigns/week: ",aV(eq.avg_campaigns_per_week)," | Avg campaigns/month:"," ",aV(eq.avg_campaigns_per_month)]}),(0,b.jsxs)("p",{children:["Avg bets/week: ",aV(eq.avg_bets_per_week)," | Avg bets/month: ",aV(eq.avg_bets_per_month)]}),(0,b.jsxs)("p",{className:"ps-statcard-pnl",children:["PnL (net, after topups): ",aV(eq.pnl)," | PnL (gross): ",aV(eq.pnl_gross??eq.pnl)," | PnL External:"," ",aV(eq.pnl_external)," | End equity: ",aV(eq.end_equity)]}),(0,b.jsxs)("p",{children:["Campaign WR: ",aV(eq.campaign_winrate_pct),"% | Bet WR: ",aV(eq.winrate_pct),"%"]}),(0,b.jsxs)("p",{children:["Campaign W/L: ",aV(eq.campaign_wins),"/",aV(eq.campaign_losses)," | Bets W/L:"," ",aV(eq.wins),"/",aV(eq.losses)]}),(0,b.jsxs)("p",{children:["MaxDD: ",aV(eq.maxdd)," | Min equity: ",aV(eq.min_equity)]}),(0,b.jsxs)("p",{children:["Upsized campaigns: ",aV(eq.upsize_c
4ampaigns)," | Blown: ",eq.blown?"yes":"no"]}),(0,b.jsxs)("p",{className:"ps-statcard-muted",children:["Range: ",eq.start_utc||"-"," to ",eq.end_utc||"-"]})]}):(0,b.jsx)("div",{className:"ps-empty",children:"Run a backtest to see stats."})})]}),(0,b.jsxs)("div",{className:"panel ps-stats",children:[(0,b.jsxs)("div",{className:"panel-header",children:[(0,b.jsx)("span",{className:"panel-title",children:"All Signals"}),eq&&(0,b.jsxs)("span",{className:"panel-subtitle",children:["visible ",aV(eJ)," / raw ",aV(eJ)," · hidden skipped ",aV(eY)," · page ",eX,"/",eK]})]}),(0,b.jsx)("div",{className:"panel-body",children:eq&&eJ>0?(0,b.jsxs)("div",{className:"ps-statcard",children:[(0,b.jsxs)("div",{style:{display:"flex",gap:8,marginBottom:10},children:[(0,b.jsx)("button",{className:"btn btn-ghost",disabled:eX<=1||n.signalRowsLoading,onClick:()=>{let e=Math.max(1,eX-1);J(e);let t=String(eq?.signal_rows_token||"");n.loadSignalRowsPage(e,50,t)},children:"Prev"}),(0,b.jsx)("button",{className:"btn btn-ghost",disabled:eX>=eK||n.signalRowsLoading,onClick:()=>{let e=Math.min(eK,eX+1);J(e);let t=String(eq?.signal_rows_token||"");n.loadSignalRowsPage(e,50,t)},children:"Next"})]}),n.signalRowsLoading&&(0,b.jsx)("p",{className:"ps-statcard-muted",children:"Loading signal rows…"}),n.signalRowsError&&(0,b.jsxs)("p",{className:"ps-statcard-warn",children:["Signal rows: ",n.signalRowsError]}),eG.map((e,t)=>{let a,s,r,n,l,i=(eX-1)*50+t+1,o=aK(e);return(0,b.jsxs)("div",{style:{marginBottom:14,paddingBottom:10,borderBottom:"1px solid rgba(160,170,190,0.2)"},children:[(0,b.jsxs)("p",{children:["#",i," entry ",aY(e?.entry_ts)," (",e?.entry_side||"-",") | status: ",e?.status||"-",e?.win_step?` (step ${e?.win_step})`:"",o?` | strategy: ${o}`:""]}),(0,b.jsxs)("p",{children:["streak: ",e?.streak_dir||"-"," x",aV(e?.streak_len_effective)," | source: ",e?.entry_dir_source||"-"," | neutral fallback: ",String(!!e?.used_neutral_fallback)]}),(0,b.jsxs)("p",{children:["confidence: ",aV(100*Number(e?.confidence??1)),"% | entry size:"," ",e?.entry_size_usd==null?"-":`$${aV(Number(e?.entry_size_usd))}`]}),e?.feature_values&&(0,b.jsxs)("p",{children:["feature: ret1 ",aJ(e.feature_values.ret1_pct)," | retN ",aJ(e.feature_values.retn_pct)," | atr14"," ",aJ(e.feature_values.atr14_pct)," | ema gap ",aJ(e.feature_values.ema20_gap_pct)," | vol"," ",aJ(e.feature_values.vol_ratio5)," | rsi ",aJ(e.feature_values.rsi14)," | wickOpp"," ",aJ(e.feature_values.wick_opp_ratio)," | filter ",String(e?.feature_filter_reason||"-")]}),(0,b.jsx)("div",{className:"ps-signal-candles",children:(s=(a=(e?.context_candles||[]).filter(e=>[e?.open,e?.high,e?.low,e?.close].every(e=>Number.isFinite(Number(e))))).map(e=>Number(e.low)),r=a.map(e=>Number(e.high)),n=s.length?Math.min(...s):0,l=r.length?Math.max(...r):1,a.map((a,s)=>(0,b.jsx)(aX,{c:a,minLow:n,maxHigh:l,onClick:()=>((e,t)=>{let a=(Array.isArray(e?.context_candles)?e.context_candles:[]).map(e=>({idx:Number(e?.idx),open_ts:Number(e?.open_ts),close_ts:Number(e?.close_ts),open:Number(e?.open),high:Number(e?.high),low:Number(e?.low),close:Number(e?.close),role:String(e?.role||"")})).filter(e=>Number.isFinite(e.open_ts)&&Number.isFinite(e.close_ts)&&Number.isFinite(e.open)&&Number.isFinite(e.high)&&Number.isFinite(e.low)&&Number.isFinite(e.close)).sort((e,t)=>{let a=Number.isFinite(e.idx)?e.idx:0,s=Number.isFinite(t.idx)?t.idx:0;return a!==s?a-s:e.open_ts-t.open_ts});if(!a.length)return;let s=a.map(e=>({time:e.open_ts,open:e.open,high:e.high,low:e.low,close:e.close})),r=a.flatMap(e=>"detect"===e.role?[{time:e.open_ts,position:"aboveBar",color:"#f7c86a",shape:"circle",text:"D"}]:"entry"===e.role?[{time:e.open_ts,position:"belowBar",color:"#8fb8ff",shape:"circle",text:"E"}]:[]),n=a.find(e=>"entry"===e.role)||a.find(e=>"detect"===e.role)||a[Math.max(0,Math.floor(a.length/2))],l=Number(e?.entry_ts||0),i=String(e?.entry_side||"-"),o=String(e?.status||"-"),c=Number(e?.streak_len_effective||0),d=String(e?.streak_dir||"-"),u=aK(e);eL({title:`Signal #${t} \xb7 ${aY(l)} \xb7 ${i}${u?` \xb7 ${u}`:""}`,subtitle:`status ${o} \xb7 streak ${d} x${aV(c)}${u?` \xb7 strategy ${u}`:""} \xb7 yellow=detect, blue=entry`,candles:s,markers:r,focusTime:Number(n?.open_ts||s[s.length-1]?.time||0)})})(e,i)},`all-sig-${eX}-${t}-c-${s}`)))}),(0,b.jsx)("p",{className:"ps-statcard-muted",children:"Click any candle to open zoomed chart."}),(0,b.jsx)("p",{style:{marginTop:6},children:"Legend: streak = plain border, detect = yellow border, entry = blue border"}),Array.isArray(e?.ladder_steps)&&e.ladder_steps.length>0&&(0,b.jsx)("div",{style:{marginTop:6},children:e.ladder_steps.map((e,a)=>(0,b.jsxs)("p",{children:["step ",aV(e?.step)," @ ",aY(Number(e?.ts||0))," | x",aV(e?.multiplier)," | stake"," ",e?.stake_usd==null?"-":`$${aV(e?.stake_usd)}`," | ",e?.result||"-",e?.fill_price!=null?` | fill ${aG(e?.fill_price)}`:"",e?.pnl_usd!=null?` | pnl ${aV(e?.pnl_usd)}`:""]},`sig-ladder-${eX}-${t}-${a}`))})]},`sig-row-${eX}-${t}`)})]}):(0,b.jsx)("div",{className:"ps-empty",children:"Run backtest to see all signals and ladder outcomes."})})]}),(0,b.jsxs)("div",{className:"panel ps-stats",children:[(0,b.jsxs)("div",{className:"panel-header",children:[(0,b.jsx)("span",{className:"panel-title",children:"Auto-Tune Suggestions"}),(0,b.jsx)("span",{className:"panel-subtitle",children:eP.length>0?`${eP.length} ready`:"click Auto-tune winrate"})]}),(0,b.jsx)("div",{className:"panel-body",children:eP.length>0?(0,b.jsx)("div",{className:"ps-statcard",children:eP.map((e,t)=>(0,b.jsxs)("div",{style:{marginBottom:12,paddingBottom:10,borderBottom:"1px solid rgba(160,170,190,0.2)"},children:[(0,b.jsxs)("p",{children:["#",t+1," ",e.label," | Campaign WR ",aV(e.campaign_winrate_pct),"% | Bet WR ",aV(e.winrate_pct),"%"]}),(0,b.jsxs)("p",{children:["PnL ",aV(e.pnl)," | MaxDD ",aV(e.maxdd)," | End equity ",aV(e.end_equity)]}),(0,b.jsxs)("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:[(0,b.jsx)("button",{className:"btn btn-ghost",type:"button",onClick:()=>e6({...e.patch,feature_lab_enabled:!0},`auto: ${e.label}`),children:"Apply params"}),(0,b.jsx)("button",{className:"btn btn-ghost",type:"button",onClick:async()=>{e6({...e.patch,feature_lab_enabled:!0},`auto: ${e.label}`),await new Promise(e=>setTimeout(e,50)),e1()},children:"Apply + rerun"})]})]},`autotune-row-${t}-${e.label}`))}):(0,b.jsx)("div",{className:"ps-empty",children:"Run auto-tune to get top winrate parameter suggestions."})})]}),!1]})]})]}),eO&&(0,b.jsx)("div",{className:"ps-signal-modal",onClick:()=>eL(null),children:(0,b.jsxs)("div",{className:"ps-signal-modal-card",onClick:e=>e.stopPropagation(),children:[(0,b.jsxs)("div",{className:"ps-signal-modal-head",children:[(0,b.jsxs)("div",{className:"ps-signal-modal-meta",children:[(0,b.jsx)("div",{className:"ps-signal-modal-title",children:eO.title}),(0,b.jsx)("div",{className:"ps-signal-modal-subtitle",children:eO.subtitle})]}),(0,b.jsx)("button",{className:"btn btn-ghost ps-signal-modal-close",type:"button",onClick:()=>eL(null),children:"Close"})]}),(0,b.jsx)("div",{className:"ps-signal-modal-chart",children:(0,b.jsx)(aT,{ref:l,candles:eO.candles,markers:eO.markers,title:"Signal Context Candles",subtitle:"Focused view mirrors detection zoom behavior"})})]})})]})}function a3({title:e,children:t}){return(0,b.jsxs)("div",{className:"ps-group",children:[(0,b.jsx)("div",{className:"ps-group-title",children:e}),(0,b.jsx)("div",{className:"ps-group-fields",children:t})]})}function a6({label:e,children:t}){return(0,b.jsxs)("label",{className:"field ps-field",children:[(0,b.jsx)("span",{className:"field-label",children:e}),t]})}function a8(e){return`${(100*e).toFixed(0)}%`}function a9(e){let t=new Date(1e3*e),a=String(t.getMonth()+1).padStart(2,"0"),s=String(t.getDate()).padStart(2,"0"),r=String(t.getHours()).padStart(2,"0"),n=String(t.getMinutes()).padStart(2,"0");return`${a}/${s} ${r}:${n}`}function a7(e){let t=new Date(1e3*e),a=new Intl.DateTimeFormat("en-US",{timeZone:"America/Ne
4w_York",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",hour12:!1}).formatToParts(t),s=a.find(e=>"month"===e.type)?.value??"--",r=a.find(e=>"day"===e.type)?.value??"--",n=a.find(e=>"hour"===e.type)?.value??"--",l=a.find(e=>"minute"===e.type)?.value??"--";return`${s}/${r} ${n}:${l} ET`}function se(e){return new Date(1e3*e).toISOString()}function st({rows:e}){if(!e.length)return null;let t=Math.min(...e.map(e=>e.low)),a=Math.max(...e.map(e=>e.high)),s=Math.max(a-t,1e-9),r=308/Math.max(e.length,1),n=Math.min(28,.44*r),l=e=>14+(a-e)/s*112;return(0,b.jsxs)("svg",{className:"pattern-lab-trace-svg",viewBox:"0 0 360 140",preserveAspectRatio:"none",children:[(0,b.jsx)("rect",{x:0,y:0,width:360,height:140,fill:"transparent"}),e.map((e,t)=>{let a=26+r*t+r/2,s=l(e.open),i=l(e.close),o=l(e.high),c=l(e.low),d=Math.min(s,i),u=Math.max(Math.abs(i-s),1.5),h="UP"===e.direction?"var(--color-long)":"DOWN"===e.direction?"var(--color-short)":"var(--fg-muted)";return(0,b.jsxs)("g",{children:[(0,b.jsx)("line",{x1:a,x2:a,y1:o,y2:c,stroke:h,strokeWidth:1.4}),(0,b.jsx)("rect",{x:a-n/2,y:d,width:n,height:u,fill:h,opacity:.92,rx:1}),(0,b.jsx)("text",{x:a,y:137,textAnchor:"middle",fontSize:"10",fill:"var(--fg-muted)",children:e.idx})]},`${e.time}-${t}`)})]})}function sa({c:e,minLow:t,maxHigh:a}){let s=Number(e.open),r=Number(e.high),n=Number(e.low),l=Number(e.close);if(![s,r,n,l].every(e=>Number.isFinite(e)))return null;let i=Math.max(a-t,1e-9),o=e=>1+(a-e)/i*58,c=o(r),d=o(n),u=o(s),h=o(l),p=Math.min(u,h),m=Math.max(3,Math.abs(h-u)),x=l>=s?"var(--color-long)":"var(--color-short)";return(0,b.jsxs)("div",{className:"pattern-lab-mini-candle",children:[(0,b.jsx)("div",{className:"pattern-lab-mini-candle-wick",style:{to
4p:`${c}px`,height:`${Math.max(1,d-c)}px`}}),(0,b.jsx)("div",{className:"pattern-lab-mini-candle-body",style:{top:`${p}px`,height:`${m}px`,background:x}})]})}function ss({range:e,compact:t=!1,onRemove:a}){let s=Array.isArray(e.candles)?e.candles:[],r=s.length?Math.min(...s.map(e=>Number(e.low))):0,n=s.length?Math.max(...s.map(e=>Number(e.high))):1,l=(e.summary?.net_move_pct??0)*100;return(0,b.jsxs)("div",{className:`pattern-lab-selected-range-card${t?" compact":""}`,children:[(0,b.jsxs)("div",{className:"pattern-lab-selected-range-head",children:[(0,b.jsxs)("span",{children:[a9(e.start_time)," → ",a9(e.end_time)," (",e.bars," bars)"]}),a?(0,b.jsx)("button",{className:"pattern-lab-selected-range-remove",onClick:a,title:"Remove this selected range",children:"×"}):null]}),(0,b.jsx)("div",{className:"pattern-lab-selected-range-candle-wrap",children:(0,b.jsx)("div",{className:"pattern-lab-selected-range-candles",children:s.map(t=>(0,b.jsx)(sa,{c:t,minLow:r,maxHigh:n},`${e.id}-${t.time}`))})}),(0,b.jsxs)("div",{className:"pattern-lab-selected-range-meta",children:[(0,b.jsxs)("span",{children:["up ",e.summary.up_bars]}),(0,b.jsxs)("span",{children:["down ",e.summary.down_bars]}),(0,b.jsxs)("span",{children:["net ",l.toFixed(2),"%"]})]})]})}function sr({patterns:e,loading:t,activePattern:a,stats:s,revisionsCount:r,onSelect:n,onDelete:l,onRetrain:i,onRefresh:o,onClearDetections:c,onOpenStrategy:d,onOpenRevisions:u}){return(0,b.jsxs)("div",{className:"pattern-sidebar",children:[(0,b.jsx)("div",{className:"pattern-sidebar-header",children:(0,b.jsx)("span",{className:"pattern-sidebar-title",children:"Pattern Library"})}),(0,b.jsxs)("div",{className:"pattern-sidebar-list",children:[t&&0===e.length&&(0,b.jsx)(b.Fragment,{children:Array.from({length:4}).map((e,t)=>(0,b.jsxs)("div",{className:"pattern-sidebar-item",style:{pointerEvents:"none"},children:[(0,b.jsxs)("div",{className:"pattern-sidebar-item-header",children:[(0,b.jsx)("span",{className:"skeleton",style:{display:"inline-block",width:18,height:18,borderRadius:4}}),(0,b.jsx)("span",{className:"skeleton",style:{display:"inline-block",width:"55%",height:14,marginLeft:6}})]}),(0,b.jsx)("div",{className:"pattern-sidebar-item-desc",children:(0,b.jsx)("span",{className:"skeleton",style:{display:"block",width:"85%",height:11,marginTop:6}})})]},`sk-${t}`))}),!t&&0===e.length&&(0,b.jsx)("div",{className:"pattern-sidebar-empty",children:"No patterns yet. Use the chat to create one."}),e.map(e=>(0,b.jsxs)("div",{className:`pattern-sidebar-item${a?.key===e.key?" active":""}`,onClick:()=>n(a?.key===e.key?null:e),children:[(0,b.jsxs)("div",{className:"pattern-sidebar-item-header",children:[(0,b.jsx)("span",{className:`pattern-dir-badge ${e.direction}`,children:"bullish"===e.direction?"B":"bearish"===e.direction?"S":"N"}),(0,b.jsx)("span",{className:"pattern-sidebar-item-name",children:e.name}),(0,b.jsx)("button",{className:"pattern-sidebar-item-delete",onClick:t=>{t.stopPropagation(),window.confirm(`Delete pattern "${e.name}"?
5
6This will also remove its saved strategy and cannot be undone.`)&&l(e.key)},title:"Delete pattern",children:"×"})]}),(0,b.jsx)("div",{className:"pattern-sidebar-item-desc",children:e.description}),(0,b.jsx)("div",{className:"pattern-sidebar-item-actions",children:(0,b.jsx)("button",{className:`pattern-sidebar-strategy-btn${e.has_strategy?" view":""}`,onClick:t=>{t.stopPropagation(),d(e.key)},title:e.has_strategy?"View / update backtest strategy":"Create a backtest strategy from this pattern",children:e.has_strategy?"View Strategy":"Create Strategy"})})]},e.key))]}),a&&s&&(0,b.jsxs)("div",{className:"pattern-stats",children:[(0,b.jsxs)("div",{className:"pattern-stats-title",children:[a.name," Stats",(0,b.jsx)("button",{className:"pattern-stats-refresh",onClick:o,title:"Refresh stats & re-detect",children:"↻"}),(0,b.jsx)("button",{className:"pattern-stats-refresh",onClick:c,title:"Clear detections + feedback and re-detect fresh",children:"Clear"})]}),(0,b.jsxs)("div",{className:"pattern-stats-grid",children:[(0,b.jsxs)("div",{className:"pattern-stat",children:[(0,b.jsx)("span",{className:"pattern-stat-value",children:s.total_detections}),(0,b.jsx)("span",{className:"pattern-stat-label",children:"Reviewed"})]}),(0,b.jsxs)("div",{className:"pattern-stat",children:[(0,b.jsx)("span",{className:"pattern-stat-value",children:a8(s.accuracy)}),(0,b.jsx)("span",{className:"pattern-stat-label",children:"Accuracy"})]}),(0,b.jsxs)("div",{className:"pattern-stat",children:[(0,b.jsx)("span",{className:"pattern-stat-value correct",children:s.correct}),(0,b.jsx)("span",{className:"pattern-stat-label",children:"Correct"})]}),(0,b.jsxs)("div",{className:"pattern-stat",children:[(0,b.jsx)("span",{className:"pattern-stat-value incorrect",children:s.incorrect}),(0,b.jsx)("span",{className:"pattern-stat-label",children:"Incorrect"})]})]}),s.can_retrain&&(0,b.jsxs)("button",{className:"btn btn-primary pattern-retrain-btn",onClick:()=>i(a.key),children:["Retrain (",s.total_detections,"+ feedback)"]}),s.can_convert&&(0,b.jsxs)("div",{className:"pattern-convert-badge",children:["Ready for strategy conversion (",a8(s.accuracy)," accuracy)"]})]}),a&&(0,b.jsx)("div",{className:"pattern-revisions-trigger",children:(0,b.jsxs)("button",{className:"pattern-revisions-trigger-btn",type:"button",onClick:u,title:"Open revision history",children:["Revision history",r>0?` (${r})`:""]})})]})}function sn(e){return Object.prototype.hasOwnProperty.call(e,"proposed_updates")}function sl({front:e,dominated:t,applying:a,onPick:s}){let r=[...e,...t];if(0===r.length)return null;let n=r.map(e=>e.trade_retention_pct),l=r.map(e=>e.winrate_pct),i=Math.max(0,Math.floor(Math.min(...n,100)-5)),o=Math.ceil(Math.max(...n,105)+5),c=Math.max(0,Math.floor(Math.min(...l)-2)),d=Math.min(100,Math.ceil(Math.max(...l)+2)),u=e=>44+(e-i)/Math.max(1e-9,o-i)*464,h=e=>192-(e-c)/Math.max(1e-9,d-c)*182,[p,m]=(0,_.useState)(null),x=[...e].sort((e,t)=>
6e.trade_retention_pct-t.trade_retention_pct).map((e,t)=>`${0===t?"M":"L"}${u(e.trade_retention_pct).toFixed(1)},${h(e.winrate_pct).toFixed(1)}`).join(" "),g=u(100);return(0,b.jsxs)("div",{className:"pattern-lab-refine-preview",style:{padding:10},children:[(0,b.jsxs)("div",{className:"pattern-lab-refine-preview-head",style:{marginBottom:6},children:[(0,b.jsx)("strong",{children:"Pareto frontier"}),(0,b.jsxs)("span",{style:{color:"var(--text-secondary)"},children:[e.length," optimal · ",t.length," dominated · click a colored point to apply"]})]}),(0,b.jsxs)("div",{style:{position:"relative"},children:[(0,b.jsxs)("svg",{width:520,height:220,style:{display:"block",background:"rgba(255,255,255,0.02)",borderRadius:6},children:[(0,b.jsxs)("text",{x:38,y:h(d)+4,fontSize:"10",fill:"var(--text-secondary)",textAnchor:"end",children:[d,"%"]}),(0,b.jsxs)("text",{x:38,y:h(c)+4,fontSize:"10",fill:"var(--text-secondary)",textAnchor:"end",children:[c,"%"]}),(0,b.jsxs)("text",{x:u(i),y:210,fontSize:"10",fill:"var(--text-secondary)",textAnchor:"start",children:[i,"%"]}),(0,b.jsxs)("text",{x:u(o),y:210,fontSize:"10",fill:"var(--text-secondary)",textAnchor:"end",children:[o,"%"]}),(0,b.jsx)("text",{x:276,y:216,fontSize:"10",fill:"var(--text-secondary)",textAnchor:"middle",children:"trade count retention →"}),(0,b.jsx)("text",{x:10,y:110,fontSize:"10",fill:"var(--text-secondary)",textAnchor:"middle",transform:"rotate(-90 10 110)",children:"winrate ↑"}),(0,b.jsx)("line",{x1:g,x2:g,y1:10,y2:192,stroke:"#f6c849",strokeDasharray:"3,3",strokeWidth:1,opacity:.5}),(0,b.jsx)("text",{x:g+4,y:20,fontSize:"9",fill:"#f6c849",opacity:.7,children:"baseline"}),t.map((e,t)=>(0,b.jsx)("circle",{cx:u(e.trade_retention_pct),cy:h(e.winrate_pct),r:2,fill:"#555",opacity:.5},`d-${t}`)),(0,b.jsx)("path",{d:x,fill:"none",stroke:"#15b097",strokeWidth:1.5,opacity:.6}),e.map((e,t)=>{let r=u(e.trade_retention_pct),n=h(e.winrate_pct);return(0,b.jsx)("g",{children:(0,b.jsx)("circle",{cx:r,cy:n,r:5,fill:"#15b097",stroke:"#0c2d2a",strokeWidth:1.5,style:{cursor:a?"wait":"pointer"},onMouseEnter:()=>m(e),onMouseLeave:()=>m(t=>t===e?null:t),onClick:()=>{a||s(e)}})},`f-${t}`)})]}),p?(0,b.jsxs)("div",{style:{position:"absolute",top:6,right:6,padding:"6px 8px",background:"rgba(0,0,0,0.85)",border:"1px solid var(--border-subtle)",borderRadius:4,fontSize:11,fontFamily:"var(--font-mono)",pointerEvents:"none",maxWidth:220},children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("strong",{children:"winrate"})," ",p.winrate_pct.toFixed(2),"%"]}),(0,b.jsxs)("div",{children:[(0,b.jsx)("strong",{children:"trades"})," ",p.correct+p.wrong," (",p.trade_retention_pct.toFixed(0),"% of baseline)"]}),(0,b.jsxs)("div",{children:[(0,b.jsx)("strong",{children:"W/L"})," ",p.correct,"/",p.wrong]}),"number"==typeof p.ev_pct?(0,b.jsxs)("div",{children:[(0,b.jsx)("strong",{children:"EV"})," ",(0,b.jsxs)("span",{style:{color:(p.ev_pct??0)>=0?"#15b097":"#e84957"},children:[(p.ev_pct??0)>=0?"+":"",(p.ev_pct??0).toFixed(3),"%/trade"]})]}):null,(0,b.jsxs)("div",{children:[(0,b.jsx)("strong",{children:"wilson"})," ",p.wilson_score.toFixed(3)]}),p.rule_changed?(0,b.jsxs)("div",{style:{color:"#f6c849",marginTop:3},children:["rule → ",p.proposed_direction_rule||"default"]}):null,p.exit_changed&&p.proposed_exit_params?(0,b.jsxs)("div",{style:{color:"#15b097",marginTop:3},children:["exit → hold ",p.proposed_exit_params.max_hold_bars,"b",p.proposed_exit_params.take_profit_percent>0?`, TP ${p.proposed_exit_params.take_profit_percent}%`:"",p.proposed_exit_params.stop_loss_percent>0?`, SL ${p.proposed_exit_params.stop_loss_percent}%`:""]}):null]}):null]})]})}function si({patternKey:e,initialParams:t,asset:a,tf:s,direction:r="neutral",directionRule:n=null,patternName:l,patternDescription:i,patternPineSource:o,patternSpec:c,detecting:d=!1,onPatternUpdated:u,onOpenHistory:h,onDirectionRuleSaved:p}){let[m,x]=(0,_.useState)(!1),[g,f]=(0,_.useState)(t&&Object.keys(t).length>0?t:null),[v,y]=(0,_.useState)(()=>{let e={};for(let[a,s]of Object.entries(t||{}))e[a]=s.default;return e}),[j,w]=(0,_.useState)({}),[N,k]=(0,_.useState)(null),[S,$]=(0,_.useState)(""),C=(0,_.useRef)({}),M=(0,_.useMemo)(()=>
6{if(!c)return null;if("string"==typeof c)try{return JSON.parse(c)}catch{return null}return c},[c]),E=Array.isArray(M?.params)?M.params:[],[A,T]=(0,_.useState)(()=>{let e={};for(let t of E)t&&"string"==typeof t.name&&(e[t.name]=Number(t.default));return e}),[F,P]=(0,_.useState)({}),R=(0,_.useRef)({});(0,_.useEffect)(()=>{let e={};for(let t of E)t&&"string"==typeof t.name&&(e[t.name]=Number(t.default));T(e)},[M]);let[O,L]=(0,_.useState)(!1),[I,D]=(0,_.useState)(null),[z,B]=(0,_.useState)(null),[W,U]=(0,_.useState)(!1),[H,q]=(0,_.useState)(!1),[V,G]=(0,_.useState)(null),[J,Y]=(0,_.useState)([]),[K,X]=(0,_.useState)(null),[Z,Q]=(0,_.useState)(0),[ee,et]=(0,_.useState)(""),[ea,es]=(0,_.useState)(null),en=(0,_.useRef)(null);en.current=K;let[el,ei]=(0,_.useState)(!1),eo=(0,_.useRef)(!0);(0,_.useEffect)(()=>(eo.current=!0,()=>{eo.current=!1}),[]);let ec=(0,_.useRef)(3),[ed,eu]=(0,_.useState)([]),[eh,ep]=(0,_.useState)([]),[em,ex]=(0,_.useState)(null),[eg,ef]=(0,_.useState)(0),[eb,e_]=(0,_.useState)(null),[ev,ey]=(0,_.useState)(0),[ej,ew]=(0,_.useState)(null),[eN,ek]=(0,_.useState)(null),[eS,e$]=(0,_.useState)(()=>{try{let e=window.localStorage.getItem("openpoly.autotune.market_type");return"prediction_market"===e?"prediction_market":"futures"}catch{return"futures"}});(0,_.useEffect)(()=>{try{window.localStorage.setItem("openpoly.autotune.market_type",eS)}catch{}},[eS]);let[eC,eM]=(0,_.useState)(()=>{try{return"1"===window.localStorage.getItem("openpoly.autotune.allow_redefinition")}catch{return!1}});(0,_.useEffect)(()=>{try{window.localStorage.setItem("openpoly.autotune.allow_redefinition",eC?"1":"0")}catch{}},[eC]);let[eE,eA]=(0,_.useState)(null),[eT,eF]=(0,_.useState)(null),[eP,eR]=(0,_.useState)(null);(0,_.useEffect)(()=>{eR(null)},[c]);let[eO,eL]=(0,_.useState)(()=>"playground"===window.localStorage.getItem("openpoly.glyphMode")?"playground":"sliders");(0,_.useEffect)(()=>{window.localStorage.setItem("openpoly.glyphMode",eO)},[eO]);let[eI,eD]=(0,_.useState)(null);(0,_.useEffect)(()=>{let e=!0;return ai().then(t=>{e&&eD(t)}).catch(()=>{}),()=>{e=!1}},[]),(0,_.useEffect)(()=>{let t=!0;return(async()=>{try{let a=await (0,er.authGetJson)(`/api/patterns/${e}`);if(!t)return;if(a.ok&&a.data){let e=a.data.pine_params;if(e&&Object.keys(e).length>0){f(e);let t={};for(let[a,s]of Object.entries(e))t[a]=s.default;y(t)}else f(null)}}catch{}})(),()=>{t=!1}},[e]);let ez=(t,r)=>{y(e=>({...e,[t]:r})),C.current[t]&&clearTimeout(C.current[t]),C.current[t]=setTimeout(()=>{C.current[t]=null,w(e=>({...e,[t]:!0})),k(null),$(`saving ${t}…`),(async()=>{try{let l=await (0,er.authFetch)(`/api/patterns/${e}/params`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({param_updates:{[t]:r},intent:"positive",stats_asset:a,stats_tf:s,stats_direction_rule:n||null})}),i=await l.json().catch(()=>({}));if(!l.ok||!i?.ok){let e=i?.message||i?.error||`HTTP ${l.status}`;k(`Failed to save ${t}: ${e}`),$("");return}$(`saved ${t}`);let o=i?.data?.pattern;o&&u&&u(o)}catch(e){k(`Failed to save ${t}: ${e instanceof Error?e.message:String(e)}`),$("")}finally{w(e=>{let a={...e};return delete a[t],a})}})()},250)},eB=(e,t)=>{T(a=>({...a,[e]:t})),R.current[e]&&clearTimeout(R.current[e]),R.current[e]=setTimeout(()=>{R.current[e]=null,P(t=>({...t,[e]:!0})),k(null),$(`saving ${e}…`),(async()=>{try{let a=E.map(a=>a&&a.name===e?{...a,default:t}:a);await eZ({params:a}),$(`saved ${e}`)}catch(e){k(e instanceof Error?e.message:String(e)),$("")}finally{P(t=>{let{[e]:a,...s}=t;return s})}})()},250)},eW=async()=>{L(!0),B(null),D(null);try{let t=await (0,er.authFetch)(`/api/patterns/${e}/refine`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({asset:a,tf:s})}),r=await t.json().catch(()=>({}));if(!t.ok||!r?.ok){let e=r?.message||r?.error||`HTTP ${t.status}`;B(e);return}D(r.data)}catch(e){B(e instanceof Error?e.message:String(e))}finally{L(!1)}},eU=async()=>{if(q(!0),G(null),Y([]),X(null),Q(0),eu([]),ep([]),ex(null),ef(0),e_(null),ey(0),ew(null),ek(null),e1){try{let t=await (0,er.authFetch)(`/api/patterns/${e}/refine/suggestions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({asset:a,tf:s,max_suggestions:5})}),r=await t.json().catch(()=>({}));if(t.ok&&r?.ok){let e=Array.isArray(r?.data?.suggestions)?r.data.suggestions:[];Y(e),0===e.length&&G(null)}else G(r?.message||r?.error||`HTTP ${t.status}`)}catch(e){G(e instanceof Error?e.message:String(e))}finally{q(!1)}return}let t="",r=null,n=null;try{r=await (0,er.authFetch)(`/api/patterns/${e}/spec/auto-tune/start`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({asset:a,tf:s,max_suggestions:5,lookback_days:1825,market_type:eS,allow_redefinition:eC,time_budget_seconds:0})})}catch(e){n=e}let l=r?await r.json().catch(()=>null):null;if(r&&r.ok&&l?.ok&&(t=String(l?.data?.job_id||"").trim()),!t){let e=null!==n||!r||0===r.status||r.status>=500,a="";if(e&&(es("start request failed; checking whether the run started anyway…"),await new Promise(e=>
6setTimeout(e,3e3)),a=await eH()),!a){es(null),r&&r.ok&&l?.ok?G("server did not return a job_id"):l?.message||l?.error?G(String(l.message||l.error)):null!==n?G(n instanceof Error?n.message:String(n)):G(`HTTP ${r?r.status:0}`),q(!1);return}t=a,es("start request dropped; adopted the run that was already going")}X(t),en.current=t,await eq(t)},eH=async()=>{let e=await eV();if(!e||"running"!==String(e.status||""))return"";let t=String(e.job_id||"").trim();return t&&function(e,t,a=12e4){if(!Number.isFinite(e)||e<=0)return!1;let s=t-e;return s>=-a&&s<=a}(Date.parse(String(e.started_at||e.created_at||"")),Date.now())?t:""},eq=async t=>{let a=Date.now(),s=e=>new Promise(t=>setTimeout(t,e)),r={evaluated:0,lastAdvanceMs:a},n=0,l=0,i="released";q(!0),es(null),et("");try{for(;;){var o;if(!eo.current){i="unmounted";break}if(en.current!==t){i="released";break}if(Date.now()-a>864e5){es("stopped watching after 6 h; the job may still finish server-side and will show up under the last run"),i="cap";break}await s(n>0?function(e){let t=Number.isFinite(e)?Math.floor(e):1;return t<=1?2e3:Math.min(2e3*Math.pow(2,t-1),15e3)}(n):1500);let c=null,d=!1;try{c=await (0,er.authFetch)(`/api/patterns/${e}/spec/auto-tune/status?job_id=${encodeURIComponent(t)}`,{method:"GET"})}catch{d=!0}let u=c?await c.json().catch(()=>null):null;if(!c||!c.ok||!u||!u.ok){let e=d||!c||c.ok&&!u,t=function(e,t){if(t||null===e||!Number.isFinite(e))return"transient";let a=Math.floor(e);return tG.has(a)||a>=500?"transient":"definitive"}(e?null:c.status,e);if("transient"===t){if(n+=1,0===l&&(l=Date.now()),Date.now()-l>6e5){i="outage";break}es(function(e){let t=Number.isFinite(e)&&e>0?Math.floor(e):1;return`connection lost, retrying (${t})`}(n));continue}G(u?.message||u?.error||`HTTP ${c?c.status:0}`),i="definitive";break}n=0,l=0;let h=u?.data||{};Q(Number(h.evaluated||0)),et(function(e){var t;let a,s,r,n,l,i,o=e||{},c=Number(o.evaluated||0),d=Number(o.elapsed_seconds||0),u=[(a=Number.isFinite(d)&&d>0?Math.floor(d):0,s=Math.floor(a/3600),r=Math.floor(a%3600/60),n=a%60,l=e=>String(e).padStart(2,"0"),s>0?`${s}:${l(r)}:${l(n)}`:`${l(r)}:${l(n)}`),`${tV(c)} states`,function(e,t,a){let s=Number.isFinite(a)?Number(a):NaN;if(!Number.isFinite(s)||s<=0){let a=Number.isFinite(t)?t:0;s=a>0&&Number.isFinite(e)?e/a:0}return!Number.isFinite(s)||s<=0?"-":s>=10?`${Math.round(s)}/s`:`${s.toFixed(1)}/s`}(c,d,o.evaluated_per_second)],h=(i=Number.isFinite(t=Number(o.time_budget_seconds||0))?Math.floor(t):0)<=0?"":`budget ${Math.round(i/60)} min`;return h&&u.push(h),u.join(" · ")}(h)),r=function(e,t,a){let s=Number.isFinite(t)?Math.max(0,Math.floor(t)):0;return s>e.evaluated?{evaluated:s,lastAdvanceMs:a}:e}(r,Number(h.evaluated||0),Date.now()),es((o=r,Date.now()-o.lastAdvanceMs<6e5?null:"no progress for 10 min; the server may have restarted, cancel or keep waiting"));let p=Array.isArray(h.top_suggestions)?h.top_suggestions:[];p.length>0&&Y(p);let m=Array.isArray(h.pareto_front)?h.pareto_front:[],x=Array.isArray(h.pareto_dominated_sample)?h.pareto_dominated_sample:[];m.length>0&&eu(m),x.length>0&&ep(x),h.loss_cluster_suggestion&&"object"==typeof h.loss_cluster_suggestion&&ex(h.loss_cluster_suggestion);let g=Number(h.min_decisive_floor||0);g>0&&ef(g),"string"==typeof h.search_note&&h.search_note&&e_(h.search_note);let f=Number(h.search_decisive_floor||0);f>0&&ey(f),null!=h.search_feasible_candidates&&ew(Number(h.search_feasible_candidates)),null!=h.search_infeasible_skipped&&ek(Number(h.search_infeasible_skipped));let b=String(h.state||"");if("done"===b||"cancelled"===b||"error"===b){es(null),i="done"===b?"done":"definitive","error"===b?G(String(h.error||"auto-tune failed")):"cancelled"===b?G("auto-tune cancelled."):h.budget_exhausted?(es(function(e){let t=Number.isFinite(e)?Math.max(0,Math.floor(e)):0;return`stopped at the time budget after ${tV(t)} states; showing best so far`}(Number(h.evaluated||0))),0===p.length&&G("No better CPS setup found before the time budget ran out.")):0===p.length&&G("No better CPS setup found on the selected historical window.");break}}}catch(e){G(e instanceof Error?e.message:String(e)),i="definitive"}finally{q(!1),X(null),en.current===t&&(en.current=null),et("")}if("done"===i||"unmounted"===i)return;let c=("outage"===i||"cap"===i)&&ec.current>0;c&&(ec.current-=1),"outage"===i&&es("connection lost for 10 min; re-reading the saved run"),await eG({resume:c,expectJobId:t})},eV=(0,_.useCallback)(async()=>
6{if(!e||!a||!s)return null;try{let t=new URLSearchParams({asset:a,tf:s,market_type:eS}).toString(),r=await (0,er.authGetJson)(`/api/patterns/${e}/spec/auto-tune/last?${t}`);if(!r?.ok)return null;return r.data||null}catch{return null}},[e,a,s,eS]),eG=(0,_.useCallback)(async e=>{let t=e?.resume!==!1,a=await eV();if(!a)return null;if(!eo.current)return a;let s=Array.isArray(a.suggestions)?a.suggestions:[];s.length>0&&Y(s);let r=Array.isArray(a.pareto_front)?a.pareto_front:[],n=Array.isArray(a.pareto_dominated_sample)?a.pareto_dominated_sample:[];r.length>0&&eu(r),n.length>0&&ep(n),a.loss_cluster_suggestion&&"object"==typeof a.loss_cluster_suggestion&&ex(a.loss_cluster_suggestion);let l=Number(a.min_decisive_floor||0);l>0&&ef(l),"string"==typeof a.search_note&&a.search_note&&e_(a.search_note);let i=Number(a.search_decisive_floor||0);i>0&&ey(i),null!=a.search_feasible_candidates&&ew(Number(a.search_feasible_candidates)),null!=a.search_infeasible_skipped&&ek(Number(a.search_infeasible_skipped)),Q(Number(a.evaluated_states||0));let o=String(a.status||""),c=String(a.job_id||"");return e?.expectJobId&&c===e.expectJobId&&"done"===o&&(G(null),es(null)),t&&"running"===o&&c&&null===en.current&&(X(c),en.current=c,eq(c)),a},[eV]),eJ=async()=>{ei(!0);try{let e=await eG({resume:!0});e?"running"!==String(e.status||"")&&es(null):es("no saved auto-tune run for this pattern yet")}finally{ei(!1)}};(0,_.useEffect)(()=>{eG()},[eG]);let eY=async()=>{if(!e||!a||!s||!window.confirm("Clear all saved auto-tune suggestions for this pattern? This can't be undone."))return;let t=!1;try{let r=new URLSearchParams({asset:a,tf:s,market_type:eS}).toString();t=!(await (0,er.authFetch)(`/api/patterns/${e}/spec/auto-tune/last?${r}`,{method:"DELETE"})).ok}catch{t=!0}Y([]),eu([]),ep([]),ex(null),ef(0),e_(null),ey(0),ew(null),ek(null),Q(0),G(null),es(t?"cleared on screen, but the server did not confirm the delete":null)},eK=async()=>{let t=en.current;if(!t)return;let a=!1;try{a=!(await (0,er.authFetch)(`/api/patterns/${e}/spec/auto-tune/cancel`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({job_id:t})})).ok}catch{a=!0}a&&es("stopped watching; the server did not confirm the cancel"),X(null),en.current=null},eX=async t=>{let r=await (0,er.authFetch)(`/api/patterns/${e}/params`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({param_updates:t,intent:"positive",stats_asset:a,stats_tf:s,stats_direction_rule:n||null})}),l=await r.json().catch(()=>({}));if(!r.ok||!l?.ok)throw Error(l?.message||l?.error||`HTTP ${r.status}`);y(e=>({...e,...t}));let i=l?.data?.pattern;i&&u&&u(i)},eZ=async(t,a={})=>{let s={spec_patch:t,intent:"positive"};void 0!==a.directionRule&&(s.direction_rule_override=a.directionRule??""),void 0!==a.exitParams&&a.exitParams&&(s.exit_params_override=a.exitParams);let r=await (0,er.authFetch)(`/api/patterns/${e}/spec`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)}),n=await r.json().catch(()=>({}));if(!r.ok||!n?.ok)throw Error(n?.message||n?.error||`HTTP ${r.status}`);let l=n?.data?.pattern;l&&u&&u(l)},eQ=async(t,a={})=>{let s={replace_spec:t,intent:"positive"};void 0!==a.directionRule&&(s.direction_rule_override=a.directionRule??""),void 0!==a.exitParams&&a.exitParams&&(s.exit_params_override=a.exitParams);let r=await (0,er.authFetch)(`/api/patterns/${e}/spec`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)}),n=await r.json().catch(()=>({}));if(!r.ok||!n?.ok)throw Error(n?.message||n?.error||`HTTP ${r.status}`);let l=n?.data?.pattern;l&&u&&u(l)},e0=async()=>{if(I&&I.proposed_updates){if(0===Object.keys(I.proposed_updates).length)return void D(null);U(!0),B(null);try{await eX(I.proposed_updates),D(null)}catch(e){B(e instanceof Error?e.message:String(e))}finally{U(!1)}}},e1=!!(g&&Object.keys(g).length>0),e2=e1||!!c,e5=J.length>0?sn(J[0])?"pine":"cps":null;if(!e1&&!c)return null;let e4=e1?Object.keys(g).length:0,e3=E.length,e6=Object.keys(j).length>0||Object.keys(F).length>0,e8=e6||d||W,e9=e6?"saving…":d?"detecting…":W?"applying…":"";return(0,b.jsxs)("div",{className:`pattern-lab-params${m?" collapsed":""}`,children:[(0,b.jsxs)("div",{className:"pattern-lab-params-head",children:[(0,b.jsxs)("button",{className:"pattern-lab-params-toggle",type:"button",onClick:()=>x(e=>!e),title:m?"Expand parameters":"Collapse parameters",children:[m?"▸":"▾"," Tunable parameters"]}),e8&&(0,b.jsxs)("span",{className:"pattern-lab-params-loader",role:"status","aria-label":e9,children:[(0,b.jsx)("span",{className:"pattern-lab-params-spinner"}),(0,b.jsx)("span",{className:"pattern-lab-params-loader-text",children:e9})]}),(0,b.jsx)("span",{className:"pattern-lab-params-status",children:S||(e1&&e3>0?`${e4} pine knob${1===e4?"":"s"} + ${e3} spec param${1===e3?"":"s"} — drag, autosaves`:e1?`${e4} knob${1===e4?"":"s"} — drag, autosaves`:e3>0?`${e3} spec param${1===e3?"":"s"} — drag, autosaves`:c?`CPS spec — ${c.length} candle${1===c.length?"":"s"}, drag bands to tune`:"")}),h&&(e1||!!c)&&(0,b.jsx)("button",{className:"pattern-lab-params-history-btn",type:"button",onClick:h,title:"See recent param/spec changes (with restore)",children:"History"}),e1&&(0,b.jsx)("button",{className:"pattern-lab-params-refine",type:"button",onClick:eW,disabled:O||W,title:"Run coordinate-descent over input.*() params against your ✓/✗ feedback",children:(0,b.jsx)(aN,{busy:O,label:"Refine ✨",busyLabel:"Refining…"})}),e2&&(0,b.jsx)("button",{className:"pattern-lab-params-refine",type:"button",onClick:eU,disabled:H||W||O,title:e1?"Generate multiple high-scoring parameter suggestions from feedback":"Search CPS candle-band configurations for higher historical winrate",children:(0,b.jsx)(aN,{busy:H,label:"Auto Tune 🎯",busyLabel:K?`Auto-tuning… ${Z>0?Z:""}`:"Auto-tuning…"})}),e2&&!e1&&(0,b.jsxs)("select",{value:eS,onChange:e=>e$("prediction_market"===e.target.value?"prediction_market":"futures"),disabled:H,title:"Market type. Futures sweeps TP/SL/hold; prediction markets resolve at next-bar close so exit knobs are skipped.",style:{padding:"3px 6px",fontSize:11,background:"var(--bg-base)",border:"1px solid var(--border-subtle)",borderRadius:4,color:"var(--fg)"},children:[(0,b.jsx)("option",{value:"futures",children:"futures (sweep exits)"}),(0,b.jsx)("option",{value:"prediction_market",children:"prediction market (direction only)"})]}),e2&&!e1&&(0,b.jsxs)("label",{title:"OFF (default): autotune refines each candle band by ±1 adjacent step — it can't redefine the candle (e.g. marubozu → doji). ON: full band ladder sweep + loss-cluster constraint suggestions; may change the core candle structure.",style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:11,color:eC?"#e8a23d":"var(--text-secondary)",cursor:H?"not-allowed":"pointer",userSelect:"none"},children:[(0,b.jsx)("input",{type:"checkbox",checked:eC,disabled:H,onChange:e=>eM(e.target.checked)}),"allow redefinition"]}),H&&K&&(0,b.jsx)("button",{className:"pattern-lab-params-refine",type:"button",onClick:eK,title:"Stop the running auto-tune job",style:{background:"rgba(232, 73, 87, 0.10)",borderColor:"rgba(232, 73, 87, 0.35)"},children:"Cancel"}),e2&&!e1&&(0,b.jsx)("button",{className:"pattern-lab-params-refine",type:"button",onClick:eJ,disabled:el,title:"Re-read the last saved auto-tune run for this pattern (use after a server restart)",children:(0,b.jsx)(aN,{busy:el,label:"Refresh results",busyLabel:"Refreshing…"})}),e2&&!H&&(J.length>0||ed.length>0||em)&&(0,b.jsx)("button",{className:"pattern-lab-params-refine",type:"button",onClick:eY,title:"Wipe saved auto-tune suggestions for this pattern",style:{background:"rgba(120,120,120,0.10)",borderColor:"rgba(120,120,120,0.35)"},children:"Clear"})]}),c&&eI&&(0,b.jsxs)("div",{className:"cps-glyph-mode-toggle",children:[(0,b.jsx)("button",{type:"button",className:`cps-glyph-mode-btn${"sliders"===eO?" active":""}`,onClick:()=>
6eL("sliders"),title:"Tune via named band sliders",children:"Sliders"}),(0,b.jsx)("button",{type:"button",className:`cps-glyph-mode-btn${"playground"===eO?" active":""}`,onClick:()=>eL("playground"),title:"Drag candle O/H/L/C directly to shape the pattern",children:"Playground"})]}),(0,b.jsx)("div",{className:"pattern-lab-composite-wrap",children:"playground"===eO&&c&&eI?(0,b.jsx)(aj,{patternKey:e,patternSpec:eP??c,cpsVocabulary:eI,onPatternUpdated:u,onSpecOptimistic:e=>eR(e)}):(0,b.jsx)(an,{pineParams:g??{},values:v,direction:r,patternName:l,patternDescription:i,patternPineSource:o,patternSpec:eP??c??null,cpsVocabulary:eI,focusedKnob:eE,focusedCandles:eT})}),!m&&!e1&&c&&(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)("div",{className:"pattern-lab-refine-notes",children:"Auto Tune scans CPS candle-band combinations on historical candles and returns top winrate candidates."}),(0,b.jsx)(ah,{patternKey:e,patternSpec:eP??c,onPatternUpdated:u,onCandleHover:e=>eF(null==e?null:[e]),onSpecOptimistic:e=>eR(e),directionRule:n,asset:a,tf:s,onDirectionRuleSaved:p}),(0,b.jsx)(am,{patternKey:e,patternSpec:eP??c,onPatternUpdated:u,onSpecOptimistic:e=>eR(e)})]}),!m&&(0,b.jsxs)(b.Fragment,{children:[N?(0,b.jsx)("div",{className:"pattern-lab-params-error",children:N}):null,z?(0,b.jsxs)("div",{className:"pattern-lab-params-error",children:["Refine: ",z]}):null,!H&&!V&&0===J.length&&(eb||ev>0)?(0,b.jsxs)("div",{className:"pattern-lab-params-note",children:[(0,b.jsx)("strong",{children:"Auto-tune finished with nothing to suggest."})," ",eb||`No spec variant kept at least ${ev.toLocaleString()} decisive trades, so none could be surfaced.`,(null!=ej||null!=eN)&&(0,b.jsxs)("div",{className:"muted",style:{marginTop:4},children:[null!=ej&&(0,b.jsxs)(b.Fragment,{children:[ej.toLocaleString()," variant",1===ej?"":"s"," stayed above the floor"]}),null!=ej&&null!=eN&&" · ",null!=eN&&(0,b.jsxs)(b.Fragment,{children:[eN.toLocaleString()," rejected on sample size"]}),ev>0&&(0,b.jsxs)(b.Fragment,{children:[" · floor ",ev.toLocaleString()," trades"]})]})]}):null,V?(0,b.jsxs)("div",{className:"pattern-lab-params-error",children:["Auto-tune: ",V]}):null,ee?(0,b.jsxs)("div",{className:"muted",style:{fontFamily:"var(--font-mono)",fontSize:11},children:["Auto-tune: ",ee]}):null,ea?(0,b.jsxs)("div",{className:"muted",style:{color:"var(--text-secondary)"},children:["Auto-tune: ",ea]}):null,em?(0,b.jsxs)("div",{className:"pattern-lab-refine-preview",style:{borderLeft:"3px solid #15b097",paddingLeft:10},children:[(0,b.jsxs)("div",{className:"pattern-lab-refine-preview-head",children:[(0,b.jsx)("strong",{children:"🎯 Loss-cluster suggestion"}),(0,b.jsxs)("span",{style:{color:"var(--text-secondary)"},children:["targets the loss cluster directly · separation: Cohen's d = ",em.cohen_d.toFixed(2)]})]}),(0,b.jsx)("div",{style:{marginTop:6,lineHeight:1.4},children:em.explanation}),(0,b.jsxs)("div",{className:"muted",style:{marginTop:6,fontFamily:"var(--font-mono)",fontSize:11},children:["Target: ",(0,b.jsxs)("code",{children:[em.target_candle,".constraints += ",em.constraint]})]}),(0,b.jsxs)("div",{className:"muted",style:{marginTop:4},children:["Re-evaluated on full window:"," ",(0,b.jsxs)("strong",{style:{color:"#15b097"},children:[em.proposed_actual_winrate_pct.toFixed(2),"%"]})," ","winrate on ",em.proposed_actual_decisive," decisive trades",eg>0&&em.proposed_actual_decisive<eg?(0,b.jsx)("span",{style:{marginLeft:6,padding:"1px 6px",border:"1px solid #e84957",borderRadius:4,fontSize:10,color:"#e84957"},title:`Below the ${eg}-trade trust floor.`,children:"⚠ low sample"}):null,"number"==typeof em.proposed_actual_ev_pct?(0,b.jsxs)(b.Fragment,{children:[" ","·"," ",(0,b.jsxs)("strong",{style:{color:(em.proposed_actual_ev_pct??0)>=0?"#15b097":"#e84957"},children:["EV ",(em.proposed_actual_ev_pct??0)>=0?"+":"",(em.proposed_actual_ev_pct??0).toFixed(3),"%/trade"]})]}):null,em.rule_changed?(0,b.jsxs)("span",{style:{marginLeft:6,padding:"1px 6px",border:"1px solid #f6c849",borderRadius:4,fontSize:10,color:"#f6c849"},children:["rule → ",em.proposed_direction_rule||"default"]}):null,em.exit_changed&&em.proposed_exit_params?(0,b.jsxs)("span",{style:{marginLeft:6,padding:"1px 6px",border:"1px solid #15b097",borderRadius:4,fontSize:10,
6color:"#15b097"},children:["exit → hold ",em.proposed_exit_params.max_hold_bars,"b",em.proposed_exit_params.take_profit_percent>0?`, TP ${em.proposed_exit_params.take_profit_percent}%`:"",em.proposed_exit_params.stop_loss_percent>0?`, SL ${em.proposed_exit_params.stop_loss_percent}%`:""]}):null]}),(0,b.jsx)("div",{style:{marginTop:8},children:(0,b.jsx)("button",{className:"btn btn-primary",type:"button",disabled:W||!em.proposed_spec,onClick:async()=>{if(em.proposed_spec)try{U(!0),B(null);let e={};em.rule_changed&&(e.directionRule=em.proposed_direction_rule??""),em.exit_changed&&em.proposed_exit_params&&(e.exitParams=em.proposed_exit_params),await eQ(em.proposed_spec,e)}catch(e){B(e instanceof Error?e.message:String(e))}finally{U(!1)}},children:"Apply targeted constraint"})})]}):null,ed.length>0?(0,b.jsx)(sl,{front:ed,dominated:eh,applying:W,onPick:async e=>{try{U(!0),B(null);let t={};e.rule_changed&&(t.directionRule=e.proposed_direction_rule??""),e.exit_changed&&e.proposed_exit_params&&(t.exitParams=e.proposed_exit_params),e.proposed_spec&&"object"==typeof e.proposed_spec?await eQ(e.proposed_spec,t):e.proposed_spec_patch&&await eZ(e.proposed_spec_patch,t)}catch(e){B(e instanceof Error?e.message:String(e))}finally{U(!1)}}}):null,J.length>0?(0,b.jsxs)("div",{className:"pattern-lab-refine-preview",children:[(0,b.jsxs)("div",{className:"pattern-lab-refine-preview-head",children:[(0,b.jsx)("strong",{children:"Auto-tune suggestions"}),(0,b.jsxs)("span",{children:[J.length," candidate",1===J.length?"":"s"," ","pine"===e5?"from labeled feedback":"from historical winrate search"]})]}),(0,b.jsx)("div",{className:"pattern-lab-refine-notes",children:"Pick one, apply, then watch detection + winrate update."}),(0,b.jsx)("ul",{className:"pattern-lab-refine-moves",children:J.map((e,t)=>(0,b.jsx)("li",{children:sn(e)?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,b.jsxs)("span",{children:[(0,b.jsxs)("strong",{children:["#",t+1]})," ","score ",e.current_score.score.toFixed(2)," → ",e.proposed_score.score.toFixed(2)," ","(Δ ",e.delta_score>=0?"+":"",e.delta_score.toFixed(2),")"," ","· moves ",e.move_count]}),(0,b.jsx)("button",{className:"btn btn-ghost",type:"button",onClick:async()=>{try{U(!0),B(null),await eX(e.proposed_updates||{})}catch(e){B(e instanceof Error?e.message:String(e))}finally{U(!1)}},disabled:W||!e.proposed_updates||0===Object.keys(e.proposed_updates).length,children:"Apply"})]}),(0,b.jsxs)("div",{className:"muted",children:["TP/FP/FN: ",e.proposed_score.tp,"/",e.proposed_score.fp,"/",e.proposed_score.fn,e.config?` \xb7 grid ${e.config.grid_points} \xb7 iter ${e.config.max_iterations}`:""]}),(0,b.jsx)("div",{children:Object.entries(e.proposed_updates||{}).map(([e,a])=>{let s=g?.[e],r=v[e]??s?.default;return(0,b.jsxs)("div",{children:[(0,b.jsx)("code",{children:s?.label||e}),": ",(0,b.jsxs)("code",{children:[String(r)," → ",String(a)]})]},`${t}-${e}`)})})]}):(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,b.jsxs)("span",{children:[(0,b.jsxs)("strong",{children:["#",t+1]})," ","winrate ",e.baseline.winrate_pct.toFixed(2),"% → ",e.proposed.winrate_pct.toFixed(2),"%"," ","(Δ ",e.delta_winrate_pct>=0?"+":"",e.delta_winrate_pct.toFixed(2),"%)"," ","· moves ",e.move_count,"number"==typeof e.proposed.ev_pct?(0,b.jsxs)("span",{style:{marginLeft:6,fontSize:11,color:(e.proposed.ev_pct??0)>=0?"#15b097":"#e84957"},children:["· EV ",(e.proposed.ev_pct??0)>=0?"+":"",(e.proposed.ev_pct??0).toFixed(3),"%/trade"]}):null,eg>0&&e.proposed.decisive<eg?(0,b.jsxs)("span",{style:{marginLeft:6,padding:"1px 6px",border:"1px solid #e84957",borderRadius:4,fontSize:10,color:"#e84957"},title:`Only ${e.proposed.decisive} decisive trades — below the ${eg}-trade trust floor (≥25% of baseline). Treat the winrate / EV as noisy.`,children:["⚠ low sample (",e.proposed.decisive,")"]}):null,e.rule_changed?(0,b.jsxs)("span",{style:{marginLeft:6,padding:"1px 6px",border:"1px solid #f6c849",borderRadius:4,fontSize:10,
6color:"#f6c849"},children:["rule → ",e.proposed_direction_rule||"default"]}):null,e.exit_changed&&e.proposed_exit_params?(0,b.jsxs)("span",{style:{marginLeft:6,padding:"1px 6px",border:"1px solid #15b097",borderRadius:4,fontSize:10,color:"#15b097"},children:["exit → hold ",e.proposed_exit_params.max_hold_bars,"b",e.proposed_exit_params.take_profit_percent>0?`, TP ${e.proposed_exit_params.take_profit_percent}%`:"",e.proposed_exit_params.stop_loss_percent>0?`, SL ${e.proposed_exit_params.stop_loss_percent}%`:""]}):null]}),(0,b.jsx)("button",{className:"btn btn-ghost",type:"button",onClick:async()=>{try{U(!0),B(null);let t={};e.rule_changed&&(t.directionRule=e.proposed_direction_rule??""),e.exit_changed&&e.proposed_exit_params&&(t.exitParams=e.proposed_exit_params),e.proposed_spec&&"object"==typeof e.proposed_spec?await eQ(e.proposed_spec,t):await eZ(e.proposed_spec_patch||{},t)}catch(e){B(e instanceof Error?e.message:String(e))}finally{U(!1)}},disabled:W||(!e.proposed_spec||0===Object.keys(e.proposed_spec).length)&&(!e.proposed_spec_patch||0===Object.keys(e.proposed_spec_patch).length),children:"Apply"})]}),(0,b.jsxs)("div",{className:"muted",children:["Baseline W/L/P: ",e.baseline.correct,"/",e.baseline.wrong,"/",e.baseline.pending," ","· Proposed W/L/P: ",e.proposed.correct,"/",e.proposed.wrong,"/",e.proposed.pending," ","· Decisive: ",e.baseline.decisive," → ",e.proposed.decisive]}),(0,b.jsx)("div",{children:Object.entries(e.proposed_spec_patch?.candles||{}).flatMap(([e,a])=>Object.entries(a).flatMap(([a,s])=>s&&"object"==typeof s&&!Array.isArray(s)?Object.entries(s).map(([s,r])=>(0,b.jsxs)("div",{children:[(0,b.jsxs)("code",{children:[e,".",a,".",s]}),": ",(0,b.jsx)("code",{children:JSON.stringify(r)})]},`${t}-${e}-${a}-${s}`)):[(0,b.jsxs)("div",{children:[(0,b.jsxs)("code",{children:[e,".",a]}),": ",(0,b.jsx)("code",{children:JSON.stringify(s)})]},`${t}-${e}-${a}`)]))})]})},`auto-sugg-${t}`))})]}):null,e1&&I?(0,b.jsxs)("div",{className:"pattern-lab-refine-preview",children:[(0,b.jsxs)("div",{className:"pattern-lab-refine-preview-head",children:[(0,b.jsx)("strong",{children:"Refinement proposal"}),(0,b.jsxs)("span",{children:[I.label_counts.total," labels (",I.label_counts.correct," ✓, ",I.label_counts.incorrect," ✗) · ",I.iterations," iter"]})]}),(0,b.jsxs)("div",{className:"pattern-lab-refine-preview-scores",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("strong",{children:"Current"}),(0,b.jsxs)("div",{children:["TP ",I.current_score.tp," · FP ",I.current_score.fp," · TN ",I.current_score.tn," · FN ",I.current_score.fn]}),(0,b.jsxs)("div",{className:"muted",children:["score ",I.current_score.score.toFixed(2)]})]}),(0,b.jsxs)("div",{children:[(0,b.jsx)("strong",{children:"Proposed"}),(0,b.jsxs)("div",{children:["TP ",I.proposed_score.tp," · FP ",I.proposed_score.fp," · TN ",I.proposed_score.tn," · FN ",I.proposed_score.fn]}),(0,b.jsxs)("div",{className:"muted",children:["score ",I.proposed_score.score.toFixed(2)]})]})]}),Object.keys(I.proposed_updates).length>0?(0,b.jsx)("ul",{className:"pattern-lab-refine-moves",children:Object.entries(I.proposed_updates).map(([e,t])=>{let a=g[e],s=v[e]??a?.default;return(0,b.jsxs)("li",{children:[(0,b.jsx)("strong",{children:a?.label||e})," ",(0,b.jsxs)("span",{className:"muted",children:["(",e,"):"]})," ",(0,b.jsxs)("code",{children:[String(s)," → ",String(t)]})]},e)})}):(0,b.jsx)("div",{className:"muted",children:"No single-knob move improves the score on your labeled set."}),I.notes&&I.notes.length>0?(0,b.jsx)("div",{className:"pattern-lab-refine-notes",children:I.notes.map((e,t)=>(0,b.jsxs)("div",{children:["· ",e]},t))}):null,(0,b.jsxs)("div",{className:"pattern-lab-refine-actions",children:[(0,b.jsx)("button",{className:"btn btn-primary",type:"button",onClick:e0,disabled:W||0===Object.keys(I.proposed_updates).length,children:W?"Applying…":"Apply proposal"}),(0,b.jsx)("button",{className:"btn btn-ghost",type:"button",onClick:()=>D(null),disabled:W,children:"Discard"})]})]}):null,E.length>0&&(0,b.jsx)("div",{className:"pattern-lab-cps-params-grid",children:E.map(e=>{if(!e||"string"!=typeof e.name)return null;let t=A[e.name]??Number(e.default),a=!!F[e.name],s=Number(e.min),r=Number(e.max),n="int"===e.type,l=Number(e.step??(n?1:Math.max(.001,Number(((r-s)/100).toFixed(4)))));return(0,b.jsxs)("div",{className:`pattern-lab-param-row${a?" saving":""}`,children:[(0,b.jsxs)("div",{className:"pattern-lab-param-label",children:[(0,b.jsxs)("span",{children:[e.label||e.name,(0,b.jsxs)("span",{className:"pattern-lab-param-affects",title:"CPS spec param — referenced as param.<name> in cross_constraints",children:[" ","→ spec"]})]}),(0,b.jsxs)("span",{className:"muted",children:["(",e.name,")"]})]}),(0,b.jsx)("input",{type:"range",min:s,max:r,step:l,value:t,onChange:t=>eB(e.name,n?parseInt(t.target.value,10):parseFloat(t.target.value)),className:"pattern-lab-param-slider"}),(0,b.jsx)("input",{type:"number",className:"pattern-lab-param-num",min:s,max:r,step:l,value:t,onChange:t=>eB(e.name,n?parseInt(t.target.value||"0",10):parseFloat(t.target.value||"0"))}),(0,b.jsx)("span",{className:"pattern-lab-param-pending",children:a?"•":""})]},`cps-${e.name}`)})}),e1&&(0,b.jsx)("div",{className:"pattern-lab-params-grid",children:Object.entries(g).map(([e,t])=>{let a=v[e]??t.default,s=!!j[e],r=t4(e,t,g).affectsLabel,n={onMouseEnter:()=>eA(e),onMouseLeave:()=>eA(t=>t===e?null:t),onFocus:()=>eA(e),onBlur:()=>eA(t=>t===e?null:t)};if("bool"===t.type)return(0,b.jsxs)("label",{className:`pattern-lab-param-bool${s?" saving":""}${eE===e?" focused":""}`,...n,children:[(0,b.jsx)("input",{type:"checkbox",checked:!!a,onChange:t=>ez(e,t.target.checked)}),(0,b.jsxs)("span",{children:[t.label||e," ",(0,b.jsxs)("span",{className:"muted",children:["(",e,")"]})]})]},e);let l="int"===t.type,i=t.min??+!!l,o=t.max??(l?100:1),c=Number(a),d=l?1:Math.max(.001,Number(((o-i)/100).toFixed(4)));return(0,b.jsxs)("div",{className:`pattern-lab-param-row${s?" saving":""}${eE===e?" focused":""}`,...n,children:[(0,b.jsxs)("div",{className:"pattern-lab-param-label",children:[(0,b.jsxs)("span",{children:[t.label||e,r&&(0,b.jsxs)("span",{className:"pattern-lab-param-affects",title:`Affects ${r}`,children:[" ","→ ",r]})]}),(0,b.jsxs)("span",{className:"muted",children:["(",e,")"]})]}),(0,b.jsx)("input",{type:"range",min:i,max:o,step:d,value:c,onChange:t=>ez(e,l?parseInt(t.target.value,10):parseFloat(t.target.value)),className:"pattern-lab-param-slider"}),(0,b.jsx)("input",{type:"number",className:"pattern-lab-param-num",min:i,max:o,step:d,value:c,onChange:t=>ez(e,l?parseInt(t.target.value||"0",10):parseFloat(t.target.value||"0"))}),(0,b.jsx)("span",{className:"pattern-lab-param-pending",children:s?"•":""})]},e)})})]})]})}function so({patternName:e,patternKey:t,revisions:a,revisionsLoading:s,rollbackLoading:r,onClose:n,onRollbackRevision:l,filterChangeSource:i,title:o="Revision History",emptyLabel:c="No revisions yet."}){let d=i?a.filter(e=>(e.change_source||"")===i):a;return(0,b.jsx)("div",{className:"pattern-lab-revisions-modal-backdrop",onClick:n,children:(0,b.jsxs)("div",{className:"pattern-lab-revisions-modal",onClick:e=>e.stopPropagation(),children:[(0,b.jsxs)("div",{className:"pattern-lab-revisions-modal-head",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("div",{className:"pattern-lab-revisions-modal-title",children:o}),(0,b.jsx)("div",{className:"pattern-lab-revisions-modal-subtitle",children:e})]}),(0,b.jsx)("button",{className:"pattern-lab-revisions-modal-close",onClick:n,children:"×"})]}),s?(0,b.jsx)("div",{className:"pattern-sidebar-empty",children:(0,b.jsx)(ak,{children:"Loading revisions…"})}):0===d.length?(0,b.jsx)("div",{className:"pattern-sidebar-empty",children:c}):(0,b.jsx)("div",{className:"pattern-revisions-list",children:d.map(a=>{let s=null!=a.stats_correct||null!=a.stats_wrong,n=Number(a.stats_correct??0),i=Number(a.stats_wrong??0),o=Number(a.stats_pending??0),c=n+i,d=c>0?Math.round(n/c*100):null;return(0,b.jsxs)("div",{className:"pattern-revision-row",children:[(0,b.jsxs)("div",{className:"pattern-revision-meta",children:[(0,b.jsxs)("span",{className:"pattern-revision-rev",children:["r",a.rev_no]}),(0,b.jsx)("span",{className:"pattern-revision-source",children:a.change_source||"update"}),(0,b.jsx)("span",{className:"pattern-revision-time",children:function(e){if(!e)return"-";let t=new Date(e);if(Number.isNaN(t.getTime()))return"-";let a=String(t.getMonth()+1).padStart(2,"0"),s=String(t.getDate()).padStart(2,"0"),r=String(t.getHours()).padStart(2,"0"),n=String(t.getMinutes()).padStart(2,"0");return`${a}/${s} ${r}:${n}`}(a.created_at)})]}),!!a.change_note&&(0,b.jsx)("div",{className:"pattern-revision-note",children:a.change_note}),s?(0,b.jsxs)("div",{className:"pattern-revision-stats",children:[(0,b.jsxs)("span",{className:"pattern-revision-stat correct",children:["✓ ",n]}),(0,b.jsxs)("span",{className:"pattern-revision-stat wrong",children:["✗ ",i]}),o>0&&(0,b.jsxs)("span",{className:"pattern-revision-stat pending",children:["· ",o]}),null!=d&&(0,b.jsxs)("span",{className:"pattern-revision-stat accuracy",children:[d,"%"]}),(a.stats_asset||a.stats_tf)&&(0,b.jsxs)("span",{className:"pattern-revision-stat context",children:[[a.stats_asset,a.stats_tf].filter(
6Boolean).join(" "),a.stats_direction_rule&&"default"!==a.stats_direction_rule?` \xb7 ${a.stats_direction_rule}`:""]})]}):(0,b.jsx)("div",{className:"pattern-revision-stats muted",children:"— no winrate captured"}),!1===a.restorable_substrate&&(0,b.jsx)("div",{style:{fontSize:10,color:"var(--color-neutral)",marginTop:4,fontStyle:"italic"},title:"This revision was recorded before History v2 — it doesn't carry the pattern_spec / pine_source, so Restore can only revert name / description / direction / lookback. The detection logic stays as-is.",children:"⚠ metadata only — spec not captured (pre-upgrade revision)"}),(0,b.jsx)("button",{className:"pattern-revision-restore",disabled:r,onClick:()=>{let s=!1===a.restorable_substrate?`Restore r${a.rev_no} of "${e}"?
7
8This revision is from before the History upgrade — only name / description / direction / lookback will be restored. The pattern's detection logic (CPS spec or Pine knobs) will NOT change.`:`Rollback ${e} to revision r${a.rev_no}?`;window.confirm(s)&&l(t,a.id)},title:`Restore revision r${a.rev_no}`,children:"Restore"})]},a.id)})})]})})}function sc({patternKey:e,draftId:t,onClose:a,onApply:s,onReject:r}){let[n,l]=(0,_.useState)(null),[i,o]=(0,_.useState)(""),[c,d]=(0,_.useState)(!0);(0,_.useEffect)(()=>{let a=!0;return d(!0),o(""),(async()=>{try{let s=await (0,er.authGetJson)(`/api/patterns/${e}/drafts/${t}`);if(!a)return;s.ok&&s.data?l(s.data):o(s.error||"Failed to load draft")}catch(e){if(!a)return;o(e instanceof Error?e.message:String(e))}finally{a&&d(!1)}})(),()=>{a=!1}},[e,t]);let u=n?.pine_params?Object.entries(n.pine_params).slice(0,50):[],h="awaiting_approval"===(n?.status||"");return(0,b.jsx)("div",{className:"pattern-lab-revisions-modal-backdrop",onClick:a,children:(0,b.jsxs)("div",{className:"pattern-lab-revisions-modal",onClick:e=>e.stopPropagation(),children:[(0,b.jsxs)("div",{className:"pattern-lab-revisions-modal-head",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("div",{className:"pattern-lab-revisions-modal-title",children:"Patch Draft"}),(0,b.jsxs)("div",{className:"pattern-lab-revisions-modal-subtitle",children:[e," · draft ",t.slice(0,8),"…"]})]}),(0,b.jsx)("button",{className:"pattern-lab-revisions-modal-close",onClick:a,children:"×"})]}),c&&(0,b.jsx)("div",{className:"pattern-sidebar-empty",children:(0,b.jsx)(ak,{children:"Loading draft…"})}),i&&(0,b.jsx)("div",{className:"pattern-lab-params-error",children:i}),n&&(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)("div",{className:"patch-draft-meta",children:[(0,b.jsxs)("span",{children:["Status: ",(0,b.jsx)("code",{children:n.status})]}),n.intent&&(0,b.jsxs)("span",{children:["Intent: ",(0,b.jsx)("code",{children:n.intent})]}),n.source_lang&&(0,b.jsxs)("span",{children:["Source: ",(0,b.jsx)("code",{children:n.source_lang})]}),n.direction&&(0,b.jsxs)("span",{children:["Direction: ",(0,b.jsx)("code",{children:n.direction})]})]}),!!n.user_message&&(0,b.jsxs)("div",{className:"patch-draft-section",children:[(0,b.jsx)("strong",{children:"Change note"}),(0,b.jsx)("div",{className:"patch-draft-note",children:n.user_message})]}),!!n.apply_result&&n.apply_result.startsWith("Error")&&(0,b.jsxs)("div",{className:"patch-draft-section",children:[(0,b.jsx)("strong",{children:"Last apply error"}),(0,b.jsx)("pre",{className:"patch-draft-error-pre",children:n.apply_result}),(0,b.jsx)("div",{className:"patch-draft-hint",children:"This draft is still applyable — fix the underlying issue (e.g. tighten a knob, mark conflicting feedback) and click Apply again."})]}),u.length>0&&(0,b.jsxs)("div",{className:"patch-draft-section",children:[(0,b.jsxs)("strong",{children:["Tunable parameters (",u.length,")"]}),(0,b.jsxs)("table",{className:"patch-draft-params-table",children:[(0,b.jsx)("thead",{children:(0,b.jsxs)("tr",{children:[(0,b.jsx)("th",{children:"Knob"}),(0,b.jsx)("th",{children:"Default"}),(0,b.jsx)("th",{children:"Affects"})]})}),(0,b.jsx)("tbody",{children:u.map(([e,t])=>(0,b.jsxs)("tr",{children:[(0,b.jsx)("td",{children:(0,b.jsx)("code",{children:e})}),(0,b.jsx)("td",{children:(0,b.jsx)("code",{children:String(t?.default)})}),(0,b.jsx)("td",{children:(0,b.jsx)("code",{children:Array.isArray(t?.affects)?t.affects.join(","):"-"})})]},e))})]})]}),!!n.pine_source&&(0,b.jsxs)("div",{className:"patch-draft-section",children:[(0,b.jsx)("strong",{children:"Pine source"}),(0,b.jsx)("pre",{className:"patch-draft-source-pre",children:n.pine_source})]}),!n.pine_source&&!!n.calc_py&&(0,b.jsxs)("div",{className:"patch-draft-section",children:[(0,b.jsx)("strong",{children:"calc_py"}),(0,b.jsx)("pre",{className:"patch-draft-source-pre",children:n.calc_py})]}),(0,b.jsxs)("div",{style:{display:"flex",gap:8,marginTop:12},children:[(0,b.jsx)("button",{className:"pattern-btn",disabled:!h,onClick:()=>{s(e,t),a()},children:"Apply Patch"}),(0,b.jsx)("button",{className:"pattern-btn subtle",disabled:!h,onClick:()=>{r(e,t),a()},children:"Reject"}),(0,b.jsx)("button",{className:"pattern-btn subtle",onClick:a,children:"Close"})]})]})]})})}function sd(e){return e?e.close>e.open?"up":e.close<e.open?"down":"flat":"flat"}function su({detections:e,feedbackMap:t,onNavigate:a,onFeedback:s,patternName:r,color:n,candles:l,patternDirection:i,windowStats:o,windowStatsLoading:c,onComputeWindowStats:d,windowStatsYears:u=2,onWindowStatsYearsChange:h,directionRule:p}){let m=(0,_.useMemo)(()=>(function(e,t,a,s){let r={total:e.length,correct:0,wrong:0,pending:0,accuracy:null};if(0===e.length||t.length<2)return r;let n=new Map;for(let e=0;e<t.length;e+=1)n.set(t[e].time,e);let l=(s||"").trim().toLowerCase();for(let s of e){let e,i=n.get(s.time);if(null==i||i+1>=t.length){r.pending+=1;continue}let o=t[i],c=t[i+1],d=i>0?t[i-1]:null,u=sd(o);switch(l){case"follow_confirmation":e=u;break;case"opposite_confirmation":e="up"===u?"down":"down"===u?"up":"flat";break;case"fixed_up":e="up";break;case"fixed_down":e="down";break;case"follow_streak":e=d?sd(d):u;break;default:e="bullish"===a?"up":"bearish"===a?"down":u}let h=sd(c);"flat"===h||"flat"===e?r.pending+=1:h===e?r.correct+=1:r.wrong+=1}let i=r.correct+r.wrong;
8return r.accuracy=0===i?null:r.correct/i,r})(e,l,i,p),[e,l,i,p]),x=(0,_.useMemo)(()=>{let e=(p||"").trim().toLowerCase();return e&&"default"!==e&&"infer"!==e?"follow_confirmation"===e?"follow trigger candle":"opposite_confirmation"===e?"opposite of trigger":"fixed_up"===e?"always up":"fixed_down"===e?"always down":"follow_streak"===e?"follow prior streak":e:`pattern direction (${i})`},[p,i]);return(0,b.jsxs)("div",{className:"pattern-detections",children:[(0,b.jsxs)("div",{className:"pattern-detections-header",children:[(0,b.jsxs)("span",{children:[r," Detections"]}),(0,b.jsx)("span",{className:"pattern-detections-count",children:m.total})]}),(0,b.jsxs)("div",{className:"pattern-detections-stats",title:`Next-bar correct under rule: ${x}. Computed over the chart's visible window — updates live as you tune knobs.`,children:[(0,b.jsx)("span",{className:"pattern-detections-stats-label",title:"Stats over the candles currently loaded in the chart",children:"shown"}),(0,b.jsxs)("span",{className:"pattern-detections-stat correct",children:[(0,b.jsx)("span",{className:"stat-glyph",children:"✓"})," ",m.correct]}),(0,b.jsxs)("span",{className:"pattern-detections-stat wrong",children:[(0,b.jsx)("span",{className:"stat-glyph",children:"✗"})," ",m.wrong]}),m.pending>0&&(0,b.jsxs)("span",{className:"pattern-detections-stat pending",title:"No next bar in view or flat candle",children:[(0,b.jsx)("span",{className:"stat-glyph",children:"·"})," ",m.pending]}),(0,b.jsx)("span",{className:"pattern-detections-stat rule",title:"Direction rule driving the prediction",children:x}),null!=m.accuracy&&(0,b.jsxs)("span",{className:"pattern-detections-stat accuracy",children:[(100*m.accuracy).toFixed(0),"%"]})]}),(0,b.jsxs)("div",{className:`pattern-detections-stats pattern-detections-stats-window${c?" loading":""}`,title:"Server-computed accuracy over a wide lookback. Reflects real history, not just the loaded chart slice. Click the button to fetch fresh stats after tuning.",children:[(0,b.jsxs)("select",{className:"pattern-detections-stats-label pattern-detections-stats-year-select",title:"Window size for server-side stats. Tap to change, then hit refresh to recompute.",value:u,onChange:e=>h?.(parseInt(e.target.value,10)),disabled:!h||c,children:[(0,b.jsx)("option",{value:1,children:"1y"}),(0,b.jsx)("option",{value:2,children:"2y"}),(0,b.jsx)("option",{value:3,children:"3y"}),(0,b.jsx)("option",{value:4,children:"4y"}),(0,b.jsx)("option",{value:5,children:"5y"})]}),o?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)("span",{className:"pattern-detections-stat correct",children:[(0,b.jsx)("span",{className:"stat-glyph",children:"✓"})," ",o.correct]}),(0,b.jsxs)("span",{className:"pattern-detections-stat wrong",children:[(0,b.jsx)("span",{className:"stat-glyph",children:"✗"})," ",o.wrong]}),o.pending>0&&(0,b.jsxs)("span",{className:"pattern-detections-stat pending",title:"No next bar in window or flat candle",children:[(0,b.jsx)("span",{className:"stat-glyph",children:"·"})," ",o.pending]}),(0,b.jsxs)("span",{className:"pattern-detections-stat rule",title:`${o.total} total detections over ${o.window_bars.toLocaleString()} bars`,children:[o.total," total"]}),null!=o.accuracy&&(0,b.jsxs)("span",{className:"pattern-detections-stat accuracy",children:[(100*o.accuracy).toFixed(0),"%"]})]}):(0,b.jsx)("span",{className:"pattern-detections-stat pending",children:c?"computing…":"not computed yet"}),d&&(0,b.jsx)("button",{type:"button",className:"pattern-detections-stats-compute-btn",onClick:d,disabled:c,title:"Fetch 2y stats from the server. Cached after first call per pattern + window.",children:c?"computing…":o?"refresh":"compute"})]}),(0,b.jsxs)("div",{className:"pattern-detections-list",children:[0===e.length&&(0,b.jsxs)("div",{className:"pattern-detections-empty",children:["No detections in the loaded chart window. The 2y stats above run independently — click ",(0,b.jsx)("strong",{children:"compute"})," to see how this pattern performs over the last 2 years."]}),e.map(e=>{let r=t[1e3*e.time]??null;return(0,b.jsxs)("div",{className:"pattern-detection-row",children:[(0,b.jsxs)("button",{className:"pattern-detection-time",onClick:()=>a(e.time),title:"Jump to candle",children:[(0,b.jsx)("span",{className:"pattern-detection-dot",style:{background:"correct"===r?"#00d4aa":"incorrect"===r?"#555":n}}),a9(e.time)]}),(0,b.jsx)("span",{className:"pattern-detection-conf",children:null==e.confidence?"N/A":`${(100*e.confidence).toFixed(0)}%`}),(0,b.jsxs)("div",{className:"pattern-detection-actions",children:[(0,b.jsx)("button",{className:`pattern-det-fb${"correct"===r?" active":""}`,onClick:()=>s(e.time,"correct"),title:"Correct",style:{color:"#00d4aa"},children:"✓"}),(0,b.jsx)("button",{className:`pattern-det-fb${"incorrect"===r?" active":""}`,onClick:()=>s(e.time,"incorrect"),title:"Incorrect",style:{color:"#ff4976"},children:"✗"})]})]},e.time)}
8)]})]})}function sh({blocks:e,onApplyPatch:t,onRejectPatch:a,onViewPatchChanges:s}){return e&&0!==e.length?e.map((e,r)=>{switch(e.type){case"text":return(0,b.jsx)(ei.default,{content:e.content??""},r);case"tool":return(0,b.jsx)(ec.default,{tool:e},r);case"indicator":return(0,b.jsx)(ed.default,{indicator:e.indicator},r);case"pattern_patch_draft":return(0,b.jsxs)("div",{className:"chat-tool-block",style:{marginTop:8},children:[(0,b.jsx)("div",{className:"chat-tool-header",children:(0,b.jsx)("strong",{children:"Patch Draft"})}),(0,b.jsxs)("div",{className:"chat-tool-result",children:["Pattern: ",(0,b.jsx)("code",{children:e.pattern_key}),(0,b.jsx)("br",{}),"Draft: ",(0,b.jsx)("code",{children:e.draft_id}),(0,b.jsx)("br",{}),"Status: ",(0,b.jsx)("code",{children:e.status}),e.intent?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)("br",{}),"Intent: ",(0,b.jsx)("code",{children:e.intent})]}):null,e.source_lang?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)("br",{}),"Source: ",(0,b.jsx)("code",{children:e.source_lang})]}):null]}),(0,b.jsxs)("div",{style:{display:"flex",gap:8,marginTop:8,flexWrap:"wrap"},children:[(0,b.jsx)("button",{className:"pattern-btn",onClick:()=>t?.(String(e.pattern_key||""),String(e.draft_id||"")),children:"Apply Patch"}),(0,b.jsx)("button",{className:"pattern-btn subtle",onClick:()=>a?.(String(e.pattern_key||""),String(e.draft_id||"")),children:"Reject"}),(0,b.jsx)("button",{className:"pattern-btn subtle",onClick:()=>s?.(String(e.pattern_key||""),String(e.draft_id||"")),children:"View changes"})]})]},r);case"pattern_patch_applied":return(0,b.jsxs)("div",{className:"chat-tool-block",style:{marginTop:8},children:[(0,b.jsx)("div",{className:"chat-tool-header",children:(0,b.jsx)("strong",{children:"Patch Applied"})}),(0,b.jsxs)("div",{className:"chat-tool-result",children:["Pattern: ",(0,b.jsx)("code",{children:e.pattern_key}),(0,b.jsx)("br",{}),"Draft: ",(0,b.jsx)("code",{children:e.draft_id}),e.already_applied?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)("br",{}),"Already applied."]}):null]})]},r);case"pattern_patch_rejected":return(0,b.jsxs)("div",{className:"chat-tool-block",style:{marginTop:8},children:[(0,b.jsx)("div",{className:"chat-tool-header",children:(0,b.jsx)("strong",{children:"Patch Rejected"})}),(0,b.jsxs)("div",{className:"chat-tool-result",children:["Pattern: ",(0,b.jsx)("code",{children:e.pattern_key}),(0,b.jsx)("br",{}),"Draft: ",(0,b.jsx)("code",{children:e.draft_id})]})]},r);default:return null}}):null}function sp(){let e,t=function(){let[e,t]=(0,_.useState)([]),[a,s]=(0,_.useState)(null),[r,n]=(0,_.useState)(null),[l,i]=(0,_.useState)([]),[o,c]=(0,_.useState)({}),[d,u]=(0,_.useState)([]),[h,p]=(0,_.useState)(!1),[m,x]=(0,_.useState)(!1),[g,f]=(0,_.useState)(!1),[b,v]=(0,_.useState)(null),[y,j]=(0,_.useState)(null),[w,N]=(0,_.useState)(!1),k=(0,_.useRef)(0),S=(0,_.useCallback)(async(e,t,a,s)=>{let r=k.current+1;k.current=r,N(!0);try{let n=await (0,er.authPostJson)(`/api/patterns/${e}/stats/window`,{asset:t,tf:a,lookback_days:s?.lookbackDays??730,direction_rule:s?.directionRule});if(r!==k.current)return;n.ok&&n.data&&j(n.data)}catch{r===k.current&&j(null)}finally{r===k.current&&N(!1)}},[]),[$,C]=(0,_.useState)(null),[M,E]=(0,_.useState)(!1),A=(0,_.useRef)(0),T=(0,_.useRef)(null),F=(0,_.useRef)(null),P=(0,_.useRef)(null),R=(0,_.useRef)(0),O=(0,_.useRef)(null),L=(0,_.useRef)(null),I=(0,_.useCallback)(async()=>{try{let e=await (0,er.authGetJson)("/api/patterns");e.ok&&t(e.data||[])}catch{}},[]);(0,_.useEffect)(()=>{I()},[I]);let D=(0,_.useCallback)(async e=>{if(s(e),i([]),c({}),n(null),u([]),v(null),L.current=e?.key??null,e){try{let t=await (0,er.authGetJson)(`/api/patterns/${e.key}`);t.ok&&t.data&&s(t.data)}catch{}try{let t=await (0,er.authGetJson)(`/api/patterns/${e.key}/stats`);t.ok&&n(t.data)}catch{}try{let t=await (0,er.authGetJson)(`/api/patterns/${e.key}/feedback`);if(t.ok&&t.data){let e={};for(let a of t.data)e[a.candle_time_ms]=a.feedback;c(e)}}catch{}try{p(!0);let t=await (0,er.authGetJson)(`/api/patterns/${e.key}/revisions?limit=50`);t.ok&&t.data&&u(t.data)}catch{}finally{p(!1)}try{let t=await (0,er.authGetJson)(`/api/patterns/${e.key}/strategy`);if(t.ok&&t.data){let e=t.data.params||{},a=String(e.direction_rule_override||"").trim().toLowerCase();v(a||null)}}catch{}}},[]),z=(0,_.useCallback)(async()=>{let e=L.current;if(e)try{let t=await (0,er.authGetJson)(`/api/patterns/${e}`);t.ok&&t.data&&s(t.data)}catch{}},[]),B=(0,_.useCallback)(e=>{e&&e.key&&(s(t=>t&&t.key===e.key?{...t,...e}:t),t(t=>t.map(t=>t.key===e.key?{...t,...e}:t)))},[]),W=(0,_.useCallback)(async e=>{let t=e||L.current;if(t)try{p(!0);let e=await (0,er.authGetJson)(`/api/patterns/${t}/revisions?limit=50`);e.ok&&e.data&&u(e.data)}catch{}finally{p(!1)}},[]),U=(0,_.useCallback)((e,t)=>{let a=t||L.current;if(!a)return;O.current&&(clearTimeout(O.current),O.current=null);let r=0===e.length,n=async()=>{try{await (0,er.authFetch)(`/api/patterns/${a}`,{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({chat_messages:e})})}catch{}};if(r){s(e=>e&&e.key===a?{...e,chat_messages:[]}:e),n();return}O.current=setTimeout(n,800)}
8,[]),H=(0,_.useCallback)(async(e,t,a,s,r,n)=>{if(!e.length){T.current&&(T.current.abort(),T.current=null),F.current=null,E(!1),i([]),C(null);return}let l=Number(e[0]?.time||0),c=Number(e[e.length-1]?.time||0),d=`${t.length}:${function(e){let t=0x811c9dc5;for(let a=0;a<e.length;a+=1)t^=e.charCodeAt(a),t=Math.imul(t,0x1000193);return(t>>>0).toString(36)}(t)}`,u=`${a}|${s}|${r}|${l}|${c}|${e.length}|${d}`,h=Date.now(),p=!!n?.fresh;if(!p&&(F.current===u||P.current===u&&h-R.current<1e3))return;let m=A.current+1;A.current=m,R.current=h,F.current=u,T.current&&T.current.abort();let x=new AbortController;T.current=x,E(!0);try{let e=await (0,er.authFetch)(`/api/patterns/${a}/detect`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({asset:s,tf:r,start_time:l,end_time:c,params:{},fresh:p}),signal:x.signal});if(!e.ok){let t=await e.text();throw Error(`POST /api/patterns/${a}/detect failed: ${e.status} ${t}`)}let t=await e.json();if(m!==A.current)return;let n=(t?.data?.detections||[]).filter(e=>Number(e?.detected||0)>0&&Number(e?.time||0)>0).map(e=>({time:Number(e.time),detected:Number(e.detected||1),confidence:null==e.confidence?null:Number.isFinite(Number(e.confidence))?Number(e.confidence):null,patternKey:a,feedback:o[1e3*Number(e.time)]??null,idx:Number.isFinite(Number(e.idx))?Number(e.idx):void 0,streak_len_effective:null==e.streak_len_effective?null:Number.isFinite(Number(e.streak_len_effective))?Number(e.streak_len_effective):null,streak_dir:null==e.streak_dir?null:Number.isFinite(Number(e.streak_dir))?Number(e.streak_dir):null,context_indices:Array.isArray(e.context_indices)?e.context_indices.map(e=>Number(e)).filter(e=>Number.isFinite(e)).map(e=>Math.floor(e)):null}));i(n),C(null),P.current=u}catch(e){if(e?.name==="AbortError"||m!==A.current)return;console.warn("Pattern detection API error:",e),i([]),C(e?.message||"Server detection error")}finally{m===A.current&&E(!1),T.current===x&&(T.current=null),F.current===u&&(F.current=null)}},[o]),q=(0,_.useCallback)(async e=>{i([]),c({}),n(null);try{await (0,er.authFetch)(`/api/patterns/${e}/feedback`,{method:"DELETE"});let[t,a]=await Promise.all([(0,er.authGetJson)(`/api/patterns/${e}/stats`),(0,er.authGetJson)(`/api/patterns/${e}/feedback`)]);if(t.ok&&n(t.data),a.ok&&a.data){let e={};for(let t of a.data)e[t.candle_time_ms]=t.feedback;c(e)}return!0}catch{return!1}},[]);(0,_.useEffect)(()=>()=>{T.current&&T.current.abort()},[]);let V=(0,_.useCallback)(async(e,t,a,s,r,l)=>{c(e=>({...e,[t]:r}));try{await (0,er.authPostJson)(`/api/patterns/${e}/feedback`,{candle_time_ms:t,asset:a,tf:s,feedback:r,candle_data:l});let i=await (0,er.authGetJson)(`/api/patterns/${e}/stats`);i.ok&&n(i.data)}catch{c(e=>{let a={...e};return delete a[t],a})}},[]),G=(0,_.useCallback)(async e=>{try{await (0,er.authFetch)(`/api/patterns/${e}`,{method:"DELETE"}),t(t=>t.filter(t=>t.key!==e)),a?.key===e&&(s(null),i([]),n(null),u([]),L.current=null)}catch{}},[a]),J=(0,_.useCallback)(async(e,t,r)=>{try{x(!0);let n=await (0,er.authPostJson)(`/api/patterns/${e}/rollback`,{revision_id:t,note:r||""});if(!n.ok)return{ok:!1};return n.data?.pattern?s(n.data.pattern):a?.key===e&&await z(),await W(e),{ok:!0,partial:!!n.data?.partial_restore,message:n.data?.partial_restore_message||void 0}}catch{return{ok:!1}}finally{x(!1)}},[a?.key,z,W]);return{patterns:e,activePattern:a,stats:r,detections:l,detectionError:$,detecting:M,feedbackMap:o,revisions:d,revisionsLoading:h,rollbackLoading:m,loading:g,refreshPatterns:I,selectPattern:D,runDetection:H,clearPatternDetections:q,submitFeedback:V,deletePattern:G,requestRetrain:(0,_.useCallback)(async e=>{try{let t=await (0,er.authPostJson)(`/api/patterns/${e}/retrain`,{});if(t.ok&&t.data?.prompt)return t.data.prompt}catch{}return null},[]),uploadImage:(0,_.useCallback)(async e=>new Promise(t=>{let a=new FileReader;a.onload=async()=>{let e=a.result;try{let a=await (0,er.authPostJson)("/api/patterns/upload-image",{image:e});if(a.ok)return void t(a.data.image_url)}catch{}t(null)},a.onerror=()=>t(null),a.readAsDataURL(e)}),[]),saveChatMessages:U,refreshActivePattern:z,applyPatternUpdate:B,refreshRevisions:W,rollbackPatternRevision:J,strategyDirectionRule:b,setStrategyDirectionRule:v,windowStats:y,windowStatsLoading:w,fetchWindowStats:S,setWindowStats:j}}(),a=(0,_.useRef)(null),s=(0,_.useRef)(null),r=(0,_.useRef)(null),n=(0,_.useRef)(null),[l,i]=(0,_.useState)("BTC"),[o,c]=(0,_.useState)("15m"),[d,u]=(0,_.useState)(null),[h,p]=(0,_.useState)(null),[m,x]=(0,_.useState)(!1),[g,f]=(0,_.useState)("lab"),[v,j]=(0,_.useState)([]),[w,N]=(0,_.useState)(!1),[k,S]=(0,_.useState)(null),[$,C]=(0,_.useState)(!1),[M,E]=(0,_.useState)(!1),[A,T]=(0,_.useState)("after_confirmation_close"),[F,P]=(0,_.useState)("infer"),[R,O]=(0,_.useState)(!0),[I,D]=(0,_.useState)(!1),[z,B]=(0,_.useState)(!1),[W,U]=(0,_.useState)(!1),[H,q]=(0,_.useState)(""),[V,G]=(0,_.useState)(""),[J,Y]=(0,_.useState)(null),[K,X]=(0,_.useState)(null),Z=(0,_.useCallback)(e=>{t.saveChatMessages(e)},[t.saveChatMessages]),Q=(0,es.default)({initialMessages:t.activePattern?.chat_messages??[],onMessagesChange:Z}),ee=(0,_.useRef)(null),et=(0,_.useRef)(0),ea=(0,_.useRef)(null),en=(0,_.useCallback)(e=>{let t=0;for(let a of e||[])if(a?.blocks)for(let e of a.blocks)e?.type==="indicator"&&(t+=1);return t},[]);(0,_.useEffect)(()=>{let e=t.activePattern?.key??null;if(e===n.current)return;if(n.current=e,e&&e===ee.current){ee.current=null;return}let a=t.activePattern?.chat_messages;a&&a.length>0?(Q.reset(a),et.current=en(a)):(Q.reset([]),et.current=0)},[t.activePattern,en]);let{candles:el,realtimeCandle:ei,loadMore:ec,loadBulk:ed}=L(l,o),{candles:eu,loadBulk:eh}=L(l,"5m");(0,_.useEffect)(()=>{j([])},[l,o]),(0,_.useEffect)(()=>{S(null),"15m"!==o&&N(!1),C(!1)},[l,o]),(0,_.useEffect)(()=>{!w||"15m"!==o||null!=k||el.length&&S(Number(el[el.length-1].time))},[w,o,k,el]),(0,_.useEffect)(()=>
8{if(!w||"15m"!==o||null==k||!eu.length)return;let e=Number(k);if(!Number.isFinite(e))return;let t=Number(eu[0]?.time??0),a=Number(eu[eu.length-1]?.time??0);if(!(t>e)&&!(a<e+600))return;let s=!1;return E(!0),(async()=>{try{await eh(5)}finally{s||E(!1)}})(),()=>{s=!0}},[w,o,k,eu,eh]),(0,_.useEffect)(()=>{t.activePattern&&0!==el.length&&t.runDetection(el,t.activePattern.calc_py,t.activePattern.key,l,o)},[t.activePattern,el,l,o,t.runDetection]),(0,_.useEffect)(()=>{t.setWindowStats(null)},[t.activePattern?.key,l,o,t.setWindowStats]);let[ep,em]=(0,_.useState)(2),ex=(0,_.useCallback)(()=>{let e=t.activePattern;e&&t.fetchWindowStats(e.key,l,o,{lookbackDays:365*Math.max(1,Math.min(ep,5)),directionRule:t.strategyDirectionRule})},[t.activePattern,l,o,ep,t.fetchWindowStats,t.strategyDirectionRule]),eg=(0,_.useRef)(!1),ef=(0,_.useRef)(null),eb=(0,_.useRef)(null),e_=(0,_.useRef)(0),ev=(0,_.useRef)(0);(0,_.useEffect)(()=>{if(!t.activePattern||t.detectionError||t.detecting||0===el.length||t.detections.length>=30||eg.current)return;let e=t.activePattern.key;eb.current===e||(ef.current!==e&&(ef.current=e,e_.current=0,ev.current=t.detections.length,eb.current&&eb.current!==e&&(eb.current=null)),e_.current>=16||t.detections.length===ev.current&&e_.current>=6||(eg.current=!0,e_.current+=1,ev.current=t.detections.length,ed(5).then(t=>{eg.current=!1,t<=el.length&&(eb.current=e)})))},[t.activePattern,t.detectionError,t.detecting,t.detections.length,el.length,ed]),(0,_.useEffect)(()=>{let e=0,a=null,s=null;for(let t of Q.messages)if(t.blocks){for(let r of t.blocks)if("indicator"===r.type&&r.indicator){e++;let t=r.indicator,n=t.key?.startsWith("pattern_")?t.key.slice(8):null;n&&(a=n,s=t.name||n)}}if(e<=et.current||!a){et.current=e;return}et.current=e;let r=a,l=t.activePattern?.key===r;ea.current&&clearTimeout(ea.current),ea.current=setTimeout(()=>{t.refreshPatterns().then(()=>{t.saveChatMessages(Q.messages,r),l?t.refreshActivePattern():(ee.current=r,n.current=null,t.selectPattern({key:r,name:s}))})},1500)},[Q.messages]),(0,_.useEffect)(()=>{let e=null;for(let t of Q.messages)if(t.blocks)for(let a of t.blocks)a?.type==="pattern_patch_draft"&&a.pattern_key&&a.draft_id&&("awaiting_approval"===a.status||!a.status)?e={patternKey:String(a.pattern_key),draftId:String(a.draft_id)}:(a?.type==="pattern_patch_applied"||a?.type==="pattern_patch_rejected")&&e&&a.draft_id===e.draftId&&(e=null);Y(e)},[Q.messages]),(0,_.useEffect)(()=>{a.current&&(a.current.scrollTop=a.current.scrollHeight)},[Q.messages]),(0,_.useEffect)(()=>{m&&f("lab")},[m]);let ey=(0,_.useRef)(0);(0,_.useEffect)(()=>{let e=ey.current,t=Q.messages.length;if(ey.current=t,0===e||t<=e)return;let a=Q.messages[t-1];a&&"assistant"===a.role&&f("chat")},[Q.messages]);let ej=(0,_.useMemo)(()=>t.activePattern?"bullish"===t.activePattern.direction?"#00d4aa":"bearish"===t.activePattern.direction?"#ff4976":"#8491a7":"#8491a7",[t.activePattern]),ew=(0,_.useMemo)(()=>t.activePattern?t.detections.map(e=>({time:e.time,color:ej,label:t.activePattern.name,patternKey:e.patternKey,feedback:t.feedbackMap[1e3*e.time]??null,confidence:null==e.confidence?void 0:e.confidence})):[],[t.detections,t.activePattern,t.feedbackMap,ej]),eN=(0,_.useMemo)(()=>{if(!t.activePattern||0===el.length||0===t.detections.length)return[];let e=new Map;el.forEach((t,a)=>e.set(Number(t.time),a));let a=[],s=new Set,r=Math.max(2,Number(t.activePattern.lookback||0));for(let n of t.detections){let t=Number.isFinite(Number(n.idx))?Number(n.idx):e.get(Number(n.time))??-1;if(t<0||t>=el.length)continue;let l=Number(n.streak_dir??0),i=1===(Number.isFinite(l)&&(1===l||-1===l)?l:Number(el[t]?.close)>Number(el[t]?.open)?1:Number(el[t]?.close)<Number(el[t]?.open)?-1:0)?"belowBar":"aboveBar",o=[];if(Array.isArray(n.context_indices)&&n.context_indices.length>0){let e=n.context_indices.map(e=>Number(e)).filter(e=>Number.isFinite(e)).map(e=>Math.floor(e)).filter(e=>e>=0&&e<el.length);if(e.length>0){let a=e.indexOf(t);o=a>=0?e.slice(0,a):e.filter(e=>e!==t&&e<=t)}}if(0===o.length){let e=Number(n.streak_len_effective??r),a=Math.max(0,(Number.isFinite(e)?Math.max(2,Math.floor(e)):r)-1);if(a<=0)continue;o=[];for(let e=1;e<=a;e+=1){let s=t-a+(e-1);s>=0&&s<el.length&&o.push(s)}}for(let e=0;e<o.length;e+=1){let t=e+1,r=o[e];if(r<0||r>=el.length)continue;let n=el[r]?.time;if(null==n)continue;let l=`${n}|${t}|${i}`;s.has(l)||(s.add(l),a.push({time:n,position:i,shape:"circle",color:"rgba(126,166,255,0.95)",text:String(t)}))}}return a.sort((e,t)=>
8Number(e.time)-Number(t.time)),a},[t.activePattern,t.detections,el]),ek=(0,_.useCallback)(e=>{let t="5m"===o?30:"1h"===o?10:18;r.current?.focusTime(e,t)},[o]),eS=(0,_.useCallback)(e=>{if(!w||"15m"!==o)return;let t=Number(e?.time);Number.isFinite(t)&&(S(t),C(!0))},[w,o]),e$=(0,_.useCallback)((e,a)=>{if(!t.activePattern)return;let s=el.find(t=>t.time===e);t.submitFeedback(t.activePattern.key,1e3*e,l,o,a,s?{open:s.open,high:s.high,low:s.low,close:s.close}:void 0)},[el,l,o,t.activePattern,t.submitFeedback]),eC=(0,_.useCallback)(()=>{t.activePattern&&(t.selectPattern(t.activePattern),el.length>0&&t.runDetection(el,t.activePattern.calc_py,t.activePattern.key,l,o),eg.current=!1,ef.current=null,eb.current=null,e_.current=0,ev.current=0)},[t.activePattern,el,l,o,t.selectPattern,t.runDetection]),eM=(0,_.useCallback)(async()=>{!t.activePattern||window.confirm(`Clear all detection feedback for "${t.activePattern.name}" and re-detect fresh candles?`)&&(await t.clearPatternDetections(t.activePattern.key),el.length>0&&await t.runDetection(el,t.activePattern.calc_py,t.activePattern.key,l,o,{fresh:!0}),eg.current=!1,ef.current=null,eb.current=null,e_.current=0,ev.current=0)},[t.activePattern,t.clearPatternDetections,t.runDetection,el,l,o]),eE=(0,_.useMemo)(()=>{if(t.activePattern)return{active_pattern:{key:t.activePattern.key,name:t.activePattern.name,direction:t.activePattern.direction}}},[t.activePattern]),eA=(0,_.useCallback)(async e=>{let a=await t.requestRetrain(e);a&&Q.send(a,null,null,eE)},[t.requestRetrain,Q.send,eE]),eT=(0,_.useCallback)(e=>{let a=t.patterns.find(t=>t.key===e);a?p({...a}):t.activePattern?.key===e?p({...t.activePattern}):p(null)},[t.patterns,t.activePattern]),eF=(0,_.useCallback)(async(e,a)=>{if(e&&a){q(""),G("");try{let s=await (0,er.authFetch)(`/api/patterns/${e}/drafts/${a}/apply`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})}),r=await s.text();if(!s.ok){let s=r;try{let e=JSON.parse(r);s=String(e?.error||e?.detail||r)}catch{}q(`Apply patch failed: ${s}`),await t.refreshRevisions(e),console.warn(`apply patch failed for ${e}/${a}: ${r}`);return}await t.refreshPatterns(),await t.refreshActivePattern(),await t.refreshRevisions(e),G(`Patch applied: ${a}`),Y(e=>e&&e.draftId===a?null:e),Q.appendSystemNote?.(`✓ Patch applied (draft ${a.slice(0,8)}…)`),t.activePattern&&t.activePattern.key===e&&el.length>0&&await t.runDetection(el,t.activePattern.calc_py,e,l,o,{fresh:!0})}catch(e){q(`Apply patch failed: ${e instanceof Error?e.message:String(e)}`),console.error(e)}}},[t,el,l,o,Q]),eP=(0,_.useCallback)(async(e,a)=>{if(e&&a){q(""),G("");try{let s=await (0,er.authFetch)(`/api/patterns/${e}/drafts/${a}/reject`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({})}),r=await s.text();if(!s.ok){let a=r;try{let e=JSON.parse(r);a=String(e?.error||e?.detail||r)}catch{}q(`Reject patch failed: ${a}`),await t.refreshRevisions(e);return}await t.refreshRevisions(e),G(`Patch rejected: ${a}`),Y(e=>e&&e.draftId===a?null:e),Q.appendSystemNote?.(`✗ Patch rejected (draft ${a.slice(0,8)}…)`)}catch(e){q(`Reject patch failed: ${e instanceof Error?e.message:String(e)}`),console.error(e)}}},[t,Q]),eR=(0,_.useCallback)(async(e,a)=>{let s=await t.rollbackPatternRevision(e,a);s.ok&&(await t.refreshPatterns(),eC(),B(!1),U(!1),s.partial&&s.message&&window.alert(s.message))},[t.rollbackPatternRevision,t.refreshPatterns,eC]),eO=(0,_.useCallback)(()=>{B(!0),t.activePattern&&t.refreshRevisions(t.activePattern.key)},[t.activePattern,t.refreshRevisions]),eL=(0,_.useCallback)(()=>{U(!0),t.activePattern&&t.refreshRevisions(t.activePattern.key)},[t.activePattern,t.refreshRevisions]),eI=(0,_.useCallback)(async e=>{let a=e.target.files?.[0];if(!a)return;let r=await t.uploadImage(a);r&&u(r),s.current&&(s.current.value="")},[t.uploadImage]),eD=(0,_.useMemo)(()=>{if(!v.length||!el.length)return null;let e=[...v].sort((e,t)=>Math.min(e.startTime,e.endTime)-Math.min(t.startTime,t.endTime)).map(e=>{let t=Math.min(e.startTime,e.endTime),a=Math.max(e.startTime,e.endTime),s=el.filter(e=>e.time>=t&&e.time<=a);if(!s.length)return null;let r=0,n=0,l=0,i=0,o=0,c=0,d=s.map((e,t)=>{let a=t>0?s[t-1]:null,d=e.close>e.open?"UP":e.close<e.open?"DOWN":"FLAT";"UP"===d?r+=1:"DOWN"===d?n+=1:l+=1;let u=0!==e.open?Math.abs(e.close-e.open)/e.open:0,h=0!==e.open?Math.abs(e.high-e.low)/e.open:0;i+=u,o+=h,c+=e.volume||0;let p=a&&0!==a.close?(e.close-a.close)/a.close:0;return{time:e.time,iso:se(e.time),open:e.open,high:e.high,low:e.low,close:e.close,volume:e.volume||0,direction:d,body_pct:u,range_pct:h,close_ret1:p}}),u=s[0],h=s[s.length-1],p=0!==u.close?(h.close-u.close)/u.close:0;return{id:e.id,start_time:t,end_time:a,start_iso:se(t),end_iso:se(a),bars:s.length,summary:{up_bars:r,down_bars:n,flat_bars:l,net_move_pct:p,avg_body_pct:s.length?i/s.length:0,avg_range_pct:s.length?o/s.length:0,total_volume:c},candles:d}}
8).filter(Boolean);if(!e.length)return null;let t=Math.min(...e.map(e=>e.start_time)),a=el.filter(e=>e.time<t).slice(-20).map(e=>({time:e.time,iso:se(e.time),open:e.open,high:e.high,low:e.low,close:e.close,volume:e.volume||0}));return{asset:l,tf:o,selected_at:new Date().toISOString(),entry_intent:I?{timing:A,direction_rule:F,strict:R}:void 0,ranges:e,context_bars:a}},[l,o,el,v,I,A,F,R]),ez=(0,_.useMemo)(()=>eD?eD.ranges.reduce((e,t)=>e+t.bars,0):0,[eD]),eB=(0,_.useMemo)(()=>{if(!w||"15m"!==o||null==k)return[];let e=k+900,t=String(l||"BTC").toLowerCase();return eu.filter(t=>Number(t.time)>=k&&Number(t.time)<e).sort((e,t)=>Number(e.time)-Number(t.time)).map((e,a)=>{let s=e.close>e.open?"UP":e.close<e.open?"DOWN":"FLAT",r=0!==e.open?(e.close-e.open)/e.open*100:0;return{idx:a+1,time:Number(e.time),open:e.open,high:e.high,low:e.low,close:e.close,direction:s,movePct:r,slug:`${t}-updown-5m-${Number(e.time)}`}})},[w,o,k,eu,l]),eW=(0,_.useMemo)(()=>null==k||"15m"!==o?"":`${String(l||"BTC").toLowerCase()}-updown-15m-${k}`,[k,o,l]),eU=(0,_.useCallback)(()=>{j([]),x(!1)},[]),eH=(0,_.useCallback)(()=>{if(!eD)return;let e=`Analyze these selected ${eD.ranges.length} candle range(s) for pattern logic and detector rules.`;Q.send(e,null,null,eE,eD),eU()},[Q.send,eE,eD,eU]),eq=(0,_.useCallback)(async e=>{if(!d&&J&&J.patternKey&&J.draftId){let t=e.trim().toLowerCase(),a=/^(approve|approved|apply|apply patch|apply draft|apply the draft|yes apply|do it|go ahead|approve this draft( now)?|approve the draft|let'?s do it|ship it)\b/.test(t)||"yes"===t||"y"===t||"ok"===t||"okay"===t||"sure"===t||"go"===t||"proceed"===t,s=/^(reject|reject patch|reject draft|reject the draft|cancel|cancel draft|cancel the draft|no thanks|don'?t apply|discard)\b/.test(t)||"no"===t||"n"===t;if(a||s){Q.appendUserMessage?.({role:"user",content:e}),a?eF(J.patternKey,J.draftId):eP(J.patternKey,J.draftId),Y(null);return}}if(d){let t=e||"Analyze this candlestick chart screenshot and create a pattern detector for the pattern shown.";Q.send(t,null,d,eE,eD),u(null)}else Q.send(e,null,null,eE,eD);eD&&eU()},[d,J,Q,eE,eD,eU,eF,eP]),eV=(0,_.useCallback)(async e=>{e.preventDefault();let a=e.dataTransfer.files[0];if(a&&a.type.startsWith("image/")){let e=await t.uploadImage(a);e&&u(e)}},[t.uploadImage]),eG=(0,_.useCallback)(e=>{e.preventDefault()},[]);return(0,b.jsxs)("div",{className:`pattern-lab-layout mobile-tab-${g}`,onDrop:eV,onDragOver:eG,children:[(0,b.jsx)(sr,{patterns:t.patterns,loading:t.loading,activePattern:t.activePattern,stats:t.stats,revisionsCount:t.revisions.length,onSelect:t.selectPattern,onDelete:t.deletePattern,onRetrain:eA,onRefresh:eC,onClearDetections:eM,onOpenStrategy:eT,onOpenRevisions:eO}),(0,b.jsxs)("div",{className:"pattern-lab-center",children:[(0,b.jsxs)("div",{className:"pattern-lab-toolbar",children:[(0,b.jsx)("select",{value:l,onChange:e=>i(e.target.value),className:"pattern-lab-select",children:y.ASSET_OPTIONS.map(e=>(0,b.jsx)("option",{value:e.key,children:e.label},e.key))}),(0,b.jsx)("select",{value:o,onChange:e=>c(e.target.value),className:"pattern-lab-select",children:y.TIMEFRAME_OPTIONS.map(e=>(0,b.jsx)("option",{value:e,children:e},e))}),(0,b.jsx)("button",{className:`pattern-lab-select-range-btn${m?" active":""}`,onClick:()=>x(e=>!e),title:"Tap candles to add to your selection. Tap a selected candle again to remove it.",children:m?"Selecting":"Select Candles"}),(0,b.jsx)("button",{className:`pattern-lab-select-range-btn${w?" active":""}`,onClick:()=>N(e=>!e),disabled:"15m"!==o,title:"15m"===o?"Inspect 5m candles inside each 15m candle":"Switch timeframe to 15m to enable",children:w?"15m↔5m Trace ON":"15m↔5m Trace"}),v.length>0&&(0,b.jsxs)("button",{className:"pattern-lab-select-range-clear",onClick:()=>j([]),title:"Clear selected ranges",children:["Clear (",v.length,")"]}),t.activePattern&&(0,b.jsxs)("span",{className:`pattern-lab-active-badge${t.detectionError?" error":""}`,children:[t.activePattern.name,t.detectionError?(0,b.jsxs)("span",{className:"pattern-lab-detection-error",title:t.detectionError,children:["Error: ",t.detectionError.slice(0,60)]}):t.detections.length>0?(0,b.jsxs)("span",{className:"pattern-lab-detection-count",children:[t.detections.length," found"]}
8):(0,b.jsx)("span",{className:"pattern-lab-detection-count",style:{opacity:.5},children:"0 found"})]})]}),H?(0,b.jsx)("div",{className:"pattern-lab-params-error",children:H}):null,!H&&V?(0,b.jsx)("div",{className:"pattern-lab-params-error",style:{color:"var(--color-long)"},children:V}):null,(0,b.jsx)("div",{className:"pattern-lab-chart",children:(0,b.jsx)(aT,{ref:r,candles:el,realtimeCandle:ei,markers:eN,patternHighlights:ew,selectionMode:m,selectionRanges:v,onSelectionRangesChange:j,onCandleClick:w&&"15m"===o?eS:void 0,title:`${l}/USD`,subtitle:w&&"15m"===o?"15m (click candle for 5m OHLC breakdown)":o,onLoadMore:ec})}),w&&"15m"===o&&(0,b.jsxs)("div",{className:"pattern-lab-trace-panel",children:[(0,b.jsxs)("div",{className:"pattern-lab-trace-head",children:[(0,b.jsxs)("span",{children:["15m anchor: ",null!=k?a9(k):"-"]}),(0,b.jsxs)("span",{children:[eB.length,"/3 nested 5m candles • click any 15m candle"]})]}),(0,b.jsx)("div",{className:"pattern-lab-trace-empty",children:"Opens popup with candlesticks + Polymarket market times."})]}),w&&"15m"===o&&$&&(0,b.jsx)("div",{className:"pattern-lab-trace-modal-backdrop",onClick:()=>C(!1),children:(0,b.jsxs)("div",{className:"pattern-lab-trace-modal",onClick:e=>e.stopPropagation(),children:[(0,b.jsxs)("div",{className:"pattern-lab-trace-modal-head",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("div",{className:"pattern-lab-trace-modal-title",children:"Nested 5m Inside Selected 15m Candle"}),(0,b.jsxs)("div",{className:"pattern-lab-trace-modal-subtitle",children:["15m market: ",eW||"-"," (",null!=k?a7(k):"-"," → ",null!=k?a7(k+900):"-",")"]})]}),(0,b.jsx)("button",{className:"pattern-lab-trace-modal-close",onClick:()=>C(!1),children:"×"})]}),eB.length>0?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(st,{rows:eB}),(0,b.jsx)("div",{className:"pattern-lab-trace-table-wrap",children:(0,b.jsxs)("table",{className:"pattern-lab-trace-table",children:[(0,b.jsx)("thead",{children:(0,b.jsxs)("tr",{children:[(0,b.jsx)("th",{children:"#"}),(0,b.jsx)("th",{children:"5m Market Time (ET)"}),(0,b.jsx)("th",{children:"Slug"}),(0,b.jsx)("th",{children:"Dir"}),(0,b.jsx)("th",{children:"Move%"}),(0,b.jsx)("th",{children:"Open"}),(0,b.jsx)("th",{children:"High"}),(0,b.jsx)("th",{children:"Low"}),(0,b.jsx)("th",{children:"Close"})]})}),(0,b.jsx)("tbody",{children:eB.map(e=>(0,b.jsxs)("tr",{children:[(0,b.jsx)("td",{children:e.idx}),(0,b.jsxs)("td",{children:[a7(e.time)," → ",a7(e.time+300)]}),(0,b.jsx)("td",{className:"trace-slug",children:e.slug}),(0,b.jsx)("td",{className:`trace-dir-${e.direction.toLowerCase()}`,children:e.direction}),(0,b.jsxs)("td",{children:[e.movePct.toFixed(3),"%"]}),(0,b.jsx)("td",{children:e.open.toFixed(e.open>=100?2:4)}),(0,b.jsx)("td",{children:e.high.toFixed(e.high>=100?2:4)}),(0,b.jsx)("td",{children:e.low.toFixed(e.low>=100?2:4)}),(0,b.jsx)("td",{children:e.close.toFixed(e.close>=100?2:4)})]},`${e.time}-${e.idx}`))})]})})]}):(0,b.jsx)("div",{className:"pattern-lab-trace-empty",children:M?"Loading 5m candles for this 15m window...":"No 5m candles found for this 15m window yet."})]})}),t.activePattern&&(0,b.jsx)(si,{patternKey:t.activePattern.key,initialParams:t.activePattern.pine_params??null,asset:l,tf:o,direction:t.activePattern.direction,directionRule:t.strategyDirectionRule,patternName:t.activePattern.name,patternDescription:t.activePattern.description,patternPineSource:t.activePattern.pine_source??null,patternSpec:t.activePattern.pattern_spec??null,detecting:t.detecting,onPatternUpdated:t.applyPatternUpdate,onOpenHistory:eL,onDirectionRuleSaved:e=>t.setStrategyDirectionRule(e||null)},t.activePattern.key),t.activePattern&&(0,b.jsx)(su,{detections:t.detections,feedbackMap:t.feedbackMap,onNavigate:ek,onFeedback:e$,patternName:t.activePattern.name,color:ej,candles:el,patternDirection:t.activePattern.direction,directionRule:t.strategyDirectionRule,windowStats:t.windowStats,windowStatsLoading:t.windowStatsLoading,onComputeWindowStats:ex,windowStatsYears:ep,onWindowStatsYearsChange:em})]}),(0,b.jsxs)("div",{className:"pattern-lab-chat",children:[(0,b.jsxs)("div",{className:"pattern-lab-chat-header",children:[(0,b.jsx)("span",{children:"Pattern Agent"}),Q.messages.length>0&&(0,b.jsx)("button",{className:"pattern-lab-chat-clear",onClick:Q.clear,children:"Clear"})]}),eD&&(0,b.jsxs)("div",{className:"pattern-lab-selection-staging",children:[(0,b.jsxs)("div",{className:"pattern-lab-selection-staging-head",children:[(0,b.jsxs)("span",{children:["Selected ",eD.ranges.length," range(s), ",ez," candles"]}),(0,b.jsxs)("div",{className:"pattern-lab-selection-staging-actions",children:[(0,b.jsx)("button",{onClick:eH,disabled:Q.streaming,children:"Send To AI"}),(0,b.jsx)("button",{onClick:()=>j([]),children:"Clear"})]})]}),(0,b.jsxs)("div",{className:"pattern-lab-entry-intent",children:[(0,b.jsxs)("label",{className:"pattern-lab-entry-intent-check",children:[(0,b.jsx)("input",{type:"checkbox",checked:I,onChange:e=>D(e.target.checked)}),"Include entry intent with selected candles"]}),(0,b.jsxs)("div",{className:"pattern-lab-entry-intent-row",children:[(0,b.jsx)("label",{children:"Entry timing"}),(0,b.jsxs)("select",{value:A,onChange:e=>T(e.target.value),disabled:!I,children:[(0,b.jsx)("option",{value:"after_confirmation_close",children:"After confirmation close"}),(0,b.jsx)("option",{value:"next_open",children:"At next candle open"}),(0,b.jsx)("option",{value:"intra_confirmation",children:"During confirmation candle"})]})]}),(0,b.jsxs)("div",{className:"pattern-lab-entry-intent-row",children:[(0,b.jsx)("label",{children:"Direction rule"}),(0,b.jsxs)("select",{value:F,onChange:e=>P(e.target.value),disabled:!I,children:[(0,b.jsx)("option",{value:"infer",children:"Model infer direction"}),(0,b.jsx)("option",{value:"follow_confirmation",children:"Follow confirmation candle"}),(0,b.jsx)("option",{value:"opposite_confirmation",children:"Opposite confirmation candle"}),(0,b.jsx)("option",{value:"follow_streak",children:"Follow prior streak direction"}),(0,b.jsx)("option",{value:"fixed_up",children:"Always bet UP"}),(0,b.jsx)("option",{value:"fixed_down",children:"Always bet DOWN"})]})]}),(0,b.jsxs)("label",{className:"pattern-lab-entry-intent-check",children:[(0,b.jsx)("input",{type:"checkbox",checked:R,onChange:e=>O(e.target.checked),disabled:!I}),"Enforce strictly"]})]}),(0,b.jsx)("div",{className:"pattern-lab-selection-cards",children:eD.ranges.map(e=>(0,b.jsx)(ss,{range:e,onRemove:()=>j(t=>t.filter(t=>t.id!==e.id))},e.id))})]}),d&&(0,b.jsxs)("div",{className:"pattern-lab-image-preview",children:[(0,b.jsx)("img",{src:d,alt:"Upload preview"}),(0,b.jsx)("button",{onClick:()=>u(null),className:"pattern-lab-image-remove",children:"×"})]}),0!==Q.messages.length||d?(0,b.jsxs)("div",{className:"pattern-lab-chat-messages",ref:a,children:[Q.messages.map((e,t)=>(0,b.jsxs)("div",{className:`chat-msg-row ${e.role}`,children:[(0,b.jsx)("span",{className:"chat-msg-role",children:"user"===e.role?"You":"Agent"}),"user"===e.role?(0,b.jsxs)("div",{className:"chat-msg-user-text",children:[e.image_url&&(0,b.jsx)("img",{src:e.image_url,alt:"Uploaded screenshot",className:"chat-msg-user-image"}),e.selected_candles&&e.selected_candles.ranges?.length>0&&(0,b.jsxs)("div",{className:"chat-msg-selected-candles",children:[(0,b.jsxs)("div",{className:"chat-msg-selected-candles-head",children:["Candle selection: ",e.selected_candles.asset," ",e.selected_candles.tf," | ",e.selected_candles.ranges.length," range(s)"]}),e.selected_candles.entry_intent&&(0,b.jsxs)("div",{className:"chat-msg-selected-candles-intent",children:["Entry intent: ",function(e){switch(e){case"after_confirmation_close"
8:return"After confirmation close";case"next_open":return"At next candle open";case"intra_confirmation":return"During confirmation candle";default:return e}}(e.selected_candles.entry_intent.timing)," |"," ",function(e){switch(e){case"follow_confirmation":return"Follow confirmation candle";case"opposite_confirmation":return"Opposite confirmation candle";case"follow_streak":return"Follow prior streak direction";case"fixed_up":return"Always bet UP";case"fixed_down":return"Always bet DOWN";default:return"Model infer direction"}}(e.selected_candles.entry_intent.direction_rule)," |"," ","strict=",e.selected_candles.entry_intent.strict?"true":"false"]}),(0,b.jsx)("div",{className:"chat-msg-selected-candles-cards",children:e.selected_candles.ranges.map(e=>(0,b.jsx)(ss,{range:e,compact:!0},e.id))})]}),e.content]}):(0,b.jsx)(sh,{blocks:e.blocks??[],onApplyPatch:eF,onRejectPatch:eP,onViewPatchChanges:(e,t)=>X({patternKey:e,draftId:t})})]},t)),Q.streaming&&(0,b.jsxs)("div",{className:"chat-streaming-indicator",children:[(0,b.jsx)("span",{className:"chat-streaming-dot"}),"Thinking..."]})]}):(0,b.jsxs)("div",{className:"pattern-lab-chat-empty",children:[(0,b.jsx)("div",{children:"Create pattern detectors with AI."}),(0,b.jsxs)("div",{className:"pattern-lab-suggestions",children:[(0,b.jsx)("button",{onClick:()=>Q.send("Create a hammer candlestick pattern detector"),children:"Hammer pattern"}),(0,b.jsx)("button",{onClick:()=>Q.send("Create a bullish engulfing pattern detector"),children:"Bullish engulfing"}),(0,b.jsx)("button",{onClick:()=>Q.send("Create a doji candlestick pattern detector"),children:"Doji pattern"})]}),(0,b.jsxs)("div",{className:"pattern-lab-upload-hint",children:[(0,b.jsx)("button",{onClick:()=>s.current?.click(),children:"Upload screenshot"})," or drag & drop an image"]})]}),J&&(0,b.jsxs)("div",{className:"pattern-lab-pending-draft-hint",children:[(0,b.jsxs)("span",{children:["Pending patch draft — type ",(0,b.jsx)("code",{children:"approve"})," or ",(0,b.jsx)("code",{children:"reject"}),", or use the buttons on the draft card."]}),(0,b.jsx)("button",{type:"button",className:"pattern-lab-pending-draft-view",onClick:()=>X({patternKey:J.patternKey,draftId:J.draftId}),children:"View changes"})]}),(0,b.jsxs)("div",{className:"pattern-lab-chat-input",children:[(0,b.jsx)("input",{ref:s,type:"file",accept:"image/*",style:{display:"none"},onChange:eI}),(0,b.jsx)(eo.default,{onSend:eq,disabled:Q.streaming,placeholder:d?"Describe the pattern in the screenshot...":J?"type 'approve' to apply, or describe a refinement…":"Create a pattern or ask about detection..."})]})]}),h&&(0,b.jsx)(a4,{pattern:h,onClose:()=>p(null),onChanged:()=>t.refreshPatterns()},h.key),z&&t.activePattern&&(0,b.jsx)(so,{patternName:t.activePattern.name,patternKey:t.activePattern.key,revisions:t.revisions,revisionsLoading:t.revisionsLoading,rollbackLoading:t.rollbackLoading,onClose:()=>B(!1),onRollbackRevision:eR}),W&&t.activePattern&&(e=!!t.activePattern?.pine_source,(0,b.jsx)(so,{patternName:t.activePattern.name,patternKey:t.activePattern.key,revisions:t.revisions,revisionsLoading:t.revisionsLoading,rollbackLoading:t.rollbackLoading,onClose:()=>U(!1),onRollbackRevision:eR,filterChangeSource:e?"param_tune":void 0,title:e?"Param Tune History":"Spec History",emptyLabel:e?"No slider tunes yet. Drag a knob to record one.":"No spec changes yet."})),K&&(0,b.jsx)(sc,{patternKey:K.patternKey,draftId:K.draftId,onClose:()=>X(null),onApply:eF,onReject:eP}),(0,b.jsxs)("nav",{className:"pattern-lab-mobile-tabs","aria-label":"Pattern Lab sections",children:[(0,b.jsxs)("button",{type:"button",className:`pattern-lab-mobile-tab${"patterns"===g?" active":""}`,onClick:()=>f("patterns"),"aria-pressed":"patterns"===g,children:[(0,b.jsx)("span",{className:"pattern-lab-mobile-tab-icon","aria-hidden":!0,children:"≡"}),"Patterns"]}),(0,b.jsxs)("button",{type:"button",className:`pattern-lab-mobile-tab${"lab"===g?" active":""}`,onClick:()=>f("lab"),"aria-pressed":"lab"===g,children:[(0,b.jsx)("span",{className:"pattern-lab-mobile-tab-icon","aria-hidden":!0,children:"▤"}),"Lab"]}),(0,b.jsxs)("button",{type:"button",className:`pattern-lab-mobile-tab${"chat"===g?" active":""}`,onClick:()=>f("chat"),"aria-pressed":"chat"===g,children:[(0,b.jsx)("span",{className:"pattern-lab-mobile-tab-icon","aria-hidden":!0,
8children:"✦"}),"Chat"]})]})]})}function sm(e){let t=e.last_backtest?.summary;return t&&"object"==typeof t?"number"==typeof t.campaign_winrate_pct?t.campaign_winrate_pct:"number"==typeof t.winrate_pct?t.winrate_pct:null:null}function sx(e){let t=e.last_backtest?.summary;return t&&"object"==typeof t&&"number"==typeof t.pnl?t.pnl:null}function sg(e){let t=e.last_backtest?.summary;return t&&"object"==typeof t&&"number"==typeof t.maxdd?t.maxdd:null}function sf(e){let t=e.last_backtest?.summary;return t&&"object"==typeof t?"number"==typeof t.campaigns?t.campaigns:"number"==typeof t.bets?t.bets:null:null}function sb(e){if(null==e)return"—";let t=e<0?"-":"",a=Math.abs(e);return a>=1e3?`${t}$${(a/1e3).toFixed(1)}k`:`${t}$${a.toFixed(0)}`}function s_({onSelect:e,isAlreadyAdded:t,footer:a}){let[s,r]=(0,_.useState)([]),[n,l]=(0,_.useState)(!1),[i,o]=(0,_.useState)(null),[c,d]=(0,_.useState)(new Set),[u,h]=(0,_.useState)(new Set),[p,m]=(0,_.useState)(new Set),[x,g]=(0,_.useState)(!1),[f,v]=(0,_.useState)(0),[y,j]=(0,_.useState)("updated"),[w,N]=(0,_.useState)("desc"),k=(0,_.useCallback)(async()=>{l(!0),o(null);try{let e=await (0,er.authGetJson)("/api/strategy_presets");e.ok&&Array.isArray(e.data)?r(e.data):o("Failed to load presets")}catch(e){o(e?.message||"Failed to load presets")}finally{l(!1)}},[]);(0,_.useEffect)(()=>{k()},[k]);let S=(0,_.useMemo)(()=>{let e=new Set;for(let t of s)t.asset&&e.add(t.asset);return Array.from(e).sort()},[s]),$=(0,_.useMemo)(()=>{let e=new Set;for(let t of s)t.tf&&e.add(t.tf);let t=["5m","15m","1h","4h","1d"];return Array.from(e).sort((e,a)=>t.indexOf(e)-t.indexOf(a))},[s]),C=(0,_.useMemo)(()=>{let e=[];for(let t of s)if((!(c.size>0)||c.has(t.asset))&&(!(u.size>0)||u.has(t.tf))&&(!(p.size>0)||p.has(t.pattern_direction))&&(!x||t.last_backtest)){if(f>0){let e=sm(t);if(null==e||e<f)continue}e.push(t)}let t="asc"===w?1:-1;return e.sort((e,a)=>{let s=0,r=0;return("updated"===y?(s=new Date(e.updated_at||0).getTime()||0,r=new Date(a.updated_at||0).getTime()||0):"winrate"===y?(s=sm(e)??-1/0,r=sm(a)??-1/0):"pnl"===y?(s=sx(e)??-1/0,r=sx(a)??-1/0):"drawdown"===y?(s=sg(e)??1/0,r=sg(a)??1/0):"campaigns"===y&&(s=sf(e)??-1/0,r=sf(a)??-1/0),s<r)?-1*t:s>r?+t:0}),e},[s,c,u,p,x,f,y,w]),M=(0,_.useCallback)((e,t)=>{e(e=>{let a=new Set(e);return a.has(t)?a.delete(t):a.add(t),a})},[]);return(0,b.jsxs)("div",{className:"preset-card-picker",children:[(0,b.jsxs)("div",{className:"preset-card-picker-filters",children:[S.length>0&&(0,b.jsxs)("div",{className:"preset-card-picker-filter-group",children:[(0,b.jsx)("span",{className:"preset-card-picker-filter-label",children:"Asset"}),S.map(e=>(0,b.jsx)("button",{type:"button",className:`preset-card-picker-chip${c.has(e)?" active":""}`,onClick:()=>M(d,e),children:e},e))]}),$.length>0&&(0,b.jsxs)("div",{className:"preset-card-picker-filter-group",children:[(0,b.jsx)("span",{className:"preset-card-picker-filter-label",children:"TF"}),$.map(e=>(0,b.jsx)("button",{type:"button",className:`preset-card-picker-chip${u.has(e)?" active":""}`,onClick:()=>M(h,e),children:e},e))]}),(0,b.jsxs)("div",{className:"preset-card-picker-filter-group",children:[(0,b.jsx)("span",{className:"preset-card-picker-filter-label",children:"Direction"}),["bullish","bearish","neutral"].map(e=>(0,b.jsx)("button",{type:"button",className:`preset-card-picker-chip preset-card-picker-chip-dir-${e}${p.has(e)?" active":""}`,onClick:()=>M(m,e),children:e},e))]}),(0,b.jsxs)("label",{className:"preset-card-picker-toggle",children:[(0,b.jsx)("input",{type:"checkbox",checked:x,onChange:e=>g(e.target.checked)}),"only with backtest"]}),(0,b.jsxs)("div",{className:"preset-card-picker-filter-group",children:[(0,b.jsx)("span",{className:"preset-card-picker-filter-label",children:"Min winrate"}),(0,b.jsx)("input",{type:"range",min:0,max:90,step:5,value:f,onChange:e=>v(parseInt(e.target.value,10)||0),className:"preset-card-picker-winrate-slider"}),(0,b.jsx)("span",{className:"preset-card-picker-winrate-value",children:0===f?"any":`${f}%`})]}),(0,b.jsxs)("div",{className:"preset-card-picker-filter-group preset-card-picker-sort",children:[(0,b.jsx)("span",{className:"preset-card-picker-filter-label",children:"Sort"}),(0,b.jsxs)("select",{value:y,onChange:e=>j(e.target.value),className:"preset-card-picker-sort-key",children:[(0,b.jsx)("option",{value:"updated",children:"Last edited"}),(0,b.jsx)("option",{value:"winrate",children:"Winrate"}),(0,b.jsx)("option",{value:"pnl",children:"P&L"}),(0,b.jsx)("option",{value:"drawdown",children:"Drawdown"}),(0,b.jsx)("option",{value:"campaigns",children:"Trades"})]}),(0,b.jsx)("button",{type:"button",className:"preset-card-picker-sort-dir",onClick:()=>N(e=>"asc"===e?"desc":"asc"),title:"asc"===w?"Ascending":"Descending",children:"asc"===w?"↑":"↓"})]})]}),n&&0===s.length?(0,b.jsx)("div",{className:"preset-card-picker-empty",children:(0,b.jsx)(ak,{children:"Loading presets…"})}):i?(0,b.jsx)("div",{className:"preset-card-picker-empty preset-card-picker-error",children:i}):0===C.length?(0,b.jsx)("div",{className:"preset-card-picker-empty",children:0===s.length?"No saved presets yet. Save some from the Pattern Lab strategy overlay.":"No presets match your filters."}):(0,b.jsx)("div",{className:"preset-card-picker-grid",children:C.map(a=>{let s=`${a.pattern_key}::${a.name}`,r=sm(a),n=sx(a),l=sg(a),i=sf(a),o=!!t&&t(a);return(0,b.jsxs)("button",{type:"button",className:`preset-card${o?" already-added":""}`,onClick:()=>e(a),title:o?"Already in this aggregator (click to add again)":"Add this preset",children:[(0,b.jsxs)("div",{className:"preset-card-head",children:[(0,b.jsx)("span",{className:`preset-card-dir preset-card-dir-${a.pattern_direction}`,children:"bullish"===a.pattern_direction?"▲":"bearish"===a.pattern_direction?"▼":"◆"}),(0,b.jsx)("span",{className:"preset-card-pattern-name",title:a.pattern_name,children:a.pattern_name}),(0,b.jsxs)("span",{className:"preset-card-tf-badge",children:[a.asset," ",a.tf]})]}),(0,b.jsx)("div",{className:"preset-card-preset-name",children:a.name}),(0,b.jsxs)("div",{className:"preset-card-metrics",children:[(0,b.jsxs)("div",{className:"preset-card-metric",children:[(0,b.jsx)("span",{className:"preset-card-metric-label",children:"Winrate"}),(0,b.jsx)("span",{className:`preset-card-metric-value${null!=r&&r>=50?" good":null!=r&&r<40?" bad":""}`,children:null==r?"—":`${r.toFixed(0)}%`})]}),(0,b.jsxs)("div",{className:"preset-card-metric",children:[(0,b.jsx)("span",{className:"preset-card-metric-label",children:"P&L"}),(0,b.jsx)("span",{className:`preset-card-metric-value${null!=n&&n>0?" good":null!=n&&n<0?" bad":""}`,children:sb(n)})]}),(0,b.jsxs)("div",{className:"preset-card-metric",children:[(0,b.jsx)("span",{className:"preset-card-metric-label",children:"Max DD"}),(0,b.jsx)("span",{className:"preset-card-metric-value",children:sb(l)})]}),(0,b.jsxs)("div",{className:"preset-card-metric",children:[(0,b.jsx)("span",{className:"preset-card-metric-label",children:"Trades"}),(0,b.jsx)("span",{className:"preset-card-metric-value",children:i??"—"})]})]}),(0,b.jsxs)("div",{className:"preset-card-foot",children:[a.last_backtest?(0,b.jsx)("span",{className:"preset-card-foot-time",children:function(e){if(!e)return"never run";let t=new Date(e).getTime();if(!Number.isFinite(t))return"—";let a=Math.floor((Date.now()-t)/6e4);if(a<1)return"just now";if(a<60)return`${a}m ago`;let s=Math.floor(a/60);if(s<24)return`${s}h ago`;let r=Math.floor(s/24);if(r<30)return`${r}d ago`;let n=Math.floor(r/30);return`${n}mo ago`}(a.last_backtest_at)}):(0,b.jsx)("span",{className:"preset-card-foot-time muted",children:"no backtest yet"}),o&&(0,b.jsx)("span",{className:"preset-card-foot-added",children:"added"})]})]},s)})}),a]})}function sv({width:e,height:t,style:a,className:s=""}){let r="number"==typeof e?`${e}px`:e,n="number"==typeof t?`${t}px`:t;return(0,b.jsx)("span",{className:`skeleton ${s}`.trim(),style:{width:r,height:n,...a},"aria-hidden":"true"})}function sy({cols:e=4,height:t=14}){return(0,b.jsx)("tr",{children:Array.from({length:e}).map((e,a)=>(0,b.jsx)("td",{children:(0,b.jsx)(sv,{height:t,width:"80%"})},a))})}let sj=["2018","2019","2020","2021","2022","2023","2024","2025","2026","polymarket_4m","all"];function sw(e){if(!e)return"never";let t=new Date(e).getTime();if(!Number.isFinite(t))return"never";let a=Math.max(0,(Date.now()-t)/1e3);return a<60?`${Math.floor(a)}s ago`:a<3600?`${Math.floor(a/60)}m ago`:a<86400?`${Math.floor(a/3600)}h ago`:`${Math.floor(a/86400)}d ago`}function sN(e){return"number"==typeof e&&Number.isFinite(e)?`${e.toFixed(1)}%`:"—"}function sk(e){if("number"!=typeof e||!Number.isFinite(e))return"—";let t=e<0?"-":"",a=Math.abs(e);return a>=1e6?`${t}$${(a/1e6).toFixed(2)}M`:a>=1e3?`${t}$${(a/1e3).toFixed(2)}k`:`${t}$${a.toFixed(2)}`}function sS(e){let t=e?.summary;return t?"number"==typeof t.campaign_winrate_pct?t.campaign_winrate_pct:"number"==typeof t.winrate_pct?t.winrate_pct:null:null}function s$(e){return"number"==typeof e?.summary?.pnl?e.summary.pnl:null}function sC(e){return"number"==typeof e?.summary?.maxdd?e.summary.maxdd:null}function sM(){let e=function(){let[e,t]=(0,_.useState)([]),[a,s]=(0,_.useState)(null),[r,n]=(0,_.useState)(null),[l,i]=(0,_.useState)(!1),[o,c]=(0,_.useState)(null),[d,u]=(0,_.useState)(!1),[h,p]=(0,_.useState)(!1),[m,x]=(0,_.useState)(null),g=(0,_.useCallback)(async()=>{i(!0),c(null);try{let e=await (0,er.authGetJson)("/api/aggregators");if(!e.ok)throw Error(e.error||"load_failed");t(Array.isArray(e.data)?e.data:[])}catch(e){c(String(e?.message??e))}finally{i(!1)}},[]);(0,_.useEffect)(()=>{g().catch(()=>{})},[g]);let f=(0,_.useCallback)(async e=>{i(!0),c(null);try{let t=await (0,er.authGetJson)(`/api/aggregators/${e}`);if(!t.ok||!t.data)throw Error(t.error||"load_failed");s(e),n({...t.data,strategies:[...t.data.strategies||[]]}),x(null)}catch(e){c(String(e?.message??e))}finally{i(!1)}},[]),b=(0,_.useCallback)(()=>{s(null),n(null),x(null)},[]),v=(0,_.useCallback)(async e=>{c(null);let t=await (0,er.authPostJson)("/api/aggregators",{name:e.name,strategies:e.strategies||[],notes:e.notes||""});if(!t.ok||!t.data)throw Error(t.error||"create_failed");return await g(),t.data},[g]),y=(0,_.useCallback)(e=>{n(t=>t?{...t,...e}:t)},[]),j=(0,_.useCallback)(async()=>
8{if(r&&a){u(!0),c(null);try{let e=await (0,er.authFetch)(`/api/aggregators/${a}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:r.name,notes:r.notes,strategies:r.strategies,capital_usd:r.capital_usd,selected_windows:r.selected_windows})}),t=await e.json();if(!e.ok||!t.ok)throw Error(t.error||`save_failed (${e.status})`);t.data&&n({...t.data,strategies:[...t.data.strategies||[]]}),await g()}catch(e){throw c(String(e?.message??e)),e}finally{u(!1)}}},[r,a,g]),w=(0,_.useCallback)(async e=>{c(null);let t=await (0,er.authFetch)(`/api/aggregators/${e}`,{method:"DELETE"});if(!t.ok){let e=await t.text();throw Error(`delete_failed (${t.status}): ${e}`)}a===e&&b(),await g()},[a,b,g]),N=(0,_.useCallback)(e=>{n(t=>{if(!t)return t;let a=[...t.strategies||[],e];return{...t,strategies:a}})},[]),k=(0,_.useCallback)(e=>{n(t=>{if(!t)return t;let a=[...t.strategies||[]];return a.splice(e,1),{...t,strategies:a}})},[]),S=(0,_.useCallback)((e,t)=>{n(a=>{if(!a)return a;let s=[...a.strategies||[]],r=e+t;if(r<0||r>=s.length)return a;[s[e],s[r]]=[s[r],s[e]];let n=s.map((e,t)=>({...e,priority:t}));return{...a,strategies:n}})},[]),$=(0,_.useCallback)((e,t)=>{n(a=>{if(!a)return a;let s=[...a.strategies||[]];return e<0||e>=s.length?a:(s[e]={...s[e],concurrency:t},{...a,strategies:s})})},[]),C=(0,_.useCallback)((e,t,a)=>{n(s=>{if(!s)return s;let r=[...s.strategies||[]];if(e<0||e>=r.length)return s;let n={...r[e].params_override||{}};null==a||""===a?delete n[t]:n[t]=a;let l=Object.keys(n).length>0?n:null;return r[e]={...r[e],params_override:l},{...s,strategies:r}})},[]),M=(0,_.useCallback)(async()=>{if(a){p(!0),x(null);try{let e=await (0,er.authPostJson)(`/api/aggregators/${a}/backtest`,{});if(!1===e.ok)throw Error(e.error||"backtest_failed");return n(t=>t?{...t,last_backtest:e,last_backtest_at:new Date().toISOString()}:t),await g(),e}catch(e){throw x(String(e?.message??e)),e}finally{p(!1)}}},[a,g]),[E,A]=(0,_.useState)(null),[T,F]=(0,_.useState)(!1),[P,R]=(0,_.useState)(null),O=(0,_.useCallback)(async()=>{if(a)try{let e=await (0,er.authGetJson)(`/api/aggregators/${a}/paper/status`);if(!e.ok)return void R(e.error||"load_failed");A(e.data||{sessions:[]}),R(null)}catch(e){R(String(e?.message??e))}},[a]),L=(0,_.useCallback)(async(e,t)=>{if(!a)return null;F(!0),R(null);try{let s={};e.trim()&&(s.telegram_chat_id=e.trim()),t.trim()&&(s.telegram_bot_token=t.trim());let r=await (0,er.authPostJson)(`/api/aggregators/${a}/paper/start`,s);if(!r.ok){let e=r.message||r.error||"start_failed";return R(e),null}return await O(),r.data||null}catch(e){return R(String(e?.message??e)),null}finally{F(!1)}},[a,O]),I=(0,_.useCallback)(async(e,t)=>{if(!a)return{ok:!1,sent:!1,error:"no_active_aggregator"};R(null);try{let s=await (0,er.authPostJson)(`/api/aggregators/${a}/paper/telegram-test`,{telegram_chat_id:e,telegram_bot_token:t});return{ok:!!s.ok,sent:!!s.sent,error:s.error}}catch(e){return{ok:!1,sent:!1,error:String(e?.message??e)}}},[a]),D=(0,_.useCallback)(async e=>{if(!a||!e)return!1;F(!0),R(null);try{let t=await (0,er.authPostJson)(`/api/aggregators/${a}/paper/stop`,{session_id:e});if(!t.ok)return R(t.error||"stop_failed"),!1;return await O(),!0}catch(e){return R(String(e?.message??e)),!1}finally{F(!1)}},[a,O]);return(0,_.useEffect)(()=>{if(!a)return void A(null);let e=!0;O().catch(()=>{});let t=window.setInterval(()=>{if(!e)return;let t=E?.sessions?.some(e=>e.session?.status==="running");(null===E||t)&&O().catch(()=>{})},1e4);return()=>{e=!1,window.clearInterval(t)}},[a,O,E?.sessions?.length]),{aggregators:e,activeId:a,activeDraft:r,loading:l,error:o,savingDraft:d,runningBacktest:h,backtestError:m,refresh:g,openAggregator:f,closeAggregator:b,createAggregator:v,updateDraft:y,saveDraft:j,deleteAggregator:w,addStrategy:N,removeStrategy:k,reorderStrategy:S,setConcurrency:$,setParamOverride:C,runBacktest:M,paperStatus:E,paperLoading:T,paperError:P,refreshPaperStatus:O,startPaper:L,stopPaper:D,testTelegram:I}}();return e.activeDraft?(0,b.jsx)(sF,{agg:e,draft:e.activeDraft}):(0,b.jsx)(sE,{agg:e})}function sE({agg:e}
8){let[t,a]=(0,_.useState)(!1),[s,r]=(0,_.useState)(""),[n,l]=(0,_.useState)(!1),[i,o]=(0,_.useState)(null),[c,d]=(0,_.useState)("updated"),[u,h]=(0,_.useState)("desc");async function p(){let t=s.trim();if(t){l(!0),o(null);try{let s=await e.createAggregator({name:t});r(""),a(!1),await e.openAggregator(s.id)}catch(e){o(String(e?.message??e))}finally{l(!1)}}}let m=(0,_.useMemo)(()=>{let t=[...e.aggregators],a="asc"===u?1:-1,s=e=>{switch(c){case"name":return e.name.toLowerCase();case"strategies":return(e.strategies||[]).length;case"winrate":return sS(e.last_backtest)??-1/0;case"pnl":return s$(e.last_backtest)??-1/0;case"maxdd":return sC(e.last_backtest)??1/0;case"last_backtest":return e.last_backtest_at?new Date(e.last_backtest_at).getTime():0;case"updated":return e.updated_at?new Date(e.updated_at).getTime():0}};return t.sort((e,t)=>{let r=s(e),n=s(t);return r<n?-1*a:r>n?+a:0}),t},[e.aggregators,c,u]);function x(e){c===e?h("asc"===u?"desc":"asc"):(d(e),h("name"===e?"asc":"desc"))}function g(e){return c!==e?"":"asc"===u?" ▲":" ▼"}return(0,b.jsxs)("div",{className:"agg-shell",style:{padding:"var(--space-4)",height:"100%",overflowY:"auto"},children:[(0,b.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"var(--space-3)"},children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("h2",{style:{margin:0},children:"Strategy Aggregator"}),(0,b.jsx)("div",{style:{fontSize:"var(--fs-xs)",color:"var(--text-secondary)"},children:"Compose multiple saved presets into one portfolio and backtest them together."})]}),(0,b.jsx)("button",{className:"btn btn-primary",onClick:()=>a(!0),children:"+ New aggregator"})]}),t&&(0,b.jsxs)("div",{className:"card",style:{padding:"var(--space-3)",marginBottom:"var(--space-3)"},children:[(0,b.jsxs)("div",{style:{display:"flex",gap:"var(--space-2)",alignItems:"center"},children:[(0,b.jsx)("input",{type:"text",autoFocus:!0,placeholder:"Aggregator name",value:s,onChange:e=>r(e.target.value),onKeyDown:e=>{"Enter"===e.key&&p()},style:{flex:1}}),(0,b.jsx)("button",{className:"btn btn-primary",disabled:n||!s.trim(),onClick:p,children:n?"Creating…":"Create"}),(0,b.jsx)("button",{className:"btn",onClick:()=>{a(!1),r(""),o(null)},children:"Cancel"})]}),i&&(0,b.jsx)("div",{style:{marginTop:"var(--space-2)",color:"var(--danger, #fca5a5)",fontSize:"var(--fs-xs)"},children:i})]}),e.error&&(0,b.jsxs)("div",{className:"card",style:{padding:"var(--space-3)",marginBottom:"var(--space-3)",borderColor:"var(--danger, #ef4444)"},children:[(0,b.jsx)("strong",{style:{color:"var(--danger, #fca5a5)"},children:"Error:"})," ",e.error]}),e.loading&&0===e.aggregators.length?(0,b.jsx)("div",{className:"card",style:{padding:0,overflow:"hidden"},children:(0,b.jsxs)("table",{className:"agg-list-table",children:[(0,b.jsx)("thead",{children:(0,b.jsxs)("tr",{children:[(0,b.jsx)("th",{children:"Name"}),(0,b.jsx)("th",{className:"num",children:"Strategies"}),(0,b.jsx)("th",{className:"num",children:"Winrate"}),(0,b.jsx)("th",{className:"num",children:"P&L"}),(0,b.jsx)("th",{className:"num",children:"Max DD"}),(0,b.jsx)("th",{children:"Last backtest"}),(0,b.jsx)("th",{children:"Updated"}),(0,b.jsx)("th",{className:"row-action-col"})]})}),(0,b.jsx)("tbody",{children:Array.from({length:4}).map((e,t)=>(0,b.jsx)(sy,{cols:8,height:16},t))})]})}):0===e.aggregators.length?(0,b.jsxs)("div",{className:"empty-state",children:[(0,b.jsx)("div",{children:"No aggregators yet."}),(0,b.jsx)("div",{style:{fontSize:"var(--fs-xs)",color:"var(--text-secondary)"},children:'Click "+ New aggregator" above to build your first portfolio.'})]}):(0,b.jsx)("div",{className:"card",style:{padding:0,overflow:"hidden"},children:(0,b.jsxs)("table",{className:"agg-list-table",children:[(0,b.jsx)("thead",{children:(0,b.jsxs)("tr",{children:[(0,b.jsxs)("th",{onClick:()=>x("name"),className:"sortable",children:["Name",g("name")]}),(0,b.jsxs)("th",{onClick:()=>x("strategies"),className:"sortable num",children:["Strategies",g("strategies")]}),(0,b.jsxs)("th",{onClick:()=>x("winrate"),className:"sortable num",children:["Winrate",g("winrate")]}),(0,b.jsxs)("th",{onClick:()=>x("pnl"),className:"sortable num",children:["P&L",g("pnl")]}),(0,b.jsxs)("th",{onClick:()=>x("maxdd"),className:"sortable num",children:["Max DD",g("maxdd")]}),(0,b.jsxs)("th",{onClick:()=>x("last_backtest"),className:"sortable",children:["Last backtest",g("last_backtest")]}),(0,b.jsxs)("th",{onClick:()=>x("updated"),className:"sortable",children:["Updated",g("updated")]}),(0,b.jsx)("th",{className:"row-action-col"})]})}),(0,b.jsx)("tbody",{children:m.map(t=>(0,b.jsx)(sA,{item:t,onOpen:()=>e.openAggregator(t.id),onDelete:()=>e.deleteAggregator(t.id)},t.id))})]})})]})}function sA({item:e,onOpen:t,onDelete:a}){let s=sS(e.last_backtest),r=s$(e.last_backtest),n=sC(e.last_backtest),l=(e.strategies||[]).length;async function i(t){if(t.stopPropagation(),confirm(`Delete aggregator "${e.name}"?`))try{await a()}catch(e){alert(String(e?.message??e))}}let o="number"==typeof s?s>=50?"good":s<40?"bad":"":"",c="number"==typeof r?r>0?"good":r<0?"bad":"":"";return(0,b.jsxs)("tr",{onClick:t,className:"agg-list-row",children:[(0,b.jsx)("td",{children:(0,b.jsx)("span",{style:{fontWeight:600},children:e.name})}),(0,b.jsx)("td",{className:"num",children:l}),(0,b.jsx)("td",{className:`num tone-${o}`,children:sN(s)}),(0,b.jsx)("td",{className:`num tone-${c}`,children:sk(r)}),(0,b.jsx)("td",{className:"num",children:sk(n)}),(0,b.jsx)("td",{className:"muted",children:e.last_backtest_at?sw(e.last_backtest_at):"never"}),(0,b.jsx)("td",{className:"muted",children:sw(e.updated_at)}),(0,b.jsx)("td",{className:"row-action-col",children:(0,b.jsx)("button",{className:"btn btn-xs",onClick:i,title:"Delete aggregator",children:"×"})})]})}function sT({label:e,value:t,positive:a,negative:s}){return(0,b.jsxs)("div",{children:[(0,b.jsx)("div",{style:{fontSize:"var(--fs-xs)",color:"var(--fg-muted)"},children:e}),(0,b.jsx)("div",{style:{fontWeight:600,color:a?"var(--success)":s?"var(--danger)":"var(--fg)"},children:t})]})}function sF({agg:e,draft:t}){let a,s,r,n,l,[i,o]=(0,_.useState)(!1),[c,d]=(0,_.useState)(null),[u,h]=(0,_.useState)({});(0,_.useEffect)(()=>{let e=!0;return(0,er.authGetJson)("/api/strategy_presets").then(t=>{if(!e||!t?.ok||!Array.isArray(t.data))return;let a={};for(let e of t.data)a[`${e.pattern_key}::${e.name}`]={asset:e.asset,tf:e.tf,pattern_name:e.pattern_name,params:e?.params||{},last_backtest:e.last_backtest??null,last_backtest_at:e.last_backtest_at??null};h(a)}).catch(()=>{}),()=>{e=!1}},[]);let p=t.strategies||[],m=(0,_.useMemo)(()=>{let e=new Set(p.map(e=>`${e.pattern_key}::${e.preset_name??""}`));return t=>e.has(`${t.pattern_key}::${t.name}`)},[p]),x=t.last_backtest;return(0,b.jsxs)("div",{className:"agg-shell",style:{padding:"var(--space-4)",display:"flex",flexDirection:"column",gap:"var(--space-3)",height:"100%",overflowY:"auto"},children:[(0,b.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"var(--space-2)"},children:[(0,b.jsx)("button",{className:"btn",onClick:e.closeAggregator,children:"← Back"}),(0,b.jsx)("input",{type:"text",value:t.name,onChange:t=>e.updateDraft({name:t.target.value}),style:{flex:1,fontWeight:600}}),(0,b.jsx)("button",{className:"btn",onClick:e.saveDraft,disabled:e.savingDraft,children:(0,b.jsx)(aN,{busy:e.savingDraft,label:"Save",busyLabel:"Saving…"})}),(0,b.jsx)("button",{className:"btn btn-primary",onClick:e.runBacktest,disabled:e.runningBacktest||0===p.length,children:(0,b.jsx)(aN,{busy:e.runningBacktest,label:"Run backtest",busyLabel:"Running…"})})]}),(0,b.jsxs)("div",{className:"card",style:{padding:"var(--space-3)",display:"flex",flexDirection:"column",gap:"var(--space-3)"},children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("div",{style:{fontSize:"var(--fs-xs)",color:"var(--text-secondary)",marginBottom:4},children:"Portfolio capital (USD)"}),(0,b.jsx)("input",{type:"number",step:"any",min:0,placeholder:"e.g. 2000 — falls back to first strategy's preset capital if blank",value:t.capital_usd??"",onChange:t=>{let a=t.target.value.trim();if(""===a)return void e.updateDraft({capital_usd:null});let s=Number(a);Number.isFinite(s)&&s>=0&&e.updateDraft({capital_usd:s})},style:{width:280,fontFamily:"var(--font-mono)"}}),(0,b.jsx)("div",{style:{fontSize:"var(--fs-xs)",color:"var(--text-secondary)",marginTop:4},children:"One shared equity pool for all strategies in this aggregator. Per-strategy sizing modal controls how each strategy slices its bet from this pool (Base USD / Base % / Cap / Fee)."})]}),(0,b.jsxs)("div",{children:[(0,b.jsx)("div",{style:{fontSize:"var(--fs-xs)",color:"var(--text-secondary)",marginBottom:4},children:"Data window override"}),(r=(s=null!=(a=t.selected_windows??null)&&a.length>0)?a:["all"],(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:sj.map(t=>{let n="all"===t?!s:r.includes(t);return(0,b.jsx)("button",{type:"button",onClick:()=>(t=>{let r=s?a:[];if("all"===t)return void e.updateDraft({selected_windows:null});let n=r.filter(e=>
8"all"!==e&&e!==t),l=r.includes(t)?n:[...n,t];e.updateDraft({selected_windows:l.length?l:null})})(t),style:{padding:"2px 8px",borderRadius:4,fontSize:"var(--fs-xs)",border:"1px solid "+(n?"var(--accent)":"var(--border)"),background:n?"var(--accent-soft, rgba(99,102,241,0.15))":"transparent",color:n?"var(--accent)":"var(--fg)",cursor:"pointer",fontFamily:"var(--font-mono)"},children:t},t)})}),(0,b.jsx)("div",{style:{fontSize:"var(--fs-xs)",color:"var(--text-secondary)",marginTop:4},children:s?(0,b.jsxs)(b.Fragment,{children:["Forcing every strategy in this aggregator to backtest against ",(0,b.jsx)("code",{children:a.join(", ")})," — overrides each preset's saved windows."]}):(0,b.jsx)(b.Fragment,{children:'No override (default). Each strategy uses whatever windows its preset has saved — pick year tokens or "polymarket_4m" to override.'})})]}))]}),(0,b.jsx)("textarea",{placeholder:"Notes (optional)",value:t.notes||"",onChange:t=>e.updateDraft({notes:t.target.value}),rows:2,style:{width:"100%",resize:"vertical"}})]}),(0,b.jsxs)("div",{className:"card",style:{padding:"var(--space-3)"},children:[(0,b.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"var(--space-2)"},children:[(0,b.jsxs)("div",{style:{fontWeight:600},children:["Strategies (",p.length,")"]}),(0,b.jsx)("button",{className:"btn btn-primary btn-sm",onClick:()=>o(!0),children:"+ Add strategy"})]}),0===p.length?(0,b.jsxs)("div",{className:"empty-state",style:{padding:"var(--space-4)"},children:[(0,b.jsx)("div",{children:"No strategies in this aggregator yet."}),(0,b.jsx)("div",{style:{fontSize:"var(--fs-xs)",color:"var(--fg-muted)"},children:'Click "+ Add strategy" to pull in a saved preset.'})]}):(0,b.jsxs)("table",{className:"agg-strategies-table",style:{width:"100%",borderCollapse:"collapse"},children:[(0,b.jsx)("thead",{children:(0,b.jsxs)("tr",{style:{textAlign:"left",fontSize:"var(--fs-xs)",color:"var(--fg-muted)"},children:[(0,b.jsx)("th",{style:{width:64},children:"Order"}),(0,b.jsx)("th",{children:"Pattern · Preset"}),(0,b.jsx)("th",{style:{width:110},children:"Asset · TF"}),(0,b.jsx)("th",{style:{width:80,textAlign:"right"},children:"Winrate"}),(0,b.jsx)("th",{style:{width:90,textAlign:"right"},children:"P&L"}),(0,b.jsx)("th",{style:{width:70,textAlign:"right"},children:"Trades"}),(0,b.jsx)("th",{style:{width:80,textAlign:"right"},children:"Max DD"}),(0,b.jsx)("th",{style:{width:170},children:"Sizing override"}),(0,b.jsx)("th",{style:{width:140},children:"Concurrency"}),(0,b.jsx)("th",{style:{width:60}})]})}),(0,b.jsx)("tbody",{children:p.map((t,a)=>{let s,r=u[`${t.pattern_key}::${t.preset_name??""}`],n=sR.map(e=>e.key).filter(e=>t.params_override?.[e]!==void 0&&t.params_override?.[e]!==null),l=r?.last_backtest,i=sS(l),o=s$(l),c=(s=l?.summary)?"number"==typeof s.campaigns?s.campaigns:"number"==typeof s.bets?s.bets:"number"==typeof s.total_trades?s.total_trades:null:null,h=sC(l),m=null==i?"var(--fg-muted)":i>=60?"var(--success, #22c55e)":i>=50?"var(--fg)":"var(--danger)";return(0,b.jsxs)("tr",{style:{borderTop:"1px solid var(--border)"},children:[(0,b.jsx)("td",{style:{padding:"var(--space-2) 0"},children:(0,b.jsxs)("div",{style:{display:"flex",gap:2},children:[(0,b.jsx)("button",{className:"btn btn-xs",disabled:0===a,onClick:()=>e.reorderStrategy(a,-1),children:"↑"}),(0,b.jsx)("button",{className:"btn btn-xs",disabled:a===p.length-1,onClick:()=>e.reorderStrategy(a,1),children:"↓"})]})}),(0,b.jsxs)("td",{children:[(0,b.jsx)("div",{style:{fontWeight:600},children:r?.pattern_name||t.pattern_key}),(0,b.jsxs)("div",{style:{fontSize:"var(--fs-xs)",color:"var(--fg-muted)"},children:[t.preset_name?`preset: ${t.preset_name}`:"(active strategy)",r?.last_backtest_at?(0,b.jsxs)(b.Fragment,{children:[" · backtested ",function(e){if(!e)return"never";let t=Math.max(0,(Date.now()-new Date(e).getTime())/1e3);return t<60?`${Math.floor(t)}s ago`:t<3600?`${Math.floor(t/60)}m ago`:t<86400?`${Math.floor(t/3600)}h ago`:`${Math.floor(t/86400)}d ago`}(r.last_backtest_at)]}):null]})]}),(0,b.jsx)("td",{style:{fontSize:"var(--fs-xs)",color:"var(--fg-muted)"},children:r?`${r.asset} \xb7 ${r.tf}`:"—"}),(0,b.jsx)("td",{style:{textAlign:"right",fontFamily:"var(--font-mono)",color:m},children:null==i?"—":`${i.toFixed(1)}%`}),(0,b.jsx)("td",{style:{textAlign:"right",fontFamily:"var(--font-mono)",color:null==o?"var(--fg-muted)":o>0?"var(--success, #22c55e)":o<0?"var(--danger)":"var(--fg)"},children:null==o?"—":sk(o)}),(0,b.jsx)("td",{style:{textAlign:"right",fontFamily:"var(--font-mono)",color:"var(--fg-muted)"},children:null==c?"—":c}),(0,b.jsx)("td",{style:{textAlign:"right",fontFamily:"var(--font-mono)",color:null==h?"var(--fg-muted)":"var(--danger)"}
8,children:null==h?"—":sk(h)}),(0,b.jsx)("td",{children:(0,b.jsx)("button",{className:"btn btn-xs",onClick:()=>d(a),title:"Override the preset's position-sizing params for this strategy in this aggregator",children:n.length>0?`${n.length} override${1===n.length?"":"s"}…`:"Edit sizing…"})}),(0,b.jsx)("td",{children:(0,b.jsx)(sP,{value:t.concurrency,onChange:t=>e.setConcurrency(a,t)})}),(0,b.jsx)("td",{children:(0,b.jsx)("button",{className:"btn btn-xs",onClick:()=>e.removeStrategy(a),title:"Remove",children:"×"})})]},`${t.pattern_key}-${t.preset_name}-${a}`)})})]})]}),e.error&&(0,b.jsxs)("div",{className:"card",style:{padding:"var(--space-3)",borderColor:"var(--danger)"},children:[(0,b.jsx)("strong",{style:{color:"var(--danger)"},children:"Error:"})," ",e.error]}),e.backtestError&&(0,b.jsxs)("div",{className:"card",style:{padding:"var(--space-3)",borderColor:"var(--danger)"},children:[(0,b.jsx)("strong",{style:{color:"var(--danger)"},children:"Backtest failed:"})," ",e.backtestError]}),x&&!1!==x.ok&&(0,b.jsx)(sI,{result:x,aggregatorId:t.id}),(0,b.jsx)(sD,{agg:e}),null!=c&&p[c]&&(n=p[c],l=u[`${n.pattern_key}::${n.preset_name??""}`],(0,b.jsx)(sO,{strategyLabel:l?.pattern_name||n.pattern_key,presetName:n.preset_name||"(active strategy)",presetParams:l?.params||{},override:n.params_override||{},onChange:(t,a)=>e.setParamOverride(c,t,a),onClose:()=>d(null)})),i&&(0,b.jsx)(sL,{onClose:()=>o(!1),onSelect:t=>{let a;return a={pattern_key:t.pattern_key,preset_name:t.name,params_override:null,priority:p.length,concurrency:"exclusive"},void e.addStrategy(a)},alreadyAdded:m})]})}function sP({value:e,onChange:t}){return(0,b.jsxs)("div",{style:{display:"inline-flex",borderRadius:6,overflow:"hidden",border:"1px solid var(--border)"},children:[(0,b.jsx)("button",{className:"exclusive"===e?"btn btn-xs btn-primary":"btn btn-xs",onClick:()=>t("exclusive"),style:{borderRadius:0,borderRight:"1px solid var(--border)"},children:"Exclusive"}),(0,b.jsx)("button",{className:"parallel"===e?"btn btn-xs btn-primary":"btn btn-xs",onClick:()=>t("parallel"),style:{borderRadius:0},children:"Parallel"})]})}let sR=[{key:"base_mode",label:"Mode",type:"select",options:[{value:"fixed",label:"Fixed USD"},{value:"percent",label:"% of equity"}]},{key:"base_usd",label:"Base USD",type:"number",step:1,min:0,disabledWhen:(e,t)=>"fixed"!==(e.base_mode??t.base_mode)},{key:"base_pct_percent",label:"Base %",type:"number",step:.1,min:0,disabledWhen:(e,t)=>"percent"!==(e.base_mode??t.base_mode)},{key:"base_cap_usd",label:"Cap (USD; 0=off)",type:"number",step:1,min:0},{key:"fee_bps_per_side",label:"Fee bps / side",type:"number",step:.5,min:0}];function sO({strategyLabel:e,presetName:t,presetParams:a,override:s,onChange:r,onClose:n}){let l=sR.filter(e=>void 0!==s[e.key]&&null!==s[e.key]).length;return(0,b.jsx)("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.7)",backdropFilter:"blur(2px)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},onClick:n,children:(0,b.jsxs)("div",{style:{width:560,maxHeight:"90vh",overflow:"auto",padding:"var(--space-3)",background:"var(--bg-panel)",border:"1px solid var(--border-default)",borderRadius:"var(--radius-md)",boxShadow:"0 16px 48px rgba(0,0,0,0.5)"},onClick:e=>e.stopPropagation(),children:[(0,b.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"var(--space-2)"},children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("div",{style:{fontWeight:600},children:"Sizing override"}),(0,b.jsxs)("div",{style:{fontSize:"var(--fs-xs)",color:"var(--text-secondary)"},children:[e," · preset: ",t]})]}),(0,b.jsx)("button",{className:"btn btn-xs",onClick:n,children:"Close"})]}),(0,b.jsxs)("div",{style:{fontSize:"var(--fs-xs)",color:"var(--text-secondary)",marginBottom:"var(--space-2)"},children:["Same fields as the strategy backtest's Sizing group. Blank field = use the preset's value (shown as placeholder). Filled = override for this aggregator only.",l>0&&(0,b.jsxs)("button",{className:"btn btn-xs",onClick:()=>{for(let e of sR)r(e.key,null)},style:{marginLeft:"var(--space-2)"},title:"Clear all overrides — fall back to the preset's values for every field",children:["Clear all (",l,")"]})]}),(0,b.jsx)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"var(--space-3)"},children:sR.map(e=>
8{let t="number"===e.type&&!!e.disabledWhen&&e.disabledWhen(s,a),n=s[e.key],l=a[e.key],i=null==n||""===n?"":String(n);return(0,b.jsxs)("div",{children:[(0,b.jsxs)("div",{style:{fontSize:"var(--fs-xs)",color:"var(--text-secondary)",marginBottom:4},children:[e.label,null!=n&&(0,b.jsx)("span",{style:{marginLeft:6,color:"var(--accent, #60a5fa)"},children:"(override)"})]}),"select"===e.type?(0,b.jsx)("select",{value:n??l??"",onChange:t=>{let a=t.target.value;a===l||""===a?r(e.key,null):r(e.key,a)},disabled:t,style:{width:"100%"},children:e.options.map(e=>(0,b.jsx)("option",{value:e.value,children:e.label},e.value))}):(0,b.jsx)("input",{type:"number",step:e.step,min:e.min,disabled:t,value:i,placeholder:null!=l?String(l):"(no default)",onChange:t=>{let a=t.target.value.trim();if(""===a)return void r(e.key,null);let s=Number(a);if(Number.isFinite(s)){if(null!=l&&s===Number(l))return void r(e.key,null);r(e.key,s)}},style:{width:"100%",fontFamily:"var(--font-mono)"}})]},e.key)})}),(0,b.jsx)("div",{style:{marginTop:"var(--space-3)",fontSize:"var(--fs-xs)",color:"var(--text-secondary)"},children:"Changes save when you click Save on the aggregator. Run backtest after saving to see new numbers."})]})})}function sL({onClose:e,onSelect:t,alreadyAdded:a}){return(0,b.jsx)("div",{style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.7)",backdropFilter:"blur(2px)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},onClick:e,children:(0,b.jsxs)("div",{style:{width:"min(1200px, 95vw)",maxHeight:"90vh",display:"flex",flexDirection:"column",padding:"var(--space-3)",background:"var(--bg-panel)",border:"1px solid var(--border-default)",borderRadius:"var(--radius-md)",boxShadow:"0 16px 48px rgba(0, 0, 0, 0.5)"},onClick:e=>e.stopPropagation(),children:[(0,b.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"var(--space-2)"},children:[(0,b.jsx)("div",{style:{fontWeight:600},children:"Add strategy from preset library"}),(0,b.jsx)("button",{className:"btn btn-sm",onClick:e,children:"Close"})]}),(0,b.jsx)("div",{style:{flex:1,overflow:"auto"},children:(0,b.jsx)(s_,{onSelect:t,isAlreadyAdded:a})})]})})}function sI({result:e,aggregatorId:t}){let a,s,r,n,[l,i]=(0,_.useState)([]),[o,c]=(0,_.useState)(0),[d,u]=(0,_.useState)(!1),[h,p]=(0,_.useState)(null),[m,x]=(0,_.useState)(1),[g,f]=(0,_.useState)(1),v=String(e?.summary?.signal_rows_token||e?.signal_rows_token||"").trim(),[y,j]=(0,_.useState)(null),w=(0,_.useRef)(null);(0,_.useEffect)(()=>{if(!y)return;let e=window.requestAnimationFrame(()=>{w.current?.focusTime(y.focusTime,14)});return()=>window.cancelAnimationFrame(e)},[y]),(0,_.useEffect)(()=>{if(!y)return;let e=e=>{"Escape"===e.key&&j(null)};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[y]),(0,_.useEffect)(()=>{x(1)},[v]),(0,_.useEffect)(()=>{if(!v||!t)return;let e=!1;u(!0),p(null);let a=new URLSearchParams({token:v,page:String(m),page_size:String(200),order:"desc"});return(async()=>{try{let s=await (0,er.authGetJson)(`/api/aggregators/${t}/signal-rows?${a.toString()}`);if(e)return;if(!s?.ok||!s?.data)throw Error(s?.error||"load_failed");i(Array.isArray(s.data.rows)?s.data.rows:[]),c(Number(s.data.total||0)),f(Math.max(1,Number(s.data.page_count||1)))}catch(t){e||p(String(t?.message??t))}finally{e||u(!1)}})(),()=>{e=!0}},[v,t,m]);let N=e?.summary||{},k=sS(e),S=s$(e),$=sC(e),C=Array.isArray(e?.equity_curve)?e.equity_curve:[],M=Array.isArray(e?.signal_rows)?e.signal_rows:[],E=M.length>0,A=E?M.slice().reverse():l,T=Number(e?.signal_rows_total??o??A.length)||A.length,[F,P]=(0,_.useState)("all"),R=(0,_.useMemo)(()=>{let t=new Map;for(let a of A.length>0?A:Array.isArray(e?.trades)?e.trades:[]){let e=String(a?.strategy_key||"");e&&(t.has(e)||t.set(e,String(a?.strategy_name||e)))}return Array.from(t.entries()).map(([e,t])=>({key:e,label:t}))},[A,e]),O=(0,_.useMemo)(()=>"all"===F?A:A.filter(e=>String(e?.strategy_key||"")===F),[A,F]),L=!!N?.blown,I=Number.isFinite(Number(N?.blown_ts))?Number(N.blown_ts):null,D=Number.isFinite(Number(N?.peak_equity))?Number(N.peak_equity):null,z=Number.isFinite(Number(N?.peak_ts))?Number(N.peak_ts):null,B=Number.isFinite(Number(N?.initial_equity))?Number(N.initial_equity):null,W=Number.isFinite(Number(N?.end_equity))?Number(N.end_equity):null,U=null!=D&&B&&B>0?D/B:null,H=Number.isFinite(Number(N?.survived_seconds))?Number(N.survived_seconds):null,q=N?.blown_strategy&&"object"==typeof N.blown_strategy?N.blown_strategy:null,V=e=>{if(null==e)return"—";let t=e;t>1e12&&(t=Math.floor(t/1e3));let a=new Date(1e3*t),s=a.getUTCFullYear(),r=String(a.getUTCMonth()+1).padStart(2,"0"),n=String(a.getUTCDate()).padStart(2,"0");return`${s}-${r}-${n}`};return(0,b.jsxs)("div",{className:"card",style:{padding:"var(--space-3)"},children:[(0,b.jsx)("div",{style:{fontWeight:600,marginBottom:"var(--space-2)"},children:"Backtest result"}),L?(0,b.jsxs)("div",{style:{border:"1px solid var(--danger)",background:"rgba(244, 63, 94, 0.08)",borderRadius:6,padding:"var(--space-3)",marginBottom:"var(--space-3)",display:"flex",flexDirection:"column",gap:6},children:[(0,b.jsxs)("div",{style:{color:"var(--danger)",fontWeight:700,fontSize:"var(--fs-md)"},children:["🔴 BLOWN OUT",I?` on ${V(I)}`:""]}),(0,b.jsxs)("div",{style:{fontSize:"var(--fs-xs)",color:"var(--fg)"},children:["Peak: ",(0,b.jsx)("strong",{children:null!=D?sk(D):"—"}),null!=U?(0,b.jsxs)(b.Fragment,{children:[" (",U.toFixed(1),"× initial)"]}):null,z?(0,b.jsxs)(b.Fragment,{children:[" on ",V(z)]}):null,null!=H?(0,b.jsxs)(b.Fragment,{children:[" · Survived ",(e=>{if(null==e||!Number.isFinite(e)||e<=0)return"—";let t=Math.floor(e/86400),a=Math.floor(t/365),s=Math.floor(t%365/30),r=t%365%30,n=[];return a&&n.push(`${a}y`),s&&n.push(`${s}m`),r&&!a&&n.push(`${r}d`),n.length?n.join(" "):`${t}d`})(H)]}):null]}),q?(0,b.jsxs)("div",{style:{fontSize:"var(--fs-xs)",color:"var(--fg)"},children:["Killer: ",(0,b.jsx)("strong",{children:q.strategy_name}),q.strategy_asset?(0,b.jsxs)(b.Fragment,{children:[" · ",q.strategy_asset," ",q.strategy_tf]}):null,null!=q.ladder_step?(0,b.jsxs)(b.Fragment,{children:[", ladder step ",(0,b.jsx)("strong",{children:q.ladder_step})]}):null,Number.isFinite(Number(q.loss_usd))&&0!==Number(q.loss_usd)?(0,b.jsxs)(b.Fragment,{children:[", lost ",(0,b.jsx)("strong",{style:{color:"var(--danger)"},children:sk(Number(q.loss_usd))})," on the final campaign"]}):q.reason?(0,b.jsxs)(b.Fragment,{children:[" (",String(q.reason),")"]}):null]}):null]}):(0,b.jsxs)("div",{style:{border:"1px solid var(--border)",background:"rgba(34, 197, 94, 0.06)",borderRadius:6,padding:"6px 10px",marginBottom:"var(--space-3)",fontSize:"var(--fs-xs)",color:"var(--fg)"},children:[(0,b.jsx)("strong",{style:{color:"var(--success, #22c55e)"},children:"✓ Survived"}),null!=W?(0,b.jsxs)(b.Fragment,{children:[" · End equity ",(0,b.jsx)("strong",{children:sk(W)})]}):null,null!=D?(0,b.jsxs)(b.Fragment,{children:[" · Peak ",(0,b.jsx)("strong",{children:sk(D)}),null!=U?` (${U.toFixed(1)}\xd7)`:""]}):null]}),(0,b.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(5, 1fr)",gap:"var(--space-2)",marginBottom:"var(--space-3)"},children:[(0,b.jsx)(sT,{label:"Campaign winrate",value:sN(k),positive:"number"==typeof k&&k>=50,negative:"number"==typeof k&&k<40}),(0,b.jsx)(sT,{label:"P&L",value:sk(S),positive:"number"==typeof S&&S>0,negative:"number"==typeof S&&S<0}),(0,b.jsx)(sT,{label:"Max DD",value:sk($)}),(0,b.jsx)(sT,{label:"Campaigns",value:String(N.campaigns??"—")}),(0,b.jsx)(sT,{label:"Detections",value:String(N.detections??"—")})]}),C.length>1&&(0,b.jsx)("div",{style:{height:280,marginBottom:"var(--space-2)"},children:(0,b.jsx)(eE,{equityCurve:C,height:280,compact:!0})}),(A.length>0||d||h)&&(0,b.jsxs)("div",{style:{marginTop:"var(--space-3)"},children:[(0,b.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:6,gap:8,flexWrap:"wrap"},children:[(0,b.jsxs)("div",{style:{fontSize:"var(--fs-xs)",color:"var(--fg-muted)"},children:["All Signals — newest first · ",T," total","all"!==F?` \xb7 ${O.length} filtered`:"",d?(0,b.jsx)("span",{style:{marginLeft:6,opacity:.7},children:"· loading…"}):null,h?(0,b.jsxs)("span",{style:{marginLeft:6,color:"var(--danger)"},children:["· ",h]}):null]}),(0,b.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[!E&&g>1&&(0,b.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:4,fontSize:"var(--fs-xs)"},children:[(0,b.jsx)("button",{className:"btn btn-xs",disabled:m<=1||d,onClick:()=>x(e=>Math.max(1,e-1)),title:"Newer trades",children:"← Newer"}),(0,b.jsxs)("span",{style:{color:"var(--fg-muted)",minWidth:90,textAlign:"center"},children:["page ",m," / ",g]}),(0,b.jsx)("button",{className:"btn btn-xs",disabled:m>=g||d,onClick:()=>x(e=>Math.min(g,e+1)),title:"Older trades",children:"Older →"})]}),R.length>1&&(0,b.jsxs)("select",{value:F,onChange:e=>P(e.target.value),style:{fontSize:"var(--fs-xs)",padding:"2px 6px"},title:"Filter signals by strategy",children:[(0,b.jsx)("option",{value:"all",children:"All strategies"}),R.map(e=>(0,b.jsx)("option",{value:e.key,children:e.label},e.key))]})]})]}),(0,b.jsxs)("div",{style:{maxHeight:520,overflowY:"auto",border:"1px solid var(--border)",borderRadius:4,padding:"var(--space-2)"},children:[O.map((e,t)=>
8{let a=aK(e),s=String(e?.strategy_name||"").trim(),r=`${e?.strategy_asset||""}${e?.strategy_tf?` ${e.strategy_tf}`:""}`.trim(),n=(e?.context_candles||[]).filter(e=>[e?.open,e?.high,e?.low,e?.close].every(e=>Number.isFinite(Number(e)))),l=n.map(e=>Number(e.low)),i=n.map(e=>Number(e.high)),o=l.length?Math.min(...l):0,c=i.length?Math.max(...i):1;return(0,b.jsxs)("div",{style:{marginBottom:14,paddingBottom:10,borderBottom:"1px solid rgba(160,170,190,0.2)",fontSize:"var(--fs-xs)"},children:[(0,b.jsxs)("p",{style:{margin:"0 0 4px 0"},children:[(0,b.jsx)("strong",{style:{color:"var(--accent, #8fb8ff)"},children:s||a||"—"}),r?(0,b.jsxs)("span",{style:{color:"var(--fg-muted)"},children:[" · ",r]}):null," | ","entry ",aY(e?.entry_ts)," (",e?.entry_side||"-",")"," | ","status: ",e?.status||"-",e?.win_step?` (step ${e?.win_step})`:""]}),(0,b.jsxs)("p",{style:{margin:"0 0 4px 0",color:"var(--fg-muted)"},children:["streak: ",e?.streak_dir||"-"," x",aV(e?.streak_len_effective)," | ","source: ",e?.entry_dir_source||"-"," | ","neutral fallback: ",String(!!e?.used_neutral_fallback)]}),(0,b.jsxs)("p",{style:{margin:"0 0 4px 0",color:"var(--fg-muted)"},children:["confidence: ",aV(100*Number(e?.confidence??1)),"%"," | ","entry size: ",e?.entry_size_usd==null?"-":`$${aV(Number(e?.entry_size_usd))}`]}),e?.feature_values&&(0,b.jsxs)("p",{style:{margin:"0 0 4px 0",color:"var(--fg-muted)"},children:["feature: ret1 ",aJ(e.feature_values.ret1_pct)," | retN ",aJ(e.feature_values.retn_pct)," | ","atr14 ",aJ(e.feature_values.atr14_pct)," | ema gap ",aJ(e.feature_values.ema20_gap_pct)," | ","vol ",aJ(e.feature_values.vol_ratio5)," | rsi ",aJ(e.feature_values.rsi14)]}),n.length>0?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)("div",{className:"ps-signal-candles",style:{marginTop:4,marginBottom:4},children:n.map((a,s)=>(0,b.jsx)(aX,{c:a,minLow:o,maxHigh:c,onClick:()=>((e,t)=>{let a=(Array.isArray(e?.context_candles)?e.context_candles:[]).map(e=>({idx:Number(e?.idx),open_ts:Number(e?.open_ts),close_ts:Number(e?.close_ts),open:Number(e?.open),high:Number(e?.high),low:Number(e?.low),close:Number(e?.close),role:String(e?.role||"")})).filter(e=>[e.open_ts,e.close_ts,e.open,e.high,e.low,e.close].every(e=>Number.isFinite(e))).sort((e,t)=>{let a=Number.isFinite(e.idx)?e.idx:0,s=Number.isFinite(t.idx)?t.idx:0;return a!==s?a-s:e.open_ts-t.open_ts});if(!a.length)return;let s=a.map(e=>({time:e.open_ts,open:e.open,high:e.high,low:e.low,close:e.close})),r=a.flatMap(e=>"detect"===e.role?[{time:e.open_ts,position:"aboveBar",color:"#f7c86a",shape:"circle",text:"D"}]:"entry"===e.role?[{time:e.open_ts,position:"belowBar",color:"#8fb8ff",shape:"circle",text:"E"}]:[]),n=a.find(e=>"entry"===e.role)||a.find(e=>"detect"===e.role)||a[Math.max(0,Math.floor(a.length/2))],l=Number(e?.entry_ts||0),i=String(e?.entry_side||"-"),o=String(e?.status||"-"),c=String(e?.strategy_name||"").trim(),d=`${e?.strategy_asset||""}${e?.strategy_tf?` ${e.strategy_tf}`:""}`.trim(),u=c?`${c}${d?` (${d})`:""}`:aK(e);j({title:`Signal #${t} \xb7 ${aY(l)} \xb7 ${i}${u?` \xb7 ${u}`:""}`,subtitle:`status ${o}${u?` \xb7 strategy ${u}`:""} \xb7 yellow=detect, blue=entry`,candles:s,markers:r,focusTime:Number(n?.open_ts||s[s.length-1]?.time||0)})})(e,t+1)},`agg-sig-${t}-c-${s}`))}),(0,b.jsx)("p",{style:{margin:"0 0 4px 0",color:"var(--fg-muted)",fontSize:"10px"},children:"Click any candle for zoomed view. Legend: streak = plain, detect = yellow, entry = blue"})]}):(0,b.jsx)("p",{style:{margin:"0 0 4px 0",color:"var(--fg-muted)",fontSize:"10px",fontStyle:"italic"},children:"No candle preview for this signal (detector didn't record a bar index)."}),Array.isArray(e?.ladder_steps)&&e.ladder_steps.length>0&&(0,b.jsx)("div",{style:{marginTop:4},children:e.ladder_steps.map((e,a)=>(0,b.jsxs)("p",{style:{margin:"0 0 2px 0",color:"var(--fg-muted)"},children:["step ",aV(e?.step)," @ ",aY(Number(e?.ts||0))," | ","x",aV(e?.multiplier)," | ","stake: ",e?.stake_usd==null?"-":`$${aV(e?.stake_usd)}`," | ",e?.result||"-",e?.fill_price!=null?` | fill ${aG(e?.fill_price)}`:"",e?.pnl_usd!=null?` | pnl ${aV(e?.pnl_usd)}`:""]},`agg-sig-${t}-l-${a}`))})]},`agg-sig-${t}`)}),0===O.length&&(0,b.jsx)("div",{style:{padding:12,textAlign:"center",color:"var(--fg-muted)"},children:"No signals match this filter."})]})]}),!v&&!d&&0===A.length&&Array.isArray(e?.trades)&&e.trades.length>0&&(s=(a=e.trades).slice().reverse(),r="all"===F?s:s.filter(e=>String(e?.strategy_key||"")===F),n=Number(e?.trades_total??a.length)||a.length,(0,b.jsxs)("div",{style:{marginTop:"var(--space-3)"},children:[(0,b.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:6,gap:8,flexWrap:"wrap"},children:[(0,b.jsxs)("div",{style:{fontSize:"var(--fs-xs)",color:"var(--fg-muted)"},children:["Trades — ",r.length,"all"!==F?" (filtered)":""," of ",n,(0,b.jsx)("span",{style:{marginLeft:6,opacity:.7},children:"(rich signal rows unavailable in cached snapshot — re-run backtest for full context c
8andles)"})]}),R.length>1&&(0,b.jsxs)("select",{value:F,onChange:e=>P(e.target.value),style:{fontSize:"var(--fs-xs)",padding:"2px 6px"},title:"Filter trades by strategy",children:[(0,b.jsx)("option",{value:"all",children:"All strategies"}),R.map(e=>(0,b.jsx)("option",{value:e.key,children:e.label},e.key))]})]}),(0,b.jsx)("div",{style:{maxHeight:520,overflowY:"auto",border:"1px solid var(--border)",borderRadius:4},children:(0,b.jsxs)("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:"var(--fs-xs)"},children:[(0,b.jsx)("thead",{style:{position:"sticky",top:0,background:"var(--bg-panel)",zIndex:1},children:(0,b.jsxs)("tr",{style:{textAlign:"left",color:"var(--fg-muted)"},children:[(0,b.jsx)("th",{style:{padding:"4px 8px"},children:"Strategy"}),(0,b.jsx)("th",{style:{padding:"4px 8px"},children:"Entry"}),(0,b.jsx)("th",{style:{padding:"4px 8px"},children:"Side"}),(0,b.jsx)("th",{style:{padding:"4px 8px",textAlign:"right"},children:"Entry px"}),(0,b.jsx)("th",{style:{padding:"4px 8px",textAlign:"right"},children:"Exit px"}),(0,b.jsx)("th",{style:{padding:"4px 8px",textAlign:"right"},children:"Size"}),(0,b.jsx)("th",{style:{padding:"4px 8px",textAlign:"right"},children:"PnL"}),(0,b.jsx)("th",{style:{padding:"4px 8px"},children:"Outcome"}),(0,b.jsx)("th",{style:{padding:"4px 8px",textAlign:"right"},children:"Step"})]})}),(0,b.jsxs)("tbody",{children:[r.map((e,t)=>{let a=Number(e?.pnl_usd),s=Number.isFinite(a)&&a>0,r=Number.isFinite(a)&&a<0;return(0,b.jsxs)("tr",{style:{borderTop:"1px solid var(--border)"},children:[(0,b.jsxs)("td",{style:{padding:"4px 8px"},title:`${e?.strategy_key} \xb7 ${e?.strategy_asset} ${e?.strategy_tf}`,children:[(0,b.jsx)("span",{style:{fontWeight:500},children:e?.strategy_name||"—"}),(0,b.jsxs)("span",{style:{color:"var(--fg-muted)",marginLeft:4},children:[e?.strategy_asset||"",e?.strategy_tf?` ${e.strategy_tf}`:""]})]}),(0,b.jsx)("td",{style:{padding:"4px 8px",fontFamily:"var(--font-mono)"},children:aY(Number(e?.entry_ts))}),(0,b.jsx)("td",{style:{padding:"4px 8px"},children:e?.side||"—"}),(0,b.jsx)("td",{style:{padding:"4px 8px",textAlign:"right",fontFamily:"var(--font-mono)"},children:Number(e?.entry_price??0).toFixed(4)}),(0,b.jsx)("td",{style:{padding:"4px 8px",textAlign:"right",fontFamily:"var(--font-mono)"},children:Number(e?.exit_price??0).toFixed(4)}),(0,b.jsx)("td",{style:{padding:"4px 8px",textAlign:"right",fontFamily:"var(--font-mono)"},children:sk(Number(e?.size_usd))}),(0,b.jsx)("td",{style:{padding:"4px 8px",textAlign:"right",fontFamily:"var(--font-mono)",color:s?"var(--success)":r?"var(--danger)":"var(--fg)"},children:sk(Number(e?.pnl_usd))}),(0,b.jsx)("td",{style:{padding:"4px 8px"},children:e?.close_reason||"—"}),(0,b.jsx)("td",{style:{padding:"4px 8px",textAlign:"right"},children:Number.isFinite(Number(e?.ladder_step))?Number(e?.ladder_step)+1:"—"})]},t)}),0===r.length&&(0,b.jsx)("tr",{children:(0,b.jsx)("td",{colSpan:9,style:{padding:8,textAlign:"center",color:"var(--fg-muted)"},children:"No trades match filter."})})]})]})})]})),y&&(0,b.jsx)("div",{className:"ps-signal-modal",onClick:()=>j(null),children:(0,b.jsxs)("div",{className:"ps-signal-modal-card",onClick:e=>e.stopPropagation(),children:[(0,b.jsxs)("div",{className:"ps-signal-modal-head",children:[(0,b.jsxs)("div",{className:"ps-signal-modal-meta",children:[(0,b.jsx)("div",{className:"ps-signal-modal-title",children:y.title}),(0,b.jsx)("div",{className:"ps-signal-modal-subtitle",children:y.subtitle})]}),(0,b.jsx)("button",{className:"btn btn-ghost ps-signal-modal-close",type:"button",onClick:()=>j(null),children:"Close"})]}),(0,b.jsx)("div",{className:"ps-signal-modal-chart",children:(0,b.jsx)(aT,{ref:w,candles:y.candles,markers:y.markers,title:"Signal Context Candles",subtitle:"Focused view mirrors detection zoom behavior"})})]})})]})}function sD({agg:e}
8){let[t,a]=(0,_.useState)(()=>{try{return window.localStorage.getItem("openpoly.telegram.chat_id")||""}catch{return""}}),[s,r]=(0,_.useState)(()=>{try{return window.localStorage.getItem("openpoly.telegram.bot_token")||""}catch{return""}}),[n,l]=(0,_.useState)(!1),[i,o]=(0,_.useState)({kind:"idle"}),c=()=>{try{window.localStorage.setItem("openpoly.telegram.chat_id",t),window.localStorage.setItem("openpoly.telegram.bot_token",s)}catch{}},d=e.paperStatus?.sessions??[],u=d.find(e=>e.session?.status==="running"),h=d.slice(0,5),p=async()=>{c(),await e.startPaper(t,s)},m=async t=>{window.confirm("Stop this paper session? Any in-flight campaigns will continue resolving until done.")&&await e.stopPaper(t)},x=async()=>{if(!t.trim()||!s.trim())return void o({kind:"failed",msg:"fill both chat id and bot token first"});c(),o({kind:"sending"});let a=await e.testTelegram(t,s);a.sent?o({kind:"sent",msg:"6 sample messages sent — check your chat to preview the formats"}):o({kind:"failed",msg:a.error||"failed to send"})};return(0,b.jsxs)("div",{className:"card",style:{padding:"var(--space-3)",marginTop:"var(--space-3)"},children:[(0,b.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"var(--space-3)",gap:"var(--space-2)"},children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("div",{style:{fontWeight:600},children:"📄 Paper trade"}),(0,b.jsx)("div",{style:{fontSize:"var(--fs-xs)",color:"var(--fg-muted)",marginTop:2},children:"Run this aggregator against live candle feeds with simulated fills. Worker ticks every 60s; signals + step results push to Telegram if configured."})]}),u?(0,b.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"var(--space-2)"},children:[(0,b.jsx)("span",{style:{padding:"2px 8px",borderRadius:4,background:"rgba(34,197,94,0.15)",color:"var(--success, #22c55e)",fontSize:"var(--fs-xs)",fontWeight:600},children:"● RUNNING"}),(0,b.jsx)("button",{className:"btn",onClick:()=>m(u.session.id),disabled:e.paperLoading,style:{background:"rgba(232,73,87,0.12)",borderColor:"rgba(232,73,87,0.35)"},children:"Stop"})]}):(0,b.jsx)("button",{className:"btn btn-primary",onClick:p,disabled:e.paperLoading,children:(0,b.jsx)(aN,{busy:e.paperLoading,label:"Start paper session",busyLabel:"Starting…"})})]}),e.paperError&&(0,b.jsx)("div",{style:{padding:"var(--space-2) var(--space-3)",background:"rgba(232,73,87,0.08)",border:"1px solid var(--danger)",borderRadius:4,color:"var(--danger)",fontSize:"var(--fs-xs)",marginBottom:"var(--space-3)"},children:e.paperError}),!u&&(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 2fr auto auto",gap:"var(--space-2)",alignItems:"end",marginBottom:6,fontSize:"var(--fs-xs)"},children:[(0,b.jsxs)("label",{style:{color:"var(--fg-muted)"},children:["Telegram chat id",(0,b.jsx)("input",{type:"text",value:t,onChange:e=>{a(e.target.value),o({kind:"idle"})},placeholder:"-100123456789 or 87654321",style:{width:"100%",marginTop:2}})]}),(0,b.jsxs)("label",{style:{color:"var(--fg-muted)"},children:["Telegram bot token",(0,b.jsx)("input",{type:n?"text":"password",value:s,onChange:e=>{r(e.target.value),o({kind:"idle"})},placeholder:"from @BotFather",style:{width:"100%",marginTop:2,fontFamily:"var(--font-mono)"}})]}),(0,b.jsx)("button",{className:"btn",type:"button",onClick:()=>l(e=>!e),style:{fontSize:"var(--fs-xs)"},children:n?"Hide":"Show"}),(0,b.jsx)("button",{className:"btn",type:"button",onClick:x,disabled:"sending"===i.kind||!t.trim()||!s.trim(),title:"Send a test 🧪 ping to verify the bot token + chat id are correct",style:{fontSize:"var(--fs-xs)"},children:"sending"===i.kind?"Sending…":"🧪 Test"})]}),"idle"!==i.kind&&"sending"!==i.kind&&(0,b.jsxs)("div",{style:{fontSize:"var(--fs-xs)",padding:"4px 8px",marginBottom:"var(--space-3)",borderRadius:4,background:"sent"===i.kind?"rgba(34,197,94,0.10)":"rgba(232,73,87,0.10)",color:"sent"===i.kind?"var(--success, #22c55e)":"var(--danger)",border:"sent"===i.kind?"1px solid rgba(34,197,94,0.35)":"1px solid rgba(232,73,87,0.35)"},children:["sent"===i.kind?"✓ ":"✗ ",i.msg]})]}),u&&(0,b.jsx)(sB,{sess:u,aggregatorId:String(e.activeId||"")}),!u&&h.length>0&&(0,b.jsxs)("div",{style:{marginTop:"var(--space-2)"},children:[(0,b.jsx)("div",{style:{fontSize:"var(--fs-xs)",color:"var(--fg-muted)",marginBottom:4},children:"Recent sessions"}),(0,b.jsxs)("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:"var(--fs-xs)"},children:[(0,b.jsx)("thead",{children:(0,b.jsxs)("tr",{style:{textAlign:"left",color:"var(--fg-muted)",borderBottom:"1px solid var(--border)"},children:[(0,b.jsx)("th",{style:{padding:"4px 6px"},children:"Started"}),(0,b.jsx)("th",{style:{padding:"4px 6px"},children:"Status"}),(0,b.jsx)("th",{style:{padding:"4px 6px",textAlign:"right"},children:"Initial"}),(0,b.jsx)("th",{style:{padding:"4px 6px",textAlign:"right"},children:"End"}),(0,b.jsx)("th",{style:{padding:"4px 6px",textAlign:"right"},children:"Peak"}),(0,b.jsx)("th",{style:{padding:"4px 6px",textAlign:"right"},children:"Signals"})]})}),(0,b.jsx)("tbody",{children:h.map((e,t)=>{let a=e.session,s=Number(a?.initial_equity_usd??0),r=Number(a?.current_equity_usd??0),n=Number(a?.peak_equity_usd??0),l=Array.isArray(e.recent_signals)?e.recent_signals.length:0,i=a?.started_at?new Date(a.started_at).toISOString().slice(0,16).replace("T"," "):"—";return(0,b.jsxs)("tr",{style:{borderBottom:"1px solid var(--border)"},children:[(0,b.jsx)("td",{style:{padding:"4px 6px",fontFamily:"var(--font-mono)"},children:i}),(0,b.jsx)("td",{style:{padding:"4px 6px"},children:a?.status||"—"}),(0,b.jsx)("td",{style:{padding:"4px 6px",textAlign:"right",fontFamily:"var(--font-mono)"},children:sk(s)}),(0,b.jsx)("td",{style:{padding:"4px 6px",textAlign:"right",fontFamily:"var(--font-mono)",color:r>s?"var(--success, #22c55e)":r<s?"var(--danger)":"var(--fg)"},children:sk(r)}),(0,b.jsx)("td",{style:{padding:"4px 6px",textAlign:"right",fontFamily:"var(--font-mono)"},children:sk(n)}),(0,b.jsx)("td",{style:{padding:"4px 6px",textAlign:"right"},children:l})]},a?.id||t)})})]})]})]})}function sz({aggregatorId:e,sessionId:t,isRunning:a}){let[s,r]=(0,_.useState)([]),[n,l]=(0,_.useState)(null),i=(0,_.useRef)(0),o=(0,_.useRef)(null),c=(0,_.useRef)(!0),[d,u]=(0,_.useState)(0);return(0,_.useEffect)(()=>
8{if(!t)return;let s=!1,n=async()=>{try{let a=await (0,er.authGetJson)(`/api/aggregators/${e}/paper/logs?session_id=${encodeURIComponent(t)}&since_ms=${i.current}&limit=500`);if(s)return;if(!a?.ok||!a?.data)return void l(a?.error||"log fetch failed");let n=a.data.logs||[];if(0===n.length)return;i.current=Math.max(i.current,...n.map(e=>Number(e.ts_ms||0))),r(e=>{let t=[...e,...n];return t.length>2e3?t.slice(t.length-2e3):t}),l(null),c.current||u(e=>e+n.length)}catch(e){s||l(e?.message||"log fetch failed")}};if(n(),!a)return()=>{s=!0};let o=window.setInterval(n,5e3);return()=>{s=!0,window.clearInterval(o)}},[e,t,a]),(0,_.useEffect)(()=>{if(!c.current)return;let e=o.current;e&&(e.scrollTop=e.scrollHeight)},[s.length]),(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginTop:"var(--space-3)",marginBottom:4,fontSize:"var(--fs-xs)",color:"var(--fg-muted)"},children:[(0,b.jsxs)("span",{children:["Live log (",s.length," entr",1===s.length?"y":"ies",")",a?(0,b.jsx)("span",{style:{marginLeft:6,color:"#15b097"},children:"● polling"}):(0,b.jsx)("span",{style:{marginLeft:6},children:"● stopped"})]}),n?(0,b.jsx)("span",{style:{color:"var(--danger)"},children:n}):null]}),(0,b.jsxs)("div",{style:{position:"relative"},children:[(0,b.jsx)("div",{ref:o,onScroll:()=>{let e=o.current;!e||(c.current=e.scrollHeight-e.clientHeight-e.scrollTop<30,c.current&&u(0))},style:{maxHeight:320,overflowY:"auto",border:"1px solid var(--border)",borderRadius:4,background:"var(--bg-base)",padding:"6px 8px",fontFamily:"var(--font-mono)",fontSize:11,lineHeight:1.5},children:0===s.length?(0,b.jsx)("div",{style:{color:"var(--fg-muted)",padding:"8px 0",textAlign:"center"},children:a?"Waiting for the next tick (worker runs every 60s)…":"No log entries yet."}):s.map(e=>{var t;let a=new Date(e.ts_ms).toLocaleTimeString();return(0,b.jsxs)("div",{style:{display:"flex",gap:8,color:"error"===(t=e.level)?"var(--danger)":"warn"===t?"var(--color-neutral, #f0b232)":"var(--fg)"},children:[(0,b.jsx)("span",{style:{color:"var(--fg-muted)",flexShrink:0},children:a}),(0,b.jsx)("span",{style:{wordBreak:"break-word"},children:e.message})]},e.id)})}),d>0?(0,b.jsxs)("button",{type:"button",onClick:()=>{let e=o.current;e&&(e.scrollTop=e.scrollHeight,c.current=!0,u(0))},style:{position:"absolute",bottom:8,right:12,padding:"2px 8px",borderRadius:4,border:"1px solid var(--border)",background:"var(--bg-panel)",color:"var(--fg)",fontSize:10,cursor:"pointer"},children:["↓ ",d," new"]}):null]})]})}function sB({sess:e,aggregatorId:t}){let a=e.session||{},s=Number(a.initial_equity_usd??0),r=Number(a.current_equity_usd??0),n=Number(a.peak_equity_usd??0),l=r-s,i=s>0?l/s*100:0,o=a.last_tick_at?new Date(a.last_tick_at).toLocaleString():"never",c=a.started_at?new Date(a.started_at).toLocaleString():"—",d=(e.recent_signals||[]).slice(0,15),u=e.pending_steps||[],h=String(a.id||""),p="running"===String(a.status||"");return(0,b.jsxs)("div",{children:[(0,b.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(5, 1fr)",gap:"var(--space-2)",marginBottom:"var(--space-3)"},children:[(0,b.jsx)(sT,{label:"Equity now",value:sk(r),positive:r>s,negative:r<s}),(0,b.jsx)(sT,{label:"Net PnL",value:sk(l),positive:l>0,negative:l<0}),(0,b.jsx)(sT,{label:"PnL %",value:`${i>=0?"+":""}${i.toFixed(2)}%`,positive:i>0,negative:i<0}),(0,b.jsx)(sT,{label:"Peak",value:sk(n)}),(0,b.jsx)(sT,{label:"Initial",value:sk(s)})]}),(0,b.jsxs)("div",{style:{fontSize:"var(--fs-xs)",color:"var(--fg-muted)",marginBottom:"var(--space-3)"},children:["started ",c," · last tick ",o," · id ",(0,b.jsx)("code",{children:a.id}),u.length>0&&(0,b.jsxs)(b.Fragment,{children:[" · ",(0,b.jsx)("strong",{children:u.length})," pending step",1===u.length?"":"s"]})]}),d.length>0?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)("div",{style:{fontSize:"var(--fs-xs)",color:"var(--fg-muted)",marginBottom:4},children:["Recent signals (",d.length,")"]}),(0,b.jsx)("div",{style:{maxHeight:300,overflowY:"auto",border:"1px solid var(--border)",borderRadius:4},children:(0,b.jsxs)("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:"var(--fs-xs)"},children:[(0,b.jsx)("thead",{style:{position:"sticky",top:0,background:"var(--bg-panel)"},children:(0,b.jsxs)("tr",{style:{textAlign:"left",color:"var(--fg-muted)"},children:[(0,b.jsx)("th",{style:{padding:"4px 6px"},children:"When"}),(0,b.jsx)("th",{style:{padding:"4px 6px"},children:"Strategy"}),(0,b.jsx)("th",{style:{padding:"4px 6px"},children:"Side"}),(0,b.jsx)("th",{style:{padding:"4px 6px",textAlign:"right"},children:"Base"}),(0,b.jsx)("th",{style:{padding:"4px 6px"},children:"Status"}),(0,b.jsx)("th",{style:{padding:"4px 6px",textAlign:"right"},children:"Steps"}),(0,b.jsx)("th",{style:{padding:"4px 6px",textAlign:"right"},children:"PnL"})]})}),(0,b.jsx)("tbody",{children:d.map((e,t)=>{let a=Number(e.signal_ts||0),s=a>0?new Date(1e3*a).toISOString().slice(5,16).replace("T"," "):"—",r=Number(e.final_pnl_usd??0),n=String(e.campaign_status||"pending");return(0,b.jsxs)("tr",{style:{borderTop:"1px solid var(--border)"},children:[(0,b.jsx)("td",{style:{padding:"4px 6px",fontFamily:"var(--font-mono)"},children:s}),(0,b.jsxs)("td",{style:{padding:"4px 6px"},children:[(0,b.jsx)("strong",{children:e.strategy_name||e.strategy_key}),(0,b.jsxs)("span",{style:{color:"var(--fg-muted)",marginLeft:4},children:[e.asset," ",e.tf]})]}),(0,b.jsx)("td",{style:{padding:"4px 6px"},children:String(e.entry_side||"").toUpperCase()}),(0,b.jsx)("td",{style:{padding:"4px 6px",textAlign:"right",fontFamily:"var(--font-mono)"},children:sk(Number(e.campaign_base_usd??0))}),(0,b.jsx)("td",{style:{padding:"4px 6px",color:"won"===n?"var(--success, #22c55e)":"lost"===n||"blown"===n?"var(--danger)":"var(--color-neutral, #f0b232)",fontWeight:600},children:n}),(0,b.jsx)("td",{style:{padding:"4px 6px",textAlign:"right"},children:e.ladder_steps_taken??0}),(0,b.jsx)("td",{style:{padding:"4px 6px",textAlign:"right",fontFamily:"var(--font-mono)",color:r>0?"var(--success, #22c55e)":r<0?"var(--danger)":"var(--fg)"},children:sk(r)})]},e.id||t)})})]})})]}):(0,b.jsx)("div",{style:{padding:"var(--space-3)",textAlign:"center",color:"var(--fg-muted)",fontSize:"var(--fs-xs)",border:"1px dashed var(--border)",borderRadius:4},children:"No signals yet. Worker checks every 60s; the next time any strategy in this aggregator fires, it'll appear here."}),h?(0,b.jsx)(sz,{aggregatorId:t,sessionId:h,isRunning:p}):null]})}var sW=e.i(9779);let sU={pusd:"pUSD",usdce:"USDC.e",pol:"POL"},sH=[{id:137,name:"Polygon",displayName:"Polygon",logoUrl:null,rpcUrl:null,nativeSymbol:"POL",nativeDecimals:18,tokens:[]},{id:1,name:"Ethereum",displayName:"Ethereum",logoUrl:null,rpcUrl:null,nativeSymbol:"ETH",
8nativeDecimals:18,tokens:[]},{id:8453,name:"Base",displayName:"Base",logoUrl:null,rpcUrl:null,nativeSymbol:"ETH",nativeDecimals:18,tokens:[]},{id:42161,name:"Arbitrum",displayName:"Arbitrum",logoUrl:null,rpcUrl:null,nativeSymbol:"ETH",nativeDecimals:18,tokens:[]},{id:10,name:"Optimism",displayName:"Optimism",logoUrl:null,rpcUrl:null,nativeSymbol:"ETH",nativeDecimals:18,tokens:[]}];function sq(e){let t=String(e||"");return t?`${t.slice(0,6)}…${t.slice(-4)}`:"—"}function sV(e){return null!=e&&Number.isFinite(e)?`$${Number(e).toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})}`:"—"}function sG(e){return null!=e&&Number.isFinite(e)?`${Number(e).toFixed(3)} POL`:"—"}function sJ(){let[e,t]=(0,_.useState)([]),[a,s]=(0,_.useState)([]),[r,n]=(0,_.useState)(new Set),[l,i]=(0,_.useState)("active"),[o,c]=(0,_.useState)(!1),[d,u]=(0,_.useState)(""),[h,p]=(0,_.useState)(""),[m,x]=(0,_.useState)({}),[g,f]=(0,_.useState)({}),[v,y]=(0,_.useState)(sH),[j,w]=(0,_.useState)([]),[N,k]=(0,_.useState)(!1),[S,$]=(0,_.useState)(!1),[C,M]=(0,_.useState)(!1),[E,A]=(0,_.useState)(!1),[T,F]=(0,_.useState)(null),[P,R]=(0,_.useState)(null),[O,L]=(0,_.useState)(!1),[I,D]=(0,_.useState)(!1),z=(0,_.useMemo)(()=>"archived"===l?a:"all"===l?[...e,...a]:e,[l,e,a]),B=(0,_.useMemo)(()=>z.filter(e=>r.has(e.id)),[z,r]),W=(0,_.useCallback)(()=>{u(""),p("")},[]),U=(0,_.useCallback)(async()=>{let[e,a]=await Promise.all([(0,er.authGetJson)("/api/wallets"),(0,er.authGetJson)("/api/wallets?include_archived=true")]);if(!e.ok)throw Error("Failed to load wallets");let r=Array.isArray(a.data)?a.data:[];t(Array.isArray(e.data)?e.data:[]),s(r.filter(e=>e.archived))},[]),H=(0,_.useCallback)(async()=>{try{let e=await (0,er.authGetJson)("/api/vault/supported-chains"),t=(e.ok&&Array.isArray(e.data)?e.data:[]).filter(e=>e&&"number"==typeof e.id);y(t.length?t:sH)}catch{}},[]),q=(0,_.useCallback)(async()=>{try{let e=await (0,er.authGetJson)("/api/wallets/address-book");e.ok&&w(Array.isArray(e.data)?e.data:[])}catch{}},[]),V=(0,_.useCallback)(async e=>{f(t=>({...t,[e]:!0}));try{let t=await (0,er.authGetJson)(`/api/wallets/${e}/balances`);t.ok&&t.data&&x(a=>({...a,[e]:t.data}))}catch{}f(t=>({...t,[e]:!1}))},[]);(0,_.useEffect)(()=>{c(!0),Promise.all([U(),H(),q()]).catch(e=>u(String(e?.message??e))).finally(()=>c(!1))},[U,H,q]),(0,_.useEffect)(()=>{let e=z.filter(e=>!m[e.id]&&!g[e.id]).map(e=>e.id);if(!e.length)return;let t=!1;return(async()=>{for(let a=0;a<e.length;a+=3){if(t)return;await Promise.all(e.slice(a,a+3).map(e=>V(e)))}})(),()=>{t=!0}},[z.map(e=>e.id).join("|")]);let G=(0,_.useCallback)(e=>{n(t=>{let a=new Set(t);return a.has(e)?a.delete(e):a.add(e),a})},[]),J=(0,_.useCallback)(()=>n(new Set),[]),Y=(0,_.useCallback)(()=>n(new Set(z.map(e=>e.id))),[z]),K=(0,_.useCallback)(async e=>{W(),c(!0);try{let t=await (0,er.authPostJson)(`/api/wallets/${e}/set-active`,{});if(!t.ok)throw Error(t.error||"Set active failed");p("Active wallet updated"),await U()}catch(e){u(String(e?.message??e))}finally{c(!1)}},[W,U]),X=(0,_.useCallback)(async e=>{W(),c(!0);try{let t=await (0,er.authPostJson)(`/api/wallets/${e}/export-private-key`,{});if(!t.ok)throw Error(t.error||"Export failed");let a=String(t.data?.private_key||"");if(!a)throw Error("Private key missing from response");try{await navigator.clipboard.writeText(a),p("Private key copied to clipboard.")}catch{window.prompt("Copy private key",a),p("Private key opened for manual copy.")}}catch(e){u(String(e?.message??e))}finally{c(!1)}},[W]),Z=(0,_.useCallback)(async e=>{W(),c(!0);try{let t=await (0,er.authPostJson)(`/api/wallets/${e}/deploy-deposit`,{});if(!t.ok)throw Error(t.error||"Deploy failed");let a=String(t.data?.deploy_note||"").trim();p(`Deploy: trading_ready=${t.data?.trading_ready?"yes":"no"}${a?` | ${a}`:""}`),await U()}catch(e){u(String(e?.message??e))}finally{c(!1)}},[W,U]),Q=(0,_.useCallback)(async e=>{try{let t=await (0,er.authPostJson)(`/api/wallets/${e}/refresh-profile`,{});if(!t.ok)throw Error(t.error||"Profile refresh failed");let a=t.data?.polymarket_username;p(a?`Polymarket username: @${a}`:"No Polymarket profile found for that proxy"),await U()}catch(e){u(String(e?.message??e))}},[U]),ee=(0,_.useCallback)(async e=>{W(),c(!0);try{let t=await (0,er.authPostJson)(`/api/wallets/${e}/unarchive`,{});if(!t.ok)throw Error(t.error||"Unarchive failed");p("Wallet restored"),await U()}catch(e){u(String(e?.message??e))}finally{c(!1)}},[W,U]);return(0,b.jsxs)("div",{className:"wallet-view wallet-view-v2",children:[(0,b.jsxs)("div",{className:"wallet-view-header",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("div",{className:"wallet-view-title",children:"Wallets"}),(0,b.jsxs)("div",{className:"wallet-view-subtitle",children:[e.length," active",a.length?` \xb7 ${a.length} archived`:"",r.size?` \xb7 ${r.size} selected`:""]})]}),(0,b.jsxs)("div",{className:"wallet-view-header-actions",children:[(0,b.jsxs)("button",{className:"btn",onClick:()=>D(!0),title:"Saved external destinations",children:["Address book (",j.length,")"]}),(0,b.jsx)("button",{className:"btn",onClick:()=>U().catch(e=>u(String(e?.message??e))),disabled:o,children:"Refresh"}),(0,b.jsx)("button",{className:"btn",onClick:()=>{W(),$(!0)},title:"Import an existing key that already controls a Polymarket proxy",children:"Import wallet"}),(0,b.jsx)("button",{className:"btn btn-primary",onClick:()=>{W(),k(!0)},children:"+ New wallet"})]})]}),d?(0,b.jsx)("div",{className:"wallet-alert error",children:d}):null,h?(0,b.jsx)("div",{className:"wallet-alert success",children:h}):null,(0,b.jsxs)("div",{className:"wallet-toolbar",children:[(0,b.jsx)("div",{className:"wallet-filter-chips",children:["active","archived","all"].map(t=>(0,b.jsx)("button",{className:`wallet-chip${l===t?" active":""}`,onClick:()=>{i(t),J()},children:"active"===t?`Active (${e.length})`:"archived"===t?`Archived (${a.length})`:`All (${e.length+a.length})`},t))}),(0,b.jsxs)("div",{className:"wallet-action-bar",children:[r.size>0&&(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)("button",{className:"btn",onClick:J,title:"Clear selection",children:["Clear (",r.size,")"]}),(0,b.jsx)("button",{className:"btn",disabled:1!==r.size,title:1!==r.size?"Select exactly one source wallet":"Disperse pUSD from this wallet to many",onClick:()=>{W(),M(!0)},children:"Disperse from selected"}),(0,b.jsx)("button",{className:"btn",disabled:r.size<1,title:"Collect available pUSD from selected wallets into one destination",onClick:()=>{W(),A(!0)},children:"Collect from selected"})]}),z.length>0&&r.size!==z.length&&(0,b.jsx)("button",{className:"btn btn-xs",onClick:Y,children:"Select all"})]})]}),o&&0===z.length?(0,b.jsx)("div",{className:"wallet-card-grid",children:Array.from({length:3}).map((e,t)=>(0,b.jsxs)("div",{className:"wallet-card",children:[(0,b.jsx)("div",{className:"wallet-card-head",children:(0,b.jsxs)("div",{style:{flex:1},children:[(0,b.jsx)("span",{className:"skeleton",style:{display:"block",width:"60%",height:16,marginBottom:6}}),(0,b.jsx)("span",{className:"skeleton",style:{display:"block",width:"40%",height:12}})]})}),(0,b.jsxs)("div",{className:"wallet-card-body",children:[(0,b.jsx)("span",{className:"skeleton",style:{display:"block",width:"100%",height:14,marginBottom:6}}),(0,b.jsx)("span",{className:"skeleton",style:{display:"block",width:"100%",height:14,marginBottom:6}}),(0,b.jsx)("span",{className:"skeleton",style:{display:"block",width:"100%",height:14}})]})]},t))}):0===z.length?(0,b.jsx)("div",{className:"empty-state",style:{padding:"var(--space-5)"},children:"archived"===l?"No archived wallets.":"all"===l?"No wallets yet.":"No active wallets. Create one above."}):(0,b.jsx)("div",{className:"wallet-card-grid",children:z.map(e=>(0,b.jsx)(sY,{wallet:e,balances:m[e.id],loadingBalances:!!g[e.id],selected:r.has(e.id),onToggleSelect:()=>G(e.id),onSetActive:()=>K(e.id),onDeposit:()=>{W(),R(e)},onExportKey:()=>X(e.id),onDeployNow:()=>Z(e.id),onArchive:()=>{W(),F(e)},onUnarchive:()=>ee(e.id),onRefreshBalances:()=>V(e.id),onRefreshProfile:()=>Q(e.id)},e.id))}),(0,b.jsx)(s3,{open:O,onToggle:()=>L(e=>!e),wallets:e}),N&&(0,b.jsx)(sK,{onClose:()=>k(!1),onCreated:async()=>{k(!1),p("Wallet created"),await U()}}),S&&(0,b.jsx)(sX,{onClose:()=>$(!1),onImported:async e=>{$(!1);let t=e?.polymarket_username?` (@${e.polymarket_username})`:"";p(`Imported ${e?.wallet_name||"wallet"}${t}`),await U()}}),C&&1===B.length&&(0,b.jsx)(s1,{source:B[0],balances:m[B[0].id],allWallets:e,addressBook:j,onSaveAddress:q,onClose:()=>M(!1),onSuccess:async()=>{M(!1),p("Disperse submitted"),await U(),await V(B[0].id)}}),E&&B.length>=1&&(0,b.jsx)(s2,{sources:B,balancesById:m,allWallets:e,addressBook:j,onSaveAddress:q,onClose:()=>A(!1),onSuccess:async()=>{for(let e of(A(!1),p("Collect submitted"),await U(),B))await V(e.id)}}),T&&(0,b.jsx)(s5,{wallet:T,balances:m[T.id],allWallets:e,addressBook:j,onSaveAddress:q,onClose:()=>F(null),onSuccess:async()=>{let e=T.wallet_name;F(null),p(`Archived ${e}`),await U()}}),I&&(0,b.jsx)(s4,{entries:j,onClose:()=>D(!1),onReload:q}),P&&(0,b.jsx)(sW.ProxyWalletDepositModal,{address:P.trading_address||P.wallet_address,onClose:()=>R(null),chains:v,walletUsdTotal:null,destinationCurrency:"0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB",fundQuoteEndpoint:`/api/wallets/${P.id}/fund-quote`,fundStatusEndpoint:"/api/user/fund-status",onDepositComplete:()=>{p(`Deposit confirmed for ${P.wallet_name}.`),V(P.id).catch(()=>{}),U().catch(()=>{})}})]})}function sY({wallet:e,balances:t,loadingBalances:a,selected:s,onToggleSelect:r,onSetActive:n,onDeposit:l,onExportKey:i,onDeployNow:o,onArchive:c,onUnarchive:d,onRefreshBalances:u,onRefreshProfile:h}){let p=!!e.archived,m=t?.proxy,x=t?.eoa,g=p?{label:"ARCHIVED",tone:"muted"}:e.is_active?{label:"ACTIVE",tone:"success"}:!1===e.trading_ready?{label:"NOT DEPLOYED",tone:"warn"}:{label:"READY",tone:"info"};return(0,b.jsxs)("div",{className:`wallet-card${s?" selected":""}${p?" archived":""}`,children:[(0,b.jsxs)("div",{className:"wallet-card-head",children:[(0,b.jsxs)("label",{className:"wallet-card-checkbox",children:[(0,b.jsx)("input",{type:"checkbox",checked:s,onChange:r}),(0,b.jsx)("span",{})]}),(0,b.jsxs)("div",{className:"wallet-card-title",children:[(0,b.jsx)("div",{className:"wallet-card-name",children:e.wallet_name}),e.polymarket_username&&(0,b.jsxs)("div",{className:"wallet-card-handle",title:"Polymarket display username",children:["@",e.polymarket_username]}),(0,b.jsxs)("div",{className:"wallet-card-addr",children:["trading ",sq(e.trading_address||e.wallet_address)]})]}),(0,b.jsx)("span",{className:`wallet-badge tone-${g.tone}`,children:g.label})]}),(0,b.jsxs)("div",{className:"wallet-card-body",children:[(0,b.jsxs)("div",{className:"wallet-card-row",children:[(0,b.jsx)("div",{className:"wallet-card-label",children:"Proxy available"}),(0,b.jsx)("div",{className:"wallet-card-value primary",children:a&&!m?(0,b.jsx)(aw,{size:"sm"}):sV(m?.pusd_available)})]}),(0,b.jsxs)("div",{className:"wallet-card-row sub",children:[(0,b.jsxs)("div",{className:"wallet-card-label",children:["of total ",a&&!m?(0,b.jsx)(aw,{size:"sm"}):sV(m?.pusd_total)]}),(0,b.jsx)("div",{className:"wallet-card-value",children:m&&m.pusd_locked_orders>0?(0,b.jsxs)("span",{title:`${m.open_buy_orders} open buy order${1===m.open_buy_orders?"":"s"} locking pUSD`,children:["locked ",sV(m.pusd_locked_orders)]}):null})]}),(0,b.jsxs)("div",{className:"wallet-card-row",children:[(0,b.jsx)("div",{className:"wallet-card-label",children:"Gas (proxy)"}),(0,b.jsx)("div",{className:"wallet-card-value",children:a&&!m?(0,b.jsx)(aw,{size:"sm"}):sG(m?.pol)})]}),(0,b.jsxs)("div",{className:"wallet-card-row",children:[(0,b.jsx)("div",{className:"wallet-card-label",children:"EOA"}),(0,b.jsxs)("div",{className:"wallet-card-value small",children:[sV(x?.pusd)," · ",sG(x?.pol)]})]}),m?.locked_lookup_error&&(0,b.jsx)("div",{className:"wallet-card-warn",title:m.locked_lookup_error,children:"Locked-pUSD lookup unavailable — available may be off"}),e.deploy_note&&(0,b.jsx)("div",{className:"wallet-card-warn",children:e.deploy_note})]}),(0,b.jsx)("div",{className:"wallet-card-actions",children:p?(0,b.jsx)("button",{className:"btn btn-xs",onClick:d,title:"Restore wallet",children:"Unarchive"}):(0,b.jsxs)(b.Fragment,{children:[!e.is_active&&!1!==e.trading_ready&&(0,b.jsx)("button",{className:"btn btn-xs",onClick:n,children:"Set active"}),!1===e.trading_ready&&3===e.signature_type&&(0,b.jsx)("button",{className:"btn btn-xs",onClick:o,title:"Deploy deposit wallet",children:"Deploy"}),(0,b.jsx)("button",{className:"btn btn-xs btn-primary",onClick:l,children:"Deposit"}),(0,b.jsx)("button",{className:"btn btn-xs",onClick:i,title:"Copy private key",children:"Export key"}),(0,b.jsx)("button",{className:"btn btn-xs",onClick:u,title:"Re-fetch balances",children:"↻ bal"}),(0,b.jsx)("button",{className:"btn btn-xs",onClick:h,title:"Re-fetch Polymarket username",children:"↻ name"}),(0,b.jsx)("button",{className:"btn btn-xs",onClick:c,title:"Archive this wallet",children:"Archive"})]})})]})}function sK({onClose:e,onCreated:t}){let[a,s]=(0,_.useState)({wallet_name:"",generate_private_key:!0,private_key:"",api_key:"",api_secret:"",api_passphrase:"",n
8otes:""}),[r,n]=(0,_.useState)(!1),[l,i]=(0,_.useState)("");async function o(){i(""),n(!0);try{let e=await (0,er.authPostJson)("/api/wallets/create",{...a,signature_type:3});if(!e.ok)throw Error(e.error||"Create failed");await t()}catch(e){i(String(e?.message??e))}finally{n(!1)}}return(0,b.jsx)(s9,{title:"Create wallet",onClose:e,width:520,children:(0,b.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"var(--space-3)"},children:[(0,b.jsx)(s8,{label:"Wallet name",children:(0,b.jsx)("input",{type:"text",autoFocus:!0,value:a.wallet_name,onChange:e=>s(t=>({...t,wallet_name:e.target.value}))})}),(0,b.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:"var(--space-2)",fontSize:"var(--fs-sm)"},children:[(0,b.jsx)("input",{type:"checkbox",checked:a.generate_private_key,onChange:e=>s(t=>({...t,generate_private_key:e.target.checked}))}),"Auto-generate private key on server"]}),!a.generate_private_key&&(0,b.jsx)(s8,{label:"Private key",children:(0,b.jsx)("input",{type:"password",value:a.private_key,onChange:e=>s(t=>({...t,private_key:e.target.value})),placeholder:"0x..."})}),(0,b.jsx)(s8,{label:"Notes (optional)",children:(0,b.jsx)("input",{type:"text",value:a.notes,onChange:e=>s(t=>({...t,notes:e.target.value}))})}),(0,b.jsxs)("details",{style:{fontSize:"var(--fs-xs)"},children:[(0,b.jsx)("summary",{style:{cursor:"pointer",color:"var(--fg-muted)"},children:"Advanced: CLOB API credentials"}),(0,b.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"var(--space-2)",marginTop:"var(--space-2)"},children:[(0,b.jsx)(s8,{label:"API key",children:(0,b.jsx)("input",{type:"text",value:a.api_key,onChange:e=>s(t=>({...t,api_key:e.target.value}))})}),(0,b.jsx)(s8,{label:"API secret",children:(0,b.jsx)("input",{type:"password",value:a.api_secret,onChange:e=>s(t=>({...t,api_secret:e.target.value}))})}),(0,b.jsx)(s8,{label:"API passphrase",children:(0,b.jsx)("input",{type:"password",value:a.api_passphrase,onChange:e=>s(t=>({...t,api_passphrase:e.target.value}))})})]})]}),l&&(0,b.jsx)("div",{className:"wallet-alert error",children:l}),(0,b.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:"var(--space-2)"},children:[(0,b.jsx)("button",{className:"btn",onClick:e,disabled:r,children:"Cancel"}),(0,b.jsx)("button",{className:"btn btn-primary",onClick:o,disabled:r||!a.wallet_name||!a.generate_private_key&&!a.private_key,children:(0,b.jsx)(aN,{busy:r,label:"Create",busyLabel:"Creating…"})})]})]})})}function sX({onClose:e,onImported:t}){let[a,s]=(0,_.useState)(""),[r,n]=(0,_.useState)(""),[l,i]=(0,_.useState)(""),[o,c]=(0,_.useState)(!1),[d,u]=(0,_.useState)(""),[h,p]=(0,_.useState)(null),[m,x]=(0,_.useState)(!1),[g,f]=(0,_.useState)(""),[v,y]=(0,_.useState)(2),[j,w]=(0,_.useState)(!1),[N,k]=(0,_.useState)(""),[S,$]=(0,_.useState)(!1),[C,M]=(0,_.useState)(null),[E,A]=(0,_.useState)("");async function T(){if(A(""),M(null),!/^0x[a-fA-F0-9]{40}$/.test(N.trim()))return void A("Paste a 0x... EVM address (NOT a private key).");$(!0);try{let e=await (0,er.authGetJson)(`/api/wallets/derive-proxy?address=${encodeURIComponent(N.trim())}`);if(!e.ok||!e.data)throw Error(e.error||"Lookup failed");M(e.data)}catch(e){A(String(e?.message??e))}finally{$(!1)}}async function F(){u(""),p(null),c(!0);try{let e={private_key:a.trim(),wallet_name:r.trim()||void 0,notes:l.trim()||void 0};if(m){if(!/^0x[a-fA-F0-9]{40}$/.test(g.trim()))throw Error("Proxy address must be a valid 0x... address");e.proxy_address=g.trim(),e.signature_type=v}let s=await (0,er.authPostJson)("/api/wallets/import",e);if(!s.ok||!s.data)throw(s.owner_address||s.derived_proxy)&&p({owner_address:s.owner_address,derived_proxy:s.derived_proxy}),Error(s.error||"Import failed");await t(s.data)}catch(e){u(String(e?.message??e))}finally{c(!1)}}return(0,b.jsx)(s9,{title:"Import existing wallet",onClose:e,width:540,children:(0,b.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"var(--space-3)"},children:[(0,b.jsx)("div",{style:{fontSize:"var(--fs-xs)",color:"var(--fg-muted)"},children:'Paste a private key from a wallet that already controls a Polymarket account. We auto-detect which wallet type your account uses — SAFE (older "Connect Wallet" accounts), deposit-wallet (newer accounts), or legacy proxy — and pull the public Polymarket username for labeling.'}),(0,b.jsxs)("details",{open:j,onToggle:e=>w(e.target.open),children:[(0,b.jsx)("summary",{style:{cursor:"pointer",fontSize:"var(--fs-xs)",color:"var(--accent, #60a5fa)"}
8,children:"Don't know which key to use? Check an address first (no key needed)"}),(0,b.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"var(--space-2)",marginTop:"var(--space-2)",padding:"var(--space-2)",background:"var(--bg-input)",border:"1px solid var(--border-subtle)",borderRadius:6},children:[(0,b.jsxs)("div",{style:{fontSize:"var(--fs-xs)",color:"var(--fg-muted)"},children:["Paste your ",(0,b.jsx)("strong",{children:"public EOA address"})," (not a key) from Phantom — we'll show you what proxy it controls + whether it matches your Polymarket profile. Iterate through Phantom accounts until you find the one whose derived proxy matches the address shown at polymarket.com/profile/<...>."]}),(0,b.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr auto",gap:"var(--space-2)"},children:[(0,b.jsx)("input",{type:"text",placeholder:"0x... (public address, NOT private key)",value:N,onChange:e=>k(e.target.value),onKeyDown:e=>{"Enter"===e.key&&T()}}),(0,b.jsx)("button",{className:"btn btn-xs",onClick:T,disabled:S||!N.trim(),children:S?"Checking…":"Check"})]}),E&&(0,b.jsx)("div",{style:{fontSize:"var(--fs-xs)",color:"var(--danger, #fca5a5)"},children:E}),C&&(0,b.jsxs)("div",{style:{fontSize:"var(--fs-xs)",display:"flex",flexDirection:"column",gap:6},children:[(0,b.jsxs)("div",{style:{fontFamily:"var(--font-mono)"},children:["EOA: ",C.owner_address]}),[{label:"SAFE (sig 2)",c:C.safe},{label:"Deposit wallet (sig 3)",c:C.deposit_wallet},{label:"Legacy proxy (sig 1)",c:C.proxy}].map(({label:e,c:t})=>{let a=C.best_match?.address===t.address,s=t.deployed&&(t.polymarket_username||t.pusd_balance&&t.pusd_balance>0);return(0,b.jsxs)("div",{style:{padding:"var(--space-2)",border:`1px solid ${a?"var(--success, #22c55e)":"var(--border-subtle)"}`,borderRadius:6,background:a?"rgba(34, 197, 94, 0.06)":"transparent"},children:[(0,b.jsxs)("div",{style:{fontWeight:600,marginBottom:2},children:[e," ",a&&(0,b.jsx)("span",{style:{color:"var(--success, #86efac)"},children:"← best match"})]}),(0,b.jsx)("div",{style:{fontFamily:"var(--font-mono)"},children:t.address}),(0,b.jsxs)("div",{style:{color:"var(--fg-muted)"},children:["deployed: ",t.deployed?"yes":"no"," · ","handle: ",t.polymarket_username?`@${t.polymarket_username}`:"—"," · ","pUSD: ",null!=t.pusd_balance?sV(t.pusd_balance):"—"]}),s&&(0,b.jsx)("div",{style:{color:"var(--success, #86efac)",marginTop:2},children:"✓ Real trading proxy — Import auto-detect will pick this one."})]},e)})]})]})]}),(0,b.jsx)(s8,{label:"Private key",children:(0,b.jsx)("input",{type:"password",autoFocus:!0,placeholder:"0x...",value:a,onChange:e=>s(e.target.value)})}),(0,b.jsxs)("details",{open:m,onToggle:e=>x(e.target.open),children:[(0,b.jsx)("summary",{style:{cursor:"pointer",fontSize:"var(--fs-xs)",color:"var(--accent, #60a5fa)"},children:"Override auto-detect: paste a specific proxy address"}),(0,b.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"var(--space-2)",marginTop:"var(--space-2)",padding:"var(--space-2)",background:"var(--bg-input)",border:"1px solid var(--border-subtle)",borderRadius:6},children:[(0,b.jsxs)("div",{style:{fontSize:"var(--fs-xs)",color:"var(--fg-muted)"},children:["Only needed if auto-detect picks the wrong wallet (e.g. an EOA owns multiple Polymarket accounts of different types). Copy your real proxy from ",(0,b.jsx)("strong",{children:"polymarket.com/profile/<...>"}),"."]}),(0,b.jsx)(s8,{label:"Proxy address",children:(0,b.jsx)("input",{type:"text",placeholder:"0x...",value:g,onChange:e=>f(e.target.value)})}),(0,b.jsx)(s8,{label:"Wallet type",children:(0,b.jsxs)("select",{value:v,onChange:e=>y(Number(e.target.value)),children:[(0,b.jsx)("option",{value:2,children:"SAFE — sig 2"}),(0,b.jsx)("option",{value:1,children:"POLY_PROXY — sig 1"}),(0,b.jsx)("option",{value:3,children:"Deposit wallet — sig 3"})]})}),(0,b.jsx)("div",{style:{fontSize:"var(--fs-xs)",color:"var(--fg-muted)"},children:"Disperse + Collect now work for all three wallet types (pUSD and USDC.e). Native POL transfers are only supported on sig=3 deposit wallets — for SAFE/PROXY, Polymarket sponsors gas so you don't typically need to move POL."})]})]}),(0,b.jsx)(s8,{label:"Wallet name (optional)",children:(0,b.jsx)("input",{type:"text",placeholder:"Defaults to the Polymarket @username",value:r,onChange:e=>n(e.target.value)})}),(0,b.jsx)(s8,{label:"Notes (optional)",children:(0,b.jsx)("input",{type:"text",value:l,onCh
8ange:e=>i(e.target.value)})}),d&&(0,b.jsxs)("div",{className:"wallet-alert error",children:[(0,b.jsx)("div",{children:d}),h&&(h.owner_address||h.derived_proxy)&&(0,b.jsxs)("div",{style:{marginTop:4,fontSize:"var(--fs-xs)",fontFamily:"var(--font-mono)"},children:[h.owner_address&&(0,b.jsxs)("div",{children:["owner: ",h.owner_address]}),h.derived_proxy&&(0,b.jsxs)("div",{children:["derived proxy: ",h.derived_proxy]})]})]}),(0,b.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:"var(--space-2)"},children:[(0,b.jsx)("button",{className:"btn",onClick:e,disabled:o,children:"Cancel"}),(0,b.jsx)("button",{className:"btn btn-primary",onClick:F,disabled:o||!a.trim(),children:(0,b.jsx)(aN,{busy:o,label:"Import",busyLabel:"Importing…"})})]})]})})}function sZ({excludeWalletIds:e,wallets:t,addressBook:a,onSaveAddress:s,value:r,onChange:n}){let[l,i]=(0,_.useState)(r?"address_book_id"in r?"saved":"address"in r?"external":"wallet":"wallet"),o=t.filter(t=>!e.includes(t.id)),c=r&&"address"in r?r.address:"",d=/^0x[a-fA-F0-9]{40}$/.test(c),u=a.some(e=>e.address.toLowerCase()===c.toLowerCase());async function h(){let e=window.prompt("Label this address (e.g. 'Cold storage'):");if(e&&e.trim())try{let t=await (0,er.authPostJson)("/api/wallets/address-book",{label:e.trim(),address:c});if(!t.ok)throw Error(t.error||"Save failed");await s(),t.data?.id&&(i("saved"),n({address_book_id:t.data.id}))}catch(e){window.alert(String(e?.message??e))}}return(0,b.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"var(--space-2)"},children:[(0,b.jsxs)("div",{style:{display:"inline-flex",border:"1px solid var(--border)",borderRadius:6,overflow:"hidden",width:"fit-content"},children:[(0,b.jsx)("button",{className:"wallet"===l?"btn btn-xs btn-primary":"btn btn-xs",onClick:()=>{i("wallet"),n(null)},style:{borderRadius:0},children:"One of my wallets"}),(0,b.jsxs)("button",{className:"saved"===l?"btn btn-xs btn-primary":"btn btn-xs",onClick:()=>{i("saved"),n(null)},style:{borderRadius:0},children:["Saved (",a.length,")"]}),(0,b.jsx)("button",{className:"external"===l?"btn btn-xs btn-primary":"btn btn-xs",onClick:()=>{i("external"),n(null)},style:{borderRadius:0},children:"External address"})]}),"wallet"===l&&(0,b.jsxs)("select",{value:r&&"wallet_id"in r?r.wallet_id:"",onChange:e=>{let t=e.target.value;n(t?{wallet_id:t}:null)},children:[(0,b.jsx)("option",{value:"",children:"— pick a wallet —"}),o.map(e=>(0,b.jsxs)("option",{value:e.id,children:[e.wallet_name," (",sq(e.trading_address||e.wallet_address),")"]},e.id))]}),"saved"===l&&(0===a.length?(0,b.jsx)("div",{style:{fontSize:"var(--fs-xs)",color:"var(--fg-muted)"},children:'No saved addresses yet. Use "External address" mode and click Save to add one.'}):(0,b.jsxs)("select",{value:r&&"address_book_id"in r?r.address_book_id:"",onChange:e=>{let t=e.target.value;n(t?{address_book_id:t}:null)},children:[(0,b.jsx)("option",{value:"",children:"— pick a saved address —"}),a.map(e=>(0,b.jsxs)("option",{value:e.id,children:[e.label," (",sq(e.address),")"]},e.id))]})),"external"===l&&(0,b.jsxs)("div",{style:{display:"flex",gap:"var(--space-2)"},children:[(0,b.jsx)("input",{type:"text",placeholder:"0x...",style:{flex:1},value:c,onChange:e=>{let t=e.target.value.trim();n(t?{address:t}:null)}}),d&&!u&&(0,b.jsx)("button",{className:"btn btn-xs",onClick:h,title:"Save to address book",children:"Save"})]})]})}function sQ(e,t){return e?"pusd"===t?e.proxy?.pusd_available??0:"usdce"===t?e.proxy?.usdce??0:"pol"===t?e.proxy?.pol??0:0:0}function s0(e,t){return null!=e&&Number.isFinite(e)?"pol"===t?`${Number(e).toFixed(4)} POL`:`${"pusd"===t||"usdce"===t?"$":""}${Number(e).toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:4})}`:"—"}function s1({source:e,balances:t,allWallets:a,addressBook:s,onSaveAddress:r,onClose:n,onSuccess:l}){let[i,o]=(0,_.useState)("pusd"),c=sQ(t,i),[d,u]=(0,_.useState)("per_destination"),[h,p]=(0,_.useState)([{dest:null,amount:""}]),[m,x]=(0,_.useState)(""),[g,f]=(0,_.useState)("100"),[v,y]=(0,_.useState)(!1),[j,w]=(0,_.useState)(""),[N,k]=(0,_.useState)(null),S=(0,_.useMemo)(()=>{let e=h.filter(e=>null!=e.dest);if("per_destination"===d)return e.map(e=>({dest:e.dest,amount:Number(e.amount)})).filter(e=>Number.isFinite(e.amount)&&e.amount>0);if("equal_split"===d){let t=Number(m);if(!Number.isFinite(t)||t<=0||0===e.length)return[];let a=t/e.length;return e.map(e=>({dest:e.dest,amount:a}))}let t=Number(g);if(!Number.isFinite(t)||t<=0||0===e.length||c<=0)return[];let a=t/100*c/e.length;return e.map(e=>({dest:e.dest,amount:a}))},[d,h,m,g,c]),$=S.reduce((e,t)=>
8e+t.amount,0),C=c-$,M=$>c+1e-6;function E(e,t){p(a=>a.map((a,s)=>s===e?{...a,...t}:a))}async function A(){if(w(""),k(null),!S.length)return void w("Add at least one destination with a valid amount.");if(M)return void w(`Total exceeds available ${sU[i]} (${s0(c,i)})`);y(!0);try{let t=S.map(e=>{let t={amount:e.amount};return"wallet_id"in e.dest?t.wallet_id=e.dest.wallet_id:"address_book_id"in e.dest?t.address_book_id=e.dest.address_book_id:t.address=e.dest.address,t}),a=await (0,er.authPostJson)(`/api/wallets/${e.id}/transfer`,{destinations:t,token:i});if(!a.ok)throw Error(a.error||"Transfer failed");k(a.data),await l()}catch(e){w(String(e?.message??e))}finally{y(!1)}}return(0,b.jsx)(s9,{title:`Disperse ${sU[i]} from ${e.wallet_name}`,onClose:n,width:680,children:(0,b.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"var(--space-3)"},children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("div",{style:{fontSize:"var(--fs-xs)",color:"var(--fg-muted)",marginBottom:4},children:"Token"}),(0,b.jsx)("div",{style:{display:"inline-flex",border:"1px solid var(--border)",borderRadius:6,overflow:"hidden",width:"fit-content"},children:["pusd","usdce","pol"].map(e=>(0,b.jsx)("button",{className:i===e?"btn btn-xs btn-primary":"btn btn-xs",onClick:()=>o(e),style:{borderRadius:0},children:sU[e]},e))}),"pol"===i&&(0,b.jsx)("div",{style:{fontSize:"var(--fs-xs)",color:"#fbbf24",marginTop:4},children:"POL is native gas. Leave a reserve so future operations from this wallet can still pay gas."})]}),(0,b.jsxs)("div",{className:"wallet-card-row",children:[(0,b.jsxs)("div",{className:"wallet-card-label",children:["Available ",sU[i]," (proxy)"]}),(0,b.jsx)("div",{className:"wallet-card-value primary",children:s0(c,i)})]}),"pusd"===i&&t?.proxy?.pusd_locked_orders&&t.proxy.pusd_locked_orders>0?(0,b.jsxs)("div",{style:{fontSize:"var(--fs-xs)",color:"var(--fg-muted)"},children:[sV(t.proxy.pusd_locked_orders)," locked in ",t.proxy.open_buy_orders," open buy order",1===t.proxy.open_buy_orders?"":"s"," — cancel them in the trading view first if you need to free that up."]}):null,(0,b.jsx)("div",{style:{display:"inline-flex",border:"1px solid var(--border)",borderRadius:6,overflow:"hidden",width:"fit-content"},children:["per_destination","equal_split","percent"].map(e=>(0,b.jsx)("button",{className:d===e?"btn btn-xs btn-primary":"btn btn-xs",onClick:()=>u(e),style:{borderRadius:0},children:"per_destination"===e?"Per destination":"equal_split"===e?"Equal split":"% of available"},e))}),"equal_split"===d&&(0,b.jsx)(s8,{label:`Total amount (${sU[i]})`,children:(0,b.jsx)("input",{type:"text",value:m,onChange:e=>x(e.target.value),placeholder:String(c.toFixed(4))})}),"percent"===d&&(0,b.jsx)(s8,{label:"% of available",children:(0,b.jsx)("input",{type:"text",value:g,onChange:e=>f(e.target.value),placeholder:"100"})}),(0,b.jsxs)("div",{children:[(0,b.jsx)("div",{style:{fontSize:"var(--fs-xs)",color:"var(--fg-muted)",marginBottom:"var(--space-2)"},children:"Destinations"}),(0,b.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:"var(--space-3)"},children:h.map((t,n)=>(0,b.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 140px 32px",gap:"var(--space-2)",alignItems:"start"},children:[(0,b.jsx)(sZ,{excludeWalletIds:[e.id],wallets:a,addressBook:s,onSaveAddress:r,value:t.dest,onChange:e=>E(n,{dest:e})}),"per_destination"===d?(0,b.jsx)("input",{type:"text",placeholder:"0.00",value:t.amount,onChange:e=>E(n,{amount:e.target.value})}):(0,b.jsx)("div",{style:{alignSelf:"center",color:"var(--fg-muted)",fontSize:"var(--fs-xs)"},children:S[n]?s0(S[n].amount,i):"—"}),(0,b.jsx)("button",{className:"btn btn-xs",onClick:()=>{p(e=>e.filter((e,t)=>t!==n))},disabled:1===h.length,title:"Remove",children:"×"})]},n))}),(0,b.jsx)("button",{className:"btn btn-xs",style:{marginTop:"var(--space-2)"},onClick:function(){p(e=>[...e,{dest:null,amount:""}])},children:"+ Add destination"})]}),(0,b.jsxs)("div",{className:"wallet-card-row",children:[(0,b.jsx)("div",{className:"wallet-card-label",children:"Total requested"}),(0,b.jsx)("div",{className:`wallet-card-value ${M?"danger":"primary"}`,children:s0($,i)})]}),(0,b.jsxs)("div",{className:"wallet-card-row sub",children:[(0,b.jsx)("div",{className:"wallet-card-label",children:"Remainder"}),(0,b.jsx)("div",{className:"wallet-card-value",children:s0(C,i)})]}),j&&(0,b.jsx)("div",{className:"wallet-alert error",children:j}),N&&(0,b.jsx)("pre",{className:"wallet-json",children:JSON.stringify(N,null,2)}),(0,b.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:"var(--space-2)"},children:[(0,b.jsx)("button",{className:"btn",onClick:n,disabled:v,children:"Cancel"}),(0,b.jsx)("button",{className:"btn btn-primary",onClick:A,disabled:v||0===S.length||M,children:(0,b.jsx)(aN,{busy:v,label:`Disperse to ${S.length} dest`,busyLabel:"Submitting…"})})]})]})})}function s2({sources:e,balancesById:t,allWallets:a,addressBook:s,onSaveAddress:r,onClose:n,onSuccess:l}){let[i,o]=(0,_.useState)("pusd"),[c,d]=(0,_.useState)(null),[u,h]=(0,_.useState)({}),[p,m]=(0,_.useState)(!1),[x,g]=(0,_.useState)(""),[f,v]=(0,_.useState)(null);(0,_.useEffect)(()=>{h({})},[i]);let y=(0,_.useMemo)(()=>{let a={};for(let s of e)a[s.id]=sQ(t[s.id],i);return a},[e,t,i]),j=(0,_.useMemo)(()=>{let t=0;for(let a of e){let e=u[a.id],s=e?Number(e):y[a.id];Number.isFinite(s)&&s>0&&(t+=Math.min(s,y[a.id]??0))}return t},[u,y,e]),w=e.reduce((e,t)=>
8e+(y[t.id]??0),0);async function N(){if(g(""),v(null),!c)return void g("Pick a destination");if(j<=0)return void g(`No ${sU[i]} to sweep — sources have nothing available`);m(!0);try{let t=[];for(let a of e){let e=u[a.id]?.trim();if(!e){t.push({wallet_id:a.id});continue}let s=Number(e);Number.isFinite(s)&&!(s<=0)&&t.push({wallet_id:a.id,amount:s})}let a=await (0,er.authPostJson)("/api/wallets/sweep",{sources:t,destination:c,token:i});if(!a.ok)throw Error(a.error||"Sweep failed");v(a.data),await l()}catch(e){g(String(e?.message??e))}finally{m(!1)}}return(0,b.jsx)(s9,{title:`Collect from ${e.length} wallet${1===e.length?"":"s"}`,onClose:n,width:620,children:(0,b.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"var(--space-3)"},children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("div",{style:{fontSize:"var(--fs-xs)",color:"var(--fg-muted)",marginBottom:4},children:"Token"}),(0,b.jsx)("div",{style:{display:"inline-flex",border:"1px solid var(--border)",borderRadius:6,overflow:"hidden",width:"fit-content"},children:["pusd","usdce","pol"].map(e=>(0,b.jsx)("button",{className:i===e?"btn btn-xs btn-primary":"btn btn-xs",onClick:()=>o(e),style:{borderRadius:0},children:sU[e]},e))})]}),(0,b.jsxs)("div",{className:"wallet-card-row",children:[(0,b.jsx)("div",{className:"wallet-card-label",children:"Total available across sources"}),(0,b.jsx)("div",{className:"wallet-card-value primary",children:s0(w,i)})]}),(0,b.jsx)("div",{style:{fontSize:"var(--fs-xs)",color:"var(--fg-muted)"},children:"Leave an amount blank to sweep that source's full available balance. Type a number to send less than available. Per-source amounts are capped at what's actually available."}),(0,b.jsxs)("div",{children:[(0,b.jsx)("div",{style:{fontSize:"var(--fs-xs)",color:"var(--fg-muted)",marginBottom:"var(--space-1)"},children:"Sources"}),(0,b.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:4,padding:"var(--space-2)",border:"1px solid var(--border)",borderRadius:6},children:e.map(e=>{let t=y[e.id]??0;return(0,b.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 140px",gap:"var(--space-2)",alignItems:"center"},children:[(0,b.jsxs)("div",{style:{fontSize:"var(--fs-xs)"},children:[e.wallet_name," ",(0,b.jsxs)("span",{style:{color:"var(--fg-muted)"},children:["(",sq(e.trading_address||e.wallet_address),") · available ",s0(t,i)]})]}),(0,b.jsx)("input",{type:"text",placeholder:t>0?`all (${t.toFixed("pol"===i?4:2)})`:"0",value:u[e.id]??"",onChange:t=>h(a=>({...a,[e.id]:t.target.value}))})]},e.id)})})]}),(0,b.jsxs)("div",{className:"wallet-card-row",children:[(0,b.jsx)("div",{className:"wallet-card-label",children:"Total to send"}),(0,b.jsx)("div",{className:"wallet-card-value primary",children:s0(j,i)})]}),(0,b.jsx)(s8,{label:"Destination",children:(0,b.jsx)(sZ,{excludeWalletIds:e.map(e=>e.id),wallets:a,addressBook:s,onSaveAddress:r,value:c,onChange:d})}),x&&(0,b.jsx)("div",{className:"wallet-alert error",children:x}),f&&(0,b.jsx)("pre",{className:"wallet-json",children:JSON.stringify(f,null,2)}),(0,b.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:"var(--space-2)"},children:[(0,b.jsx)("button",{className:"btn",onClick:n,disabled:p,children:"Cancel"}),(0,b.jsx)("button",{className:"btn btn-primary",onClick:N,disabled:p||!c||j<=0,children:(0,b.jsx)(aN,{busy:p,label:"Confirm collect",busyLabel:"Sweeping…"})})]})]})})}function s5({wallet:e,balances:t,allWallets:a,addressBook:s,onSaveAddress:r,onClose:n,onSuccess:l}){let i=t?.proxy?.pusd_available??0,o=i>.01,[c,d]=(0,_.useState)(o),[u,h]=(0,_.useState)(null),[p,m]=(0,_.useState)(!1),[x,g]=(0,_.useState)("");async function f(){if(g(""),c&&!u)return void g("Pick a sweep destination, or uncheck the sweep option");m(!0);try{let t={};c&&u&&(t.sweep_to=u);let a=await (0,er.authPostJson)(`/api/wallets/${e.id}/archive`,t);if(!a.ok)throw Error(a.error||"Archive failed");await l()}catch(e){g(String(e?.message??e))}finally{m(!1)}}return(0,b.jsx)(s9,{title:`Archive ${e.wallet_name}`,onClose:n,width:520,children:(0,b.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"var(--space-3)"},children:[(0,b.jsxs)("div",{className:"wallet-card-row",children:[(0,b.jsx)("div",{className:"wallet-card-label",children:"Available pUSD"}),(0,b.jsx)("div",{className:`wallet-card-value ${o?"primary":""}`,children:sV(i)})]}),o&&(0,b.jsx)("div",{style:{fontSize:"var(--fs-xs)",color:"var(--fg-muted)"},children:"This wallet still holds pUSD. Sweep it to another wallet before archiving so you don't lose track of it."}),o&&(0,b.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:"var(--space-2)",fontSize:"var(--fs-sm)"},children:[(0,b.jsx)("input",{type:"checkbox",checked:c,onChange:e=>d(e.target.checked)}),"Sweep available pUSD before archiving"]}),c&&(0,b.jsx)(s8,{label:"Sweep destination",children:(0,b.jsx)(sZ,{excludeWalletIds:[e.id],wallets:a,addressBook:s,onSaveAddress:r,value:u,onChange:h})}),(0,b.jsx)("div",{style:{fontSize:"var(--fs-xs)",color:"var(--fg-muted)"},children:'Archived wallets stay in the system (keys preserved) but are hidden from the default view. You can restore them anytime from the "Archived" filter.'}),x&&(0,b.jsx)("div",{className:"wallet-alert error",children:x}),(0,b.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:"var(--space-2)"},children:[(0,b.jsx)("button",{className:"btn",onClick:n,disabled:p,children:"Cancel"}),(0,b.jsx)("button",{className:"btn btn-primary",onClick:f,disabled:p,children:(0,b.jsx)(aN,{busy:p,label:c&&u?"Sweep & archive":"Archive",busyLabel:"Archiving…"})})]})]})})}function s4({entries:e,onClose:t,onReload:a}){let[s,r]=(0,_.useState)(""),[n,l]=(0,_.useState)(""),[i,o]=(0,_.useState)(!1),[c,d]=(0,_.useState)(""),u=/^0x[a-fA-F0-9]{40}$/.test(n);async function h(){if(d(""),!s.trim()||!u)return void d("Label and a valid 0x... address are required");o(!0);try{let e=await (0,er.authPostJson)("/api/wallets/address-book",{label:s.trim(),address:n.trim()});if(!e.ok)throw Error(e.error||"Save failed");r(""),l(""),await a()}catch(e){d(String(e?.message??e))}finally{o(!1)}}async function p(e,t){if(window.confirm(`Remove "${t}" from the address book?`))try{let t=await (0,er.authFetch)(`/api/wallets/address-book/${e}`,{method:"DELETE"});if(!t.ok){let e=await t.text();throw Error(`delete failed (${t.status}): ${e}`)}await a()}catch(e){window.alert(String(e?.message??e))}}return(0,b.jsx)(s9,{title:"Address book",onClose:t,width:560,children:(0,b.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:"var(--space-3)"},children:[(0,b.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr auto",gap:"var(--space-2)",alignItems:"end"},children:[(0,b.jsx)(s8,{label:"Label",children:(0,b.jsx)("input",{type:"text",value:s,onChange:e=>r(e.target.value),placeholder:"e.g. Cold storage"})}),(0,b.jsx)(s8,{label:"Address",children:(0,b.jsx)("input",{type:"text",value:n,onChange:e=>l(e.target.value),placeholder:"0x..."})}),(0,b.jsx)("button",{className:"btn btn-primary btn-sm",onClick:h,disabled:i||!s.trim()||!u,children:(0,b.jsx)(aN,{busy:i,label:"Add",busyLabel:"Saving…"})})]}),c&&(0,b.jsx)("div",{className:"wallet-alert error",children:c}),(0,b.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:0===e.length?(0,b.jsx)("div",{className:"empty-state",style:{padding:"var(--space-3)"},children:'No saved addresses. Add one above, or click "Save" next to any external address you type into a transfer.'}):e.map(e=>(0,b.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",padding:"var(--space-2)",border:"1px solid var(--border-subtle)",borderRadius:6},children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("div",{style:{fontWeight:600},children:e.label}),(0,b.jsx)("div",{style:{fontSize:"var(--fs-xs)",color:"var(--fg-muted)",fontFamily:"var(--font-mono)"},children:e.address})]}),(0,b.jsx)("button",{className:"btn btn-xs",onClick:()=>p(e.id,e.label),children:"Remove"})]},e.id))})]})})}function s3({open:e,onToggle:t,wallets:a}){return(0,b.jsxs)("div",{style:{marginTop:"var(--space-4)"},children:[(0,b.jsxs)("button",{className:"btn",onClick:t,style:{width:"100%",justifyContent:"flex-start",textAlign:"left"},children:[e?"▾":"▸"," Legacy tools (ETH 15m order test + paper deployments)"]}),e&&(0,b.jsx)("div",{style:{marginTop:"var(--space-2)"},children:(0,b.jsx)(s6,{wallets:a})})]})}function s6({wallets:e}
8){let[t,a]=(0,_.useState)(""),[s,r]=(0,_.useState)("limit"),[n,l]=(0,_.useState)("buy"),[i,o]=(0,_.useState)("UP"),[c,d]=(0,_.useState)("0.58"),[u,h]=(0,_.useState)("20"),[p,m]=(0,_.useState)("20"),[x,g]=(0,_.useState)(!1),[f,v]=(0,_.useState)(""),[y,j]=(0,_.useState)(null);async function w(){v(""),j(null),g(!0);try{let e={wallet_id:t,order_type:s,trade_side:n,outcome:i};"limit"===s?(e.price=Number(c),e.size=Number(u),e.ttl_seconds=60):(e.amount=Number(p),e.price_cap=.99);let a=await (0,er.authPostJson)("/api/wallets/eth15m/order",e);if(!a.ok)throw Error(a.error||"Order failed");j(a.data||a)}catch(e){v(String(e?.message??e))}finally{g(!1)}}return(0,_.useEffect)(()=>{!t&&e[0]&&a(e[0].id)},[e,t]),(0,b.jsxs)("div",{className:"card",style:{padding:"var(--space-3)",display:"flex",flexDirection:"column",gap:"var(--space-2)"},children:[(0,b.jsx)("div",{style:{fontWeight:600},children:"ETH 15m order tester (legacy)"}),(0,b.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr 1fr",gap:"var(--space-2)"},children:[(0,b.jsx)(s8,{label:"Wallet",children:(0,b.jsx)("select",{value:t,onChange:e=>a(e.target.value),children:e.map(e=>(0,b.jsx)("option",{value:e.id,children:e.wallet_name},e.id))})}),(0,b.jsx)(s8,{label:"Order type",children:(0,b.jsxs)("select",{value:s,onChange:e=>r(e.target.value),children:[(0,b.jsx)("option",{value:"limit",children:"Limit"}),(0,b.jsx)("option",{value:"market",children:"Market"})]})}),(0,b.jsx)(s8,{label:"Side",children:(0,b.jsxs)("select",{value:n,onChange:e=>l(e.target.value),children:[(0,b.jsx)("option",{value:"buy",children:"Buy"}),(0,b.jsx)("option",{value:"sell",children:"Sell"})]})}),(0,b.jsx)(s8,{label:"Outcome",children:(0,b.jsxs)("select",{value:i,onChange:e=>o(e.target.value),children:[(0,b.jsx)("option",{value:"UP",children:"UP"}),(0,b.jsx)("option",{value:"DOWN",children:"DOWN"})]})})]}),"limit"===s?(0,b.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:"var(--space-2)"},children:[(0,b.jsx)(s8,{label:"Price",children:(0,b.jsx)("input",{type:"text",value:c,onChange:e=>d(e.target.value)})}),(0,b.jsx)(s8,{label:"Size",children:(0,b.jsx)("input",{type:"text",value:u,onChange:e=>h(e.target.value)})})]}):(0,b.jsx)(s8,{label:"Amount",children:(0,b.jsx)("input",{type:"text",value:p,onChange:e=>m(e.target.value)})}),(0,b.jsx)("div",{style:{display:"flex",justifyContent:"flex-end"},children:(0,b.jsx)("button",{className:"btn btn-primary btn-sm",onClick:w,disabled:x||!t,children:x?"Submitting…":"Submit order"})}),f&&(0,b.jsx)("div",{className:"wallet-alert error",children:f}),y&&(0,b.jsx)("pre",{className:"wallet-json",style:{maxHeight:200,overflow:"auto"},children:JSON.stringify(y,null,2)})]})}function s8({label:e,children:t}){return(0,b.jsxs)("div",{children:[(0,b.jsx)("div",{style:{fontSize:"var(--fs-xs)",color:"var(--fg-muted)",marginBottom:4},children:e}),t]})}function s9({title:e,onClose:t,width:a,children:s}){return(0,b.jsx)("div",{style:{position:"fixed",inset:0,background:"rgba(0, 0, 0, 0.7)",backdropFilter:"blur(2px)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e3},onClick:t,children:(0,b.jsxs)("div",{style:{width:a??520,maxHeight:"90vh",overflow:"auto",padding:"var(--space-3)",background:"var(--bg-panel)",border:"1px solid var(--border-default)",borderRadius:"var(--radius-md)",boxShadow:"0 16px 48px rgba(0, 0, 0, 0.5)"},onClick:e=>e.stopPropagation(),children:[(0,b.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"var(--space-2)"},children:[(0,b.jsx)("div",{style:{fontWeight:600},children:e}),(0,b.jsx)("button",{className:"btn btn-xs",onClick:t,children:"Close"})]}),s]})})}var s7=e.i(64435);let re={home:"#4f8cff",draw:"#9aa0a6",away:"#ff7b7b"};function rt({eventId:e,homeTeam:t,awayTeam:a,active:s=!0}){let r=(0,_.useRef)(null),n=(0,_.useRef)(null),l=(0,_.useRef)({}),i=(0,_.useRef)(null),[o,c]=(0,_.useState)(!0),[d,u]=(0,_.useState)(!1);return(0,_.useEffect)(()=>{if(!r.current)return;let e=(0,A.createChart)(r.current,{...(0,T.makeChartOptions)(300),autoSize:!0,handleScroll:!0,handleScale:!0,rightPriceScale:{borderVisible:!1}});["home","draw","away"].forEach(t=>{l.current[t]=e.addSeries(A.LineSeries,{color:re[t],lineWidth:2,priceFormat:{type:"custom",formatter:e=>`${(100*e).toFixed(1)}c`}})}),n.current=e;let t=new ResizeObserver(()=>e.applyOptions({width:r.current.clientWidth}
8));return t.observe(r.current),()=>{t.disconnect(),e.remove(),n.current=null,l.current={},i.current=null}},[]),(0,_.useEffect)(()=>{if(!s)return;let t=!1,a=null,r=async()=>{try{let a=await (0,er.authGetJson)(`/api/worldcup/matches/${e}/odds-history`);if(t||!n.current)return;let s=a.data?.series||{},r=!1;["home","draw","away"].forEach(e=>{let t=(s[e]||[]).map(e=>({time:e.t,value:e.p}));t.length&&(r=!0),l.current[e]?.setData(t)}),u(!r);let o=(a.data?.goals||[]).map(e=>({time:e.t,position:"aboveBar",color:"#f5a623",shape:"circle",text:`⚽ ${e.score}`}));o.length&&l.current.home&&(i.current?i.current.setMarkers(o):i.current=(0,A.createSeriesMarkers)(l.current.home,o)),n.current.timeScale().fitContent()}catch{t||u(!0)}finally{t||(c(!1),a=window.setTimeout(r,3e4))}};return r(),()=>{t=!0,null!=a&&window.clearTimeout(a)}},[s,e]),(0,b.jsxs)("div",{className:"wc-chart",children:[(0,b.jsxs)("div",{className:"wc-chart-legend",children:[(0,b.jsxs)("span",{style:{color:re.home},children:["━ ",t]}),(0,b.jsx)("span",{style:{color:re.draw}
8,children:"━ draw"}),(0,b.jsxs)("span",{style:{color:re.away},children:["━ ",a]}),o?(0,b.jsx)("span",{className:"wc-power-sub",children:" loading…"}):null,d?(0,b.jsx)("span",{className:"wc-power-sub",children:" no price history yet"}):null]}),(0,b.jsx)("div",{ref:r,className:"wc-chart-canvas"})]})}var ra=e.i(69941);let rs="wc_notes_pos",rr="wc_notes_open";function rn({eventId:e,label:t}){let[a,s]=(0,_.useState)(!1),[r,n]=(0,_.useState)(""),[l,i]=(0,_.useState)(!1),[o,c]=(0,_.useState)("idle"),[d,u]=(0,_.useState)(!1),h=(0,_.useRef)(null),[p,m]=(0,_.useState)(!1);(0,_.useEffect)(()=>{let e=h.current;if(!e)return;let t=()=>m(!!e.offsetParent);t();let a=new MutationObserver(t),s=e.parentElement;for(;s&&s!==document.body;)a.observe(s,{attributes:!0,attributeFilter:["style","class"]}),s=s.parentElement;return window.addEventListener("resize",t),()=>{a.disconnect(),window.removeEventListener("resize",t)}},[d]),(0,_.useEffect)(()=>{u(!0);try{s("1"===localStorage.getItem(rr))}catch{}},[]),(0,_.useEffect)(()=>{if(d)try{localStorage.setItem(rr,a?"1":"0")}catch{}},[a,d]),(0,_.useEffect)(()=>{let t=!0;return i(!1),(0,er.authGetJson)(`/api/worldcup/matches/${e}/notes`).then(e=>{t&&(n(e.data?.text||""),i(!0))}).catch(()=>{t&&i(!0)}),()=>{t=!1}},[e]);let x=(0,_.useRef)(null),g=(0,_.useCallback)(t=>{n(t),l&&(c("saving"),x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{(0,er.authPostJson)(`/api/worldcup/matches/${e}/notes`,{text:t}).then(()=>c("saved")).catch(()=>c("idle"))},700))},[e,l]);(0,_.useEffect)(()=>()=>{x.current&&clearTimeout(x.current)},[]);let[f,v]=(0,_.useState)(()=>{try{let e=localStorage.getItem(rs);if(e){let t=JSON.parse(e);if(isFinite(t.x)&&isFinite(t.y))return t}}catch{}return null}),y=(0,_.useRef)(null),j=(0,_.useRef)(null),w=(e,t)=>{let a=window.innerWidth||1200,s=window.innerHeight||800,r=y.current?.offsetWidth||300,n=Math.min(y.current?.offsetHeight||260,Math.round(.7*s));return{x:Math.min(Math.max(8,e),Math.max(8,a-r-8)),y:Math.min(Math.max(8,t),Math.max(8,s-Math.max(n,220)-8))}};(0,_.useEffect)(()=>{let e=()=>v(e=>{if(!e)return e;let t=w(e.x,e.y);if(1>Math.abs(t.x-e.x)&&1>Math.abs(t.y-e.y))return e;try{localStorage.setItem(rs,JSON.stringify(t))}catch{}return t}),t=setTimeout(e,60);return window.addEventListener("resize",e),()=>{clearTimeout(t),window.removeEventListener("resize",e)}},[a]);let N=e=>{let t=y.current;if(!t)return;let a=t.getBoundingClientRect();j.current={sx:e.clientX,sy:e.clientY,ox:a.left,oy:a.top,moved:!1};let s=e=>{let t=j.current;if(!t)return;let a=e.clientX-t.sx,s=e.clientY-t.sy;!t.moved&&5>Math.hypot(a,s)||(t.moved=!0,v(w(t.ox+a,t.oy+s)))},r=()=>{let e=j.current;window.removeEventListener("pointermove",s),window.removeEventListener("pointerup",r),e?.moved&&v(e=>{try{e&&localStorage.setItem(rs,JSON.stringify(e))}catch{}return e}),setTimeout(()=>{j.current=null},0)};window.addEventListener("pointermove",s),window.addEventListener("pointerup",r)},k=(0,b.jsx)("span",{ref:h,"aria-hidden":!0,style:{width:0,height:0,display:"inline-block"}});if(!d||!p)return k;let S={position:"fixed",zIndex:59,fontSize:12.5,...f?{left:f.x,top:f.y}:{right:18,bottom:96}};return(0,b.jsxs)(b.Fragment,{children:[k,(0,ra.createPortal)((0,b.jsx)("div",{ref:y,style:S,children:a?(0,b.jsxs)("div",{style:{width:300,borderRadius:10,overflow:"hidden",border:"1px solid rgba(224,180,90,0.45)",background:"rgba(32,28,18,0.97)",boxShadow:"0 10px 34px rgba(0,0,0,0.5)",backdropFilter:"blur(8px)"},children:[(0,b.jsxs)("div",{onPointerDown:N,title:"drag to move — position is remembered",style:{touchAction:"none",cursor:"grab",display:"flex",alignItems:"center",gap:8,padding:"7px 10px",background:"rgba(224,180,90,0.16)",borderBottom:"1px solid rgba(224,180,90,0.28)"},children:[(0,b.jsx)("b",{style:{color:"#E8D9A8"},children:"📝 Notes"}),(0,b.jsx)("span",{style:{flex:1,minWidth:0,opacity:.6,fontSize:11,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t||""}),(0,b.jsx)("span",{style:{fontSize:10.5,opacity:.75,minWidth:38,textAlign:"right"},children:"saving"===o?"saving…":"saved"===o?"saved ✓":""}),(0,b.jsx)("button",{onPointerDown:e=>e.stopPropagation(),onClick:()=>s(!1),style:{background:"transparent",border:"none",color:"#E8D9A8",cursor:"pointer",fontSize:15,lineHeight:1,padding:"0 2px"},title:"minimise",children:"—"})]}),(0,b.jsx)("textarea",{value:r,onChange:e=>g(e.target.value),onPointerDown:e=>e.stopPropagation(),placeholder:l?"Your read on this match — entries, levels, what to watch…":"loading…",spellCheck:!1,style:{width:"100%",height:190,resize:"vertical",boxSizing:"border-box",padding:"9px 10px",border:"none",outline:"none",background:"transparent",color:"#EDE6D2",fontSize:12.5,lineHeight:1.5,fontFamily:"inherit"}})]}):(0,b.jsxs)("button",{onPointerDown:N,onClick:()=>{j.current?.moved||s(!0)},title:"Your notes for this match — drag to move",style:{touchAction:"none",cursor:"grab",border:"1px solid rgba(224,180,90,0.5)",background:"rgba(224,180,90,0.16)",color:"#E8D9A8",borderRadius:999,padding:"7px 13px",fontSize:12.5,fontWeight:600,backdropFilter:"blur(6px)"},children:["📝 Notes",r.trim()?" •":""]})}),document.body)]})}let rl="https://api.sofascore.com/api/v1",ri=new Set(["fc","cf","sc","afc","ac","as","us","ss","sv","if","ik","bk","sk","cd","club","calcio","sport","sports","de","the"]);function ro(e){let t=(e||"").toLowerCase().normalize("NFD").replace(/[̀-ͯ]/g,"").replace(/[^a-z0-9]+/g," ").trim().split(/\s+/),a=new Set;for(let e of t)!e||ri.has(e)||a.add(e.length>4&&e.endsWith("s")?e.slice(0,-1):e);return a}function rc(e,t){let a=ro(e),s=ro(t);if(!a.size||!s.size)return 0;let r=0;
8return a.forEach(e=>{s.has(e)&&r++}),r/Math.min(a.size,s.size)}function rd({eventId:e,home:t,away:a,kickoffMs:s,active:r=!0}){let[n,l]=(0,_.useState)(null),[i,o]=(0,_.useState)(!1),[c,d]=(0,_.useState)(""),[u,h]=(0,_.useState)("momentum"),[p,m]=(0,_.useState)(null),[x,g]=(0,_.useState)(null),[f,v]=(0,_.useState)(null),y=(0,_.useRef)(""),j=(0,_.useCallback)(async()=>{let e=[];for(let s of[t,a]){try{let t=await fetch(`${rl}/search/all?q=${encodeURIComponent(s)}&page=0`).then(e=>e.json());e.push(...(t.results||[]).filter(e=>"team"===e.type&&e.entity?.id))}catch{}if(e.length)break}let r=null;for(let n of e.slice(0,4)){for(let e of["last","next"]){let l=[];try{l=(await fetch(`${rl}/team/${n.entity.id}/events/${e}/0`).then(e=>e.json())).events||[]}catch{}for(let e of l){let n=e.homeTeam?.name||"",l=e.awayTeam?.name||"",i=Math.max(Math.min(rc(t,n),rc(a,l)),Math.min(rc(t,l),rc(a,n))-.01);if(!(i<.5)){if(s&&Math.abs(1e3*(e.startTimestamp||0)-s)>1296e5)continue;(!r||i>r.conf)&&(r={id:e.id,conf:i,label:`${n} v ${l}`})}}}if(r&&r.conf>=.99)break}return r?{sofa_id:r.id,confidence:r.conf,matched:r.label}:{sofa_id:null,confidence:0,matched:null}},[t,a,s]),w=(0,_.useCallback)(async(t=!1)=>{o(!0),d("");try{if(!t){let t=(await (0,er.authGetJson)(`/api/worldcup/matches/${e}/sofascore`)).data;if(t?.sofa_id){l(t),o(!1);return}if(t?.resolved_ms&&Date.now()-t.resolved_ms<36e5){l({sofa_id:null}),o(!1);return}}let a=await j();l(a),(0,er.authPostJson)(`/api/worldcup/matches/${e}/sofascore`,a).catch(()=>{})}catch(e){d("couldn't reach SofaScore from this browser")}finally{o(!1)}},[e,j]);(0,_.useEffect)(()=>{r&&(l(null),m(null),g(null),y.current="",w())},[r,w]);let N=n?.sofa_id,k=(0,_.useCallback)(async t=>{let a=async e=>{try{return await fetch(`${rl}/event/${t}/${e}`).then(e=>e.ok?e.json():null)}catch{return null}},[s,r,n,l]=await Promise.all([(async()=>{try{return await fetch(`${rl}/event/${t}`).then(e=>e.ok?e.json():null)}catch{return null}})(),a("statistics"),a("shotmap"),a("graph")]),i={},o=[],c=(r?.statistics||[]).find(e=>"ALL"===e.period)||(r?.statistics||[])[0];for(let e of c?.groups||[]){let t=[];for(let a of e.statisticsItems||[]){if(!a?.name)continue;let e={name:a.name,home:String(a.home??""),away:String(a.away??"")};i[a.name]={home:e.home,away:e.away},t.push(e)}t.length&&o.push({group:String(e.groupName||"Other"),items:t})}o.length&&v(o);let d=(n?.shotmap||[]).map(e=>({minute:(e.time||0)+(e.addedTime||0),home:!!e.isHome,xg:e.xg,xgot:e.xgot,type:e.shotType,situation:e.situation,body:e.bodyPart,player:e.player?.shortName||e.player?.name||""})).sort((e,t)=>e.minute-t.minute),u=(l?.graphPoints||[]).map(e=>({minute:e.minute,value:e.value})),h=s?.event?.status?.type||"";if(Object.keys(i).length&&g(i),!Object.keys(i).length&&!d.length&&!u.length)return{status:h,saved:!1,empty:!0};let p=`${h}:${Object.keys(i).length}:${d.length}:${u.length}`;if(p===y.current)return{status:h,unchanged:!0};y.current=p;let m=u.length?u[u.length-1].minute:null,x=await (0,er.authPostJson)(`/api/worldcup/matches/${e}/sofascore/stats`,{sofa_id:t,status:h,minute:m,stats:i,shots:d,momentum:u});return{status:h,...x?.data||{}}},[e]);(0,_.useEffect)(()=>{if(!r||!N)return;let e=!0,t,a=async()=>{let s=await k(N);if(!e)return;s&&!s.unchanged&&m(s);let r=s?.status==="inprogress"?6e4:s?.status==="notstarted"?3e5:3e5*!!s?.empty;r&&(t=setTimeout(a,r))};return a(),()=>{e=!1,clearTimeout(t)}},[r,N,k]);let S=p?.status==="notstarted",$=`https://widgets.sofascore.com/en-US/embed/attackMomentum?id=${N}&widgetTheme=dark`;return(0,b.jsxs)("div",{className:"radar-section",children:[(0,b.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,b.jsx)("div",{className:"radar-section-title",style:{margin:0},children:"📊 Match Momentum & Stats"}),(0,b.jsx)("span",{className:"wc-power-sub",children:"· SofaScore"}),N&&!S&&(0,b.jsxs)("div",{className:"wc-bot-tabs",children:[(0,b.jsx)("button",{className:"momentum"===u?"on":"",onClick:()=>h("momentum"),children:"Momentum"}),(0,b.jsx)("button",{className:"stats"===u?"on":"",onClick:()=>h("stats"),children:"Statistics"})]}),(0,b.jsx)("span",{style:{flex:1}}),!i&&(0,b.jsx)("button",{className:"wc-scout-refresh",onClick:()=>w(!0),title:"Re-run the lookup against SofaScore",children:"↻ re-link"})]}),i&&(0,b.jsx)("div",{className:"radar-section-note",children:"Linking this match to SofaScore…"}),!i&&c&&(0,b.jsx)("div",{className:"radar-section-note",children:c}),!i&&!c&&!N&&(0,b.jsx)("div",{className:"radar-section-note",children:"No SofaScore fixture matched this match yet. It usually appears closer to kickoff — hit ↻ re-link then."}),N&&(0,b.jsxs)(b.Fragment,{children:[!S&&"momentum"===u&&(0,b.jsx)("iframe",{src:$,title:"SofaScore attack momentum",style:{width:"100%",height:320,border:"none",borderRadius:8,marginTop:8,background:"transparent"},loading:"lazy",referrerPolicy:"no-referrer-when-downgrade"},`${N}-momentum`),!S&&"stats"===u&&(f?.length?(0,b.jsx)("div",{className:"sofa-stats",children:f.map(e=>(0,b.jsxs)("section",{className:"sofa-group",children:[(0,b.jsx)("div",{className:"sofa-group-h",children:e.group}),e.items.map(e=>{var t,a;let s,r,n=(t=e.home,a=e.away,s=parseFloat(String(t).replace(/[^\d.]/g,"")),r=parseFloat(String(a).replace(/[^\d.]/g,"")),isFinite(s)&&isFinite(r)&&!(s+r<=0)?[s/(s+r)*100,r/(s+r)*100]:null),l=n?n[0]>n[1]?"h":n[1]>n[0]?"a":"":"";return(0,b.jsxs)("div",{className:"sofa-row",children:[(0,b.jsx)("span",{className:`s
8ofa-v${"h"===l?" lead":""}`,children:e.home}),(0,b.jsx)("span",{className:"sofa-n",children:e.name}),(0,b.jsx)("span",{className:`sofa-v${"a"===l?" lead":""}`,children:e.away}),n&&(0,b.jsxs)("div",{className:"sofa-bars",children:[(0,b.jsx)("div",{className:"sofa-bar l",children:(0,b.jsx)("i",{style:{width:`${n[0]}%`}})}),(0,b.jsx)("div",{className:"sofa-bar r",children:(0,b.jsx)("i",{style:{width:`${n[1]}%`}})})]})]},e.name)})]},e.group))}):(0,b.jsx)("div",{className:"radar-section-note",children:"Statistics appear once the match is under way."})),(0,b.jsxs)("div",{className:"radar-section-note wc-power-sub",children:["Linked to “",n?.matched||"this fixture","” on SofaScore",n?.confidence!=null?` (${Math.round(100*n.confidence)}% name match)`:"",S?".":". Momentum spikes = attacking intensity; the Statistics tab carries xG, big chances and shot splits."]}),p?.saved&&(0,b.jsxs)("div",{className:"radar-section-note wc-power-sub",children:["✓ Captured to our database: ",p.stats," stats · ",p.shots," shots with xG · ",p.momentum," momentum points","inprogress"===p.status?" — refreshing every minute while live.":"."," ","Your browser can read SofaScore even though our server can’t, so these numbers are now the model’s to use."]}),p?.empty&&(0,b.jsx)("div",{className:"radar-section-note wc-power-sub",children:"notstarted"===p.status?"⏳ Not kicked off yet — SofaScore publishes no stats, shots or momentum until a match starts. The momentum chart and the stat panel appear here the moment it does, and the numbers start flowing into our database at the same time. Checking back every 5 minutes.":"SofaScore hasn’t published stats for this match yet. Retrying every 5 minutes."})]})]})}let ru=e=>null==e?"—":`${(100*e).toFixed(1)}c`,rh=e=>`$${Number(e||0).toLocaleString(void 0,{maximumFractionDigits:0})}`,rp=e=>{if(null==e)return"—";let t=Math.abs(e),a=t>=1e6?`$${(t/1e6).toFixed(1)}M`:t>=1e3?`$${(t/1e3).toFixed(1)}k`:`$${Math.round(t)}`;return e<0?`-${a}`:a};function rm(e){return e?new Date(e).toLocaleString(void 0,{weekday:"short",month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}):"TBD"}function rx(e,t){return null==e||null==t?null:(e-t)*100}function rg({m:e}){let t=e.prices?.home??0,a=e.prices?.draw??0,s=e.prices?.away??0,r=t+a+s||1;return(0,b.jsxs)("div",{className:"wc-3way",title:`${e.home_team} ${ru(t)} \xb7 draw ${ru(a)} \xb7 ${e.away_team} ${ru(s)}`,children:[(0,b.jsx)("div",{className:"wc-3way-seg home",style:{width:`${t/r*100}%`}}),(0,b.jsx)("div",{className:"wc-3way-seg draw",style:{width:`${a/r*100}%`}}),(0,b.jsx)("div",{className:"wc-3way-seg away",style:{width:`${s/r*100}%`}})]})}let rf=e=>e&&e.n?`${e.pct}% (${e.w}/${e.n})`:"—";function rb(){let[e,t]=(0,_.useState)([]),[a,s]=(0,_.useState)(!0),[r,n]=(0,_.useState)("production"),[l,i]=(0,_.useState)(null),[o,c]=(0,_.useState)({}),[d,u]=(0,_.useState)(10),[h,p]=(0,_.useState)(null),[m,x]=(0,_.useState)({name:"",system_prompt:""}),[g,f]=(0,_.useState)(!1),v=()=>(0,er.authGetJson)("/api/worldcup/strategies").then(e=>t(e.data?.strategies||[])).catch(()=>{});(0,_.useEffect)(()=>{v().finally(()=>s(!1))},[]);let y=e.find(e=>"production"===e.id)?.system_prompt||"",j=o.production?.per_match?.length||26,w=e=>{c(t=>({...t,[e]:{...t[e]||{},status:"running",progress:{done:0,total:j}}})),(0,er.authPostJson)(`/api/worldcup/strategies/${e}/backtest?step=${d}`,{}).then(t=>c(a=>({...a,[e]:t.data}))).catch(()=>{})};(0,_.useEffect)(()=>{a||!e.length||o.production||w("production")},[a,e]),(0,_.useEffect)(()=>{let e=Object.entries(o).filter(([,e])=>e?.status==="running").map(([e])=>e).filter(e=>"production"!==e);if(!e.length)return;let t=window.setInterval(()=>{e.forEach(e=>(0,er.authGetJson)(`/api/worldcup/strategies/${e}/backtest`).then(t=>c(a=>({...a,[e]:t.data}))).catch(()=>{}))},3e3);return()=>window.clearInterval(t)},[o]);let N=Math.floor(90/d),k=j*N,S=Math.max(1,Math.round(k/6*7/60));return a?(0,b.jsx)("div",{className:"empty-state",children:"Loading strategies…"}):(0,b.jsxs)("div",{className:"wc-lab",children:[(0,b.jsxs)("div",{className:"wc-lab-intro",children:["Each strategy is a prompt for the in-play signal engine. ",(0,b.jsx)("strong",{children:"#1 is the live production strategy."})," Clone it, tweak the prompt, pick a granularity, and ",(0,b.jsx)("strong",{children:"replay it over the stored matches"})," (narration + per-minute momentum) to measure before going live. Winrate is hit rate, deduped to distinct calls; over/under ROI awaits the price-stamped data now being captured."]}
8),(0,b.jsxs)("div",{className:"wc-lab-controls",children:[(0,b.jsx)("button",{className:"wc-scout-run",onClick:()=>{p("new"),x({name:"",system_prompt:y})},children:"+ new strategy (clone production)"}),(0,b.jsxs)("label",{className:"wc-lab-gran",children:["granularity: ",(0,b.jsxs)("b",{children:["every ",d," min"]})," ",(0,b.jsxs)("span",{className:"wc-power-sub",children:["(",N," reads/match · ≈",k," LLM calls · ~",S," min",d<=2?" ⚠️ heavy":"",")"]}),(0,b.jsx)("input",{type:"range",min:1,max:15,value:d,onChange:e=>u(parseInt(e.target.value))})]})]}),h&&(0,b.jsxs)("div",{className:"wc-strat-editor",children:[(0,b.jsx)("input",{className:"wc-strat-nameinput",placeholder:"strategy name (e.g. no-play in cagey games)",value:m.name,onChange:e=>x(t=>({...t,name:e.target.value}))}),(0,b.jsx)("textarea",{className:"wc-strat-promptedit",value:m.system_prompt,onChange:e=>x(t=>({...t,system_prompt:e.target.value})),rows:14,spellCheck:!1}),(0,b.jsxs)("div",{className:"wc-strat-actions",children:[(0,b.jsx)("button",{className:"wc-scout-run",onClick:()=>{m.name.trim()&&m.system_prompt.trim()&&(f(!0),(0,er.authPostJson)("/api/worldcup/strategies",{id:"new"===h?void 0:h,name:m.name,system_prompt:m.system_prompt}).then(()=>(p(null),v())).finally(()=>f(!1)))},disabled:g,children:g?"saving…":"save strategy"}),(0,b.jsx)("button",{className:"wc-strat-link",onClick:()=>p(null),children:"cancel"})]})]}),e.map((e,t)=>{let a=o[e.id],s=r===e.id,u=a?.status==="running"?a.progress:null;return(0,b.jsxs)("div",{className:`wc-strat${e.builtin?" builtin":""}`,children:[(0,b.jsxs)("div",{className:"wc-strat-head",onClick:()=>n(s?null:e.id),children:[(0,b.jsxs)("span",{className:"wc-strat-rank",children:["#",t+1]}),(0,b.jsx)("span",{className:"wc-strat-name",children:e.name}),e.builtin?(0,b.jsx)("span",{className:"wc-strat-badge",children:"live"}):null,(0,b.jsx)("span",{className:"wc-strat-wr",children:a?.status==="running"?(0,b.jsxs)("span",{className:"wc-power-sub",children:["running ",u?`${u.done}/${u.total}`:"…"]}):a?.winrate_ex_under?.n?(0,b.jsxs)(b.Fragment,{children:["ex-under ",(0,b.jsx)("b",{children:rf(a.winrate_ex_under)})," · all ",rf(a.winrate)]}):e.backtest?.winrate_ex_under?.n?(0,b.jsxs)(b.Fragment,{children:["ex-under ",(0,b.jsx)("b",{children:rf(e.backtest.winrate_ex_under)})]}):(0,b.jsx)("span",{className:"wc-power-sub",children:"not backtested"})}),(0,b.jsx)("span",{className:"wc-strat-caret",children:s?"▾":"▸"})]}),s&&(0,b.jsxs)("div",{className:"wc-strat-body",children:[(0,b.jsx)("div",{className:"wc-strat-desc",children:e.description}),(0,b.jsx)("div",{className:"wc-strat-rules",children:e.rules}),(0,b.jsxs)("div",{className:"wc-strat-actions",children:[(0,b.jsx)("button",{className:"wc-scout-run",onClick:()=>w(e.id),disabled:a?.status==="running",children:a?.status==="running"?"running…":a?.winrate?"↻ re-run backtest":e.builtin?"▶ run backtest":`▶ backtest (every ${d}m)`}),(0,b.jsx)("button",{className:"wc-strat-link",onClick:()=>i(l===e.id?null:e.id),children:l===e.id?"hide prompt":"view prompt"}),!e.builtin&&(0,b.jsx)("button",{className:"wc-strat-link",onClick:()=>{p(e.id),x({name:e.name,system_prompt:e.system_prompt})},children:"edit"}),!e.builtin&&(0,b.jsx)("button",{className:"wc-strat-link wc-strat-del",onClick:()=>{var t;return t=e.id,void(0,er.authFetch)(`/api/worldcup/strategies/${t}`,{method:"DELETE"}).then(()=>{c(e=>{let a={...e};return delete a[t],a}),v()}).catch(()=>{})},children:"delete"})]}),u&&(0,b.jsx)("div",{className:"wc-strat-prog",children:(0,b.jsx)("div",{className:"wc-strat-progbar",style:{width:`${u.total?u.done/u.total*100:5}%`}})}),l===e.id&&(0,b.jsx)("pre",{className:"wc-strat-prompt",children:e.system_prompt}),a&&a.winrate&&(0,b.jsxs)("div",{className:"wc-strat-results",children:[(0,b.jsxs)("div",{className:"wc-strat-metrics",children:[(0,b.jsxs)("span",{children:["distinct calls ",(0,b.jsx)("b",{children:a.distinct_calls})]}),(0,b.jsxs)("span",{children:["winrate (all) ",(0,b.jsx)("b",{children:rf(a.winrate)})]}),(0,b.jsxs)("span",{children:["winrate (ex-under) ",(0,b.jsx)("b",{className:"radar-up",children:rf(a.winrate_ex_under)})]}),a.step?(0,b.jsxs)("span",{className:"wc-power-sub",children:["every ",a.step,"m"]}):null]}),(0,b.jsx)("div",{className:"wc-strat-bytype",children:Object.entries(a.by_type||{}).map(([e,t])=>(0,b.jsxs)("span",{className:"wc-strat-chip",children:[e.replace("back_",""),": ",(0,b.jsx)("b",{className:(t.pct??0)>=55?"radar-up":"radar-down",children:rf(t)})]},e))}),(0,b.jsx)("div",{className:"wc-strat-bytype",children:Object.entries(a.by_confidence||{}).map(([e,t])=>(0,b.jsxs)("span",{className:"wc-strat-chip",children:["conf ",e,": ",(0,b.jsx)("b",{className:(t.pct??0)>=55?"radar-up":"radar-down",children:rf(t)})]},e))}),a.note?(0,b.jsx)("div",{className:"wc-power-sub",children:a.note}):null,(a.per_match||[]).length>0&&(0,b.jsxs)("details",{className:"wc-strat-permatch",children:[(0,b.jsxs)("summary",{children:["per-match (",(a.per_match||[]).length,") — over + favorite calls"]}),(a.per_match||[]).map((e,t)=>(0,b.jsxs)("div",{className:"wc-strat-pm",children:[(0,b.jsxs)("span",{className:e.pct>=50?"radar-up":"radar-down",children:[e.pct,"%"]}),(0,b.jsxs)("span",{className:"wc-power-sub",children:[" (",e.w,"/",e.n,")"]})," ",e.match]},t))]})]})]})]},e.id)})]})}let r_=e=>{let t=e.period||"";if(t.startsWith("no:"))return`NO ${r_({...e,period:t.slice(3)})}`;if(t.startsWith("ml:"))return"ml:draw"===t?"ML Draw":"ml:home"===t?"ML Home":"ML Away";if(t.startsWith("exact:"))return`Exact ${t.slice(6)}`;if(t.startsWith("spread:")){let[,e,a]=t.split(":");return`${"home"===e?"Home":"Away"} by ${Math.ceil(Number(a))}+`}if(t.startsWith("tt:")){let[,e,a]=t.split(":");return`${"home"===e?"Home":"Away"} O${a}`}if("btts:yes"===t)return"Both score";if("btts:no"===t)return"Both score — NO";if(t.startsWith("updown:")){let[,e,a,s]=t.split(":");return`${e} ${"Up"===a?"▲ Up":"Down"===a?"▼ Down":a} ${s||"15m"}`}return"book"===t?"book":t.startsWith("over:")?`O${t.slice(5)}`:t.startsWith("under:")?`U${t.slice(6)}`:`${"h1"===t?"1H ":"h2"===t?"2H ":""}O${e.line}`},rv=(e,t)=>
8{let a=r_(e);return e.period?.startsWith("ml:")&&["favorite_no_fade","first_goal_no_fomo","first_goal_no_risk","us391_ml_paper","rollobravado_moneyline_copy"].includes(t||"")?a.replace(/^ML /,"NO "):a},ry=e=>e?`${new Date(e).toISOString().slice(11,16)}Z`:"—",rj=(e,t=0)=>`${(e||0)>=0?"+":"−"}$${Math.abs(e||0).toFixed(t)}`,rw={strategy:"style_inventory_rust",strategy_version:"inventory-rust-spread25-recycler-v1",min_edge:0,bankroll_usd:0,kelly_fraction:0,per_match_cap_usd:0,per_leg_cap_usd:0,max_legs:2,daily_max_loss_usd:0,dca_min_improve:0,min_confidence:"model"},rN=[{key:"over05_cap_schedule",label:"Entry cap mode",help:"flat = one price ceiling all match (legacy). stepped = pay up to 85¢ before 30', 75¢ to 45', 65¢ to 60', 55¢ to 70', never open after 70' — 10 months of real-print backtests, stressed +8-14% vs flat's breakeven-to-negative.",kind:"text",placeholder:"flat | stepped"},{key:"over05_match_cap_usd",label:"Per-match exposure cap",help:"Maximum deployed into O0.5 for one match.",min:1,max:1e6,step:25},{key:"over05_max_tranches",label:"Maximum tranches",help:"Number of scheduled entries the match cap divides into.",min:1,max:20,step:1},{key:"over05_first_tranche_mult",label:"First-buy multiplier",help:"The opening buy is this many times the base tranche; later buys stay at base. Front-loading captures fast winners — backtested +36% profit at −0.5pt ROI at 2x.",min:1,max:4,step:.5},{key:"over05_max_matches",label:"Concurrent match cap",help:"Maximum matches with open GoalPilot positions; 0 means unlimited.",min:0,max:100,step:1},{key:"daily_max_loss_usd",label:"Daily/session loss stop",help:"Pauses new entries after this loss; 0 disables it.",min:0,max:1e6,step:50},{key:"over05_max_price",label:"Token price ceiling",help:"Never buy O0.5 above this price.",min:1,max:99,step:1,scale:100},{key:"over05_trap_price",label:"Cagey-league ceiling",help:"Stricter ceiling for leagues on the cagey list (0-0 up to twice as likely). Never above the normal ceiling.",min:1,max:99,step:1,scale:100},{key:"over05_open_price",label:"Goal-happy league ceiling",help:"Looser ceiling for leagues on the goal-happy list. Never below the normal ceiling.",min:1,max:99,step:1,scale:100},{key:"over05_execution",label:"Execution",help:"maker = rest limit bids below the ask (no taker fee, no chase; may miss fills). taker = cross the spread immediately. Flip takes effect within one 10s scan.",kind:"text",placeholder:"maker | taker"},{key:"over05_trap_leagues",label:"Cagey leagues",help:"Comma-separated league codes that use the cagey ceiling.",kind:"text",placeholder:"arg,esp2,ita,…"},{key:"over05_open_leagues",label:"Goal-happy leagues",help:"Comma-separated league codes that use the goal-happy ceiling.",kind:"text",placeholder:"nor,bun,ere,…"},{key:"over05_max_spread",label:"Maximum spread",help:"Reject wider two-sided books.",min:0,max:50,step:.5,scale:100},{key:"over05_max_chase",label:"Depth chase",help:"Maximum walk above the current best ask.",min:0,max:10,step:.5,scale:100},{key:"over05_start_minute",label:"First entry minute",help:"First eligible checkpoint in a 0-0 match.",min:1,max:90,step:1},{key:"over05_end_minute",label:"Last entry minute",help:"No new GoalPilot buys after this match minute.",min:1,max:90,step:1},{key:"over05_cadence_minutes",label:"Checkpoint cadence",help:"Minutes between scheduled entry windows.",min:1,max:30,step:1},{key:"over05_min_add_match_gap_minutes",label:"Match-time add gap",help:"Minimum match minutes between same-market tranches.",min:1,max:90,step:1},{key:"over05_min_add_wall_gap_minutes",label:"Wall-clock add gap",help:"Minimum real minutes between same-market tranches.",min:1,max:120,step:1},{key:"over05_min_add_improve",label:"Required better ask",help:"Later tranches require this much price improvement.",min:0,max:10,step:.5,scale:100}],rk=[{key:"late_tail_min_minute",label:"Earliest entry minute",help:"Nothing before this. 70′ is what the research validated; 75′ tested better per dollar but halves the number of trades.",min:45,max:89,step:1},{key:"late_tail_max_minute",label:"Latest entry minute",help:"Past this the book is too thin for the price to mean anything.",min:46,max:90,step:1},{key:"late_tail_min_goals",label:"Goals already scored",help:"Below this the rule stays out. At one goal the chasing team genuinely opens up and the market is right.",min:0,max:6,step:1},{key:"late_tail_price_lo",label:"Cheapest ask taken",help:"Also a junk filter: a frontier under quoting 1¢ in a 2-goal game is a stale book, not a bargain.",min:1,max:99,step:1,scale:100},{key:"late_tail_price_hi",label:"Dearest ask taken",help:"Above this the market has already priced the quiet finish.",min:1,max:99,step:1,scale:100},{key:"late_tail_dead_line_max",label:"Score-confirmation ceiling",help:"The line below the frontier must be this dead, or our goal count is wrong and the entry is garbage.",min:1,max:50,step:1,scale:100},{key:"late_tail_stake_usd",label:"Stake per match",help:"Flat paper stake. One position per match, ever.",min:1,max:1e5,step:25},{key:"late_tail_max_matches",label:"Concurrent match cap",help:"Maximum live matches scanned per pass.",min:1,max:100,step:1}],rS=[{key:"key_sub_min_minute",label:"Earliest substitution",help:"The validated window begins at 55′.",min:45,max:89,step:1},{key:"key_sub_max_minute",label:"Latest substitution",help:"Cross-year validation drops sharply after 64′; the default ends there.",min:46,max:90,step:1},{key:"key_sub_max_price",label:"Maximum O0.5 ask",help:"Do not paper-buy after the market has already priced most of the late-goal probability.",min:1,max:99,step:1,scale:100},{key:"key_sub_max_spread",label:"Maximum spread",help:"Reject unreliable or expensive two-sided books.",min:0,max:50,step:.5,scale:100},{key:"key_sub_max_chase",label:"Depth chase",help:"Maximum walk above the displayed best ask while simulating the fill.",min:0,max:10,step:.5,scale:100},{key:"key_sub_stake_usd",label:"Paper stake",help:"Maximum all-in paper cost for the one allowed entry per match.",min:1,max:1e5,step:25},{key:"key_sub_min_fill_usd",label:"Minimum real depth",help:"Requires at least this much executable O0.5 depth inside the price ceiling.",min:1,max:1e5,step:5},{key:"key_sub_max_signal_age_minutes",label:"Substitution freshness",help:"How many match minutes the agent may act after the substitution appears in the feed.",min:0,max:10,step:1},{key:"key_sub_history_matches",label:"Prior matches profiled",help:"Maximum prior tracked club matches used to identify a key player.",min:3,max:30,step:1},{key:"key_sub_min_appearances",label:"Minimum appearances",help:"Player must have this many prior tracked appearances before any importance rule can qualify.",min:1,max:20,step:1},{key:"key_sub_min_start_rate",label:"Start-rate threshold",help:"One of three alternative key-player tests.",min:0,max:100,step:5,scale:100},{key:"key_sub_min_recent_start_rate",label:"Recent start threshold",help:"Recent-eight alternative key-player test.",min:0,max:100,step:5,scale:100},{key:"key_sub_min_contrib_rate",label:"G+A per appearance",help:"Goal-plus-assist rate alternative key-player test.",min:0,max:200,step:5,scale:100}],r$=[{key:"ml_no_stake_usd",label:"Paper stake",help:"Maximum fee-inclusive cost for the one direct favorite-NO entry.",min:1,max:1e4,step:10},{key:"ml_no_match_cap_usd",label:"Match cap",help:"Hard paper exposure cap for the match.",min:1,max:1e4,step:10},{key:"ml_no_min_favorite",label:"Minimum favorite",help:"Observable 0-0 favorite price before the first goal.",min:34,max:94,step:1,scale:100},{key:"ml_no_max_favorite",label:"Maximum favorite",help:"Upper boundary is exclusive; stronger favorites failed the execution-aligned audit.",min:35,max:95,step:1,scale:100},{key:"ml_no_min_price",label:"Minimum NO ask",help:"Do not extrapolate below the validated direct-NO entry band.",min:1,max:98,step:1,scale:100},{key:"ml_no_max_price",label:"Maximum NO ask",help:"Upper boundary is exclusive; do not pay beyond the tested band.",min:2,max:99,step:1,scale:100},{key:"ml_no_max_spread",label:"Maximum spread",help:"Requires an executable two-sided direct-NO book.",min:0,max:25,step:.5,scale:100},{key:"ml_no_min_ask_shares",label:"Minimum top ask",help:"Minimum shares available at the displayed best ask.",min:0,max:1e5,step:25},{key:"ml_no_goal_age_minutes",label:"Trailing confirmation",help:"Favorite must remain exactly one goal behind for this long after conceding first.",min:1,max:20,step:1},{key:"ml_no_live_end_minute",label:"Live cutoff",help:"No entry after the validated first-half window.",min:5,max:60,step:1},{key:"ml_no_blocked_leagues",label:"Excluded leagues",help:"Comma-separated league codes excluded by the holdout audit.",kind:"text",placeholder:"clf,lec"}],rC=[{key:"fomo_no_stake_usd",label:"Paper stake",help:"Fixed fee-inclusive paper cost per qualifying match. The deployed paper cohort is configured at $400; roughly seven of ten settle as losses.",min:1,max:1e3,step:5},{key:"fomo_no_min_minute",label:"Earliest first goal",help:"The audited first-goal window begins at 10′.",min:1,max:44,step:1},{key:"fomo_no_max_minute",label:"Latest first goal",help:"The audited first-goal window ends at 29′.",min:2,max:60,step:1},{key:"fomo_no_min_goal_age_seconds",label:"Minimum reaction delay",help:"Wait for the emotional goal repricing to settle before measuring the direct-NO ask.",min:0,max:600,step:10}
8,{key:"fomo_no_max_goal_age_seconds",label:"Maximum reaction delay",help:"Five-minute entries lost the recent holdout edge; the default stops at four minutes.",min:1,max:900,step:10},{key:"fomo_no_min_price",label:"Minimum direct-NO ask",help:"Lower prices were a different, much less stable lottery regime.",min:1,max:98,step:1,scale:100},{key:"fomo_no_max_price",label:"Maximum direct-NO ask",help:"The validated sentiment band ends at 25¢.",min:2,max:99,step:1,scale:100},{key:"fomo_no_min_compression",label:"Minimum goal compression",help:"Direct NO must fall at least this much from its pre-goal mark.",min:0,max:95,step:1,scale:100},{key:"fomo_no_max_compression",label:"Maximum goal compression",help:"More extreme collapses behaved like legitimate decisive repricing, not a repeatable fade.",min:1,max:99,step:1,scale:100},{key:"fomo_no_max_spread",label:"Maximum spread",help:"Forward-only executable-book guard; historical depth was unavailable.",min:0,max:25,step:.5,scale:100},{key:"fomo_no_min_fill_usd",label:"Minimum executable fill",help:"Reject paper fills without this much real ask depth inside the price ceiling.",min:1,max:1e3,step:5},{key:"fomo_no_recovery_window_seconds",label:"Principal recovery window",help:"Sell only enough shares to recover principal if the direct-NO bid rebounds inside this window.",min:0,max:1800,step:30},{key:"fomo_no_recovery_multiple",label:"Recovery multiple",help:"One of the two bid targets; the larger of this multiple and the absolute jump is used.",min:1.05,max:10,step:.05},{key:"fomo_no_recovery_jump",label:"Recovery price jump",help:"Absolute direct-NO rebound required when it is larger than the multiple target.",min:1,max:50,step:1,scale:100}],rM=[...rC.map(e=>"fomo_no_recovery_window_seconds"===e.key?{...e,label:"Active exit window",help:"For five minutes after entry, the router may take the full target or half-price stop; afterward it holds to settlement."}:"fomo_no_recovery_multiple"===e.key?{...e,label:"Full-exit target multiple",help:"Fully exits when the best complete route reaches the larger of this multiple and the absolute jump."}:"fomo_no_recovery_jump"===e.key?{...e,label:"Full-exit target jump",help:"Absolute rebound target used when larger than the target multiple."}:e),{key:"fomo_no_stop_multiple",label:"Direct-NO stop multiple",help:"Inside the active exit window, a direct-NO bid at this fraction of raw entry triggers full liquidation through the better complete route.",min:5,max:95,step:1,scale:100}],rE=[...rM.map(e=>"fomo_no_stake_usd"===e.key?{...e,label:"Live stake per match",help:"Maximum fee-inclusive live cost for one qualifying match. Default is $100; changes apply to future entries only."}:"fomo_no_min_fill_usd"===e.key?{...e,help:"Reject live submission unless this much ask depth is executable inside the configured price ceiling."}:"fomo_no_stop_multiple"===e.key?{...e,help:"Inside the active exit window, this fraction of raw entry triggers a bounded direct-NO taker exit."}:e),{key:"daily_max_loss_usd",label:"Daily/session loss stop",help:"Pauses this live account after its marked session loss reaches this amount. Set 0 to disable.",min:0,max:1e6,step:25}],rA=[{key:"copy_size_ratio",label:"Copy proportion",help:"Percent of US391's qualifying Under commitment.",min:.1,max:100,step:.5,scale:100},{key:"copy_max_stake_usd",label:"Per-market cap",help:"Maximum copied exposure in one exact Under market.",min:1,max:1e6,step:25},{key:"copy_max_open_exposure_usd",label:"Total open exposure cap",help:"Maximum deployed across every unresolved US391 copy.",min:1,max:1e7,step:50},{key:"copy_bankroll_fraction",label:"Wallet equity cap",help:"Maximum percent of current wallet equity per market.",min:.1,max:100,step:.25,scale:100},{key:"daily_max_loss_usd",label:"Daily/session loss stop",help:"Pauses new entries after this loss; 0 disables it.",min:0,max:1e6,step:50},{key:"copy_max_slippage",label:"Max source lag",help:"Maximum price paid above the source average.",min:0,max:25,step:.5,scale:100},{key:"copy_max_spread",label:"Maximum spread",help:"Reject wider two-sided books.",min:0,max:50,step:.5,scale:100},{key:"copy_max_chase",label:"Depth chase",help:"Maximum walk above the current best ask.",min:0,max:25,step:.5,scale:100},{key:"copy_max_price",label:"Token price ceiling",help:"Never copy above this Under token price.",min:1,max:99,step:1,scale:100},{key:"copy_min_fill_usd",label:"Minimum executable fill",help:"Wait unless this much depth clears inside the price cap.",min:1,max:1e5,step:5},{key:"copy_burst_quiet_sec",label:"Burst aggregation",help:"Wait this long after the latest source buy before copying.",min:5,max:600,step:1},{key:"copy_mempool_quiet_sec",label:"Pending burst wait",help:"Short aggregation wait after a pending source fill appears in the mempool.",min:.5,max:60,step:.5},{key:"copy_mempool_bootstrap_lookback_sec",label:"Pending startup lookback",help:"Recent pending observations accepted when the copier starts.",min:0,max:300,step:1},{key:"copy_api_poll_sec",label:"API reconciliation",help:"Seconds between authoritative Data API reconciliation polls.",min:2,max:300,step:1},{key:"copy_candidate_ttl_sec",label:"Signal expiry",help:"Stop retrying a stale source opportunity after this many seconds.",min:60,max:86400,step:30},{key:"copy_retry_sec",label:"Retry interval",help:"Delay before checking a temporarily blocked order again.",min:5,max:600,step:1},{key:"copy_max_submit_attempts",label:"Submit attempts",help:"Maximum confirmed unmatched retries.",min:1,max:20,step:1},{key:"copy_hedge_ratio",label:"Hedge veto ratio",help:"Skip when source Over hedges reach this 
8share of Under buys.",min:0,max:100,step:5,scale:100},{key:"copy_hedge_min_usd",label:"Hedge veto minimum",help:"Ignore tiny opposing source hedges below this amount.",min:1,max:1e6,step:25},{key:"copy_exit_sell_ratio",label:"Exit trigger ratio",help:"Mirror out after source sells this share of its Under buys.",min:1,max:100,step:5,scale:100},{key:"copy_bootstrap_lookback_sec",label:"Startup lookback",help:"Source history scanned when the copier process starts.",min:0,max:3600,step:5}],rT=[{key:"copy_size_ratio",label:"Copy proportion",help:"Percent of Rollo's estimated open NO exposure.",min:.1,max:100,step:.5,scale:100},{key:"copy_low_price_threshold",label:"Low-price boundary",help:"Below this source price, use the low-price lag allowance.",min:1,max:98,step:1,scale:100},{key:"copy_high_price_threshold",label:"High-price boundary",help:"Above this source price, use the high-price lag allowance.",min:2,max:99,step:1,scale:100},{key:"copy_low_price_slippage",label:"Low-price lag",help:"Maximum paid above source average in the low-price tier.",min:0,max:25,step:.5,scale:100},{key:"copy_mid_price_slippage",label:"Mid-price lag",help:"Maximum paid above source average in the middle tier.",min:0,max:25,step:.5,scale:100},{key:"copy_high_price_slippage",label:"High-price lag",help:"Maximum paid above source average in the high-price tier.",min:0,max:25,step:.5,scale:100},{key:"copy_max_spread",label:"Maximum spread",help:"Reject wider two-sided books.",min:0,max:50,step:.5,scale:100},{key:"copy_max_price",label:"Token price ceiling",help:"Never copy above this NO token price.",min:1,max:99,step:1,scale:100},{key:"copy_burst_quiet_sec",label:"API burst aggregation",help:"Data API quiet period before acting on fragmented fills.",min:5,max:600,step:1},{key:"copy_mempool_quiet_sec",label:"Mempool aggregation",help:"Faster quiet period for direct RPC-observed source fills.",min:.5,max:60,step:.5},{key:"copy_mempool_bootstrap_lookback_sec",label:"Mempool startup lookback",help:"Recent RPC activity admitted after a process restart.",min:0,max:300,step:1},{key:"copy_api_poll_sec",label:"Data API poll",help:"Fallback source-tape polling interval.",min:2,max:300,step:1},{key:"copy_candidate_ttl_sec",label:"Signal expiry",help:"Stop retrying a stale source opportunity after this many seconds.",min:60,max:86400,step:30},{key:"copy_retry_sec",label:"Retry interval",help:"Delay before checking a temporarily blocked order again.",min:5,max:600,step:1},{key:"copy_max_submit_attempts",label:"Submit attempts",help:"Maximum confirmed unmatched retries.",min:1,max:20,step:1},{key:"copy_bootstrap_lookback_sec",label:"API startup lookback",help:"Data API history scanned when the copier starts.",min:0,max:3600,step:5}],rF=[{key:"style_under_min_price",label:"Minimum NO price",help:"Reject executable NO tokens below this price.",min:1,max:98,step:1,scale:100},{key:"style_under_max_price",label:"Maximum NO price",help:"Reject executable NO tokens above this price.",min:2,max:99,step:1,scale:100},{key:"style_under_max_spread",label:"Maximum spread",help:"Reject books wider than this bid-ask spread.",min:0,max:50,step:.5,scale:100},{key:"style_under_max_quote_age_ms",label:"Maximum quote age",help:"Reject stale L2 snapshots older than this many milliseconds.",min:1e3,max:12e4,step:1e3}],rP=[{key:"ml_pair_max_event_usd",label:"Atomic pair cap",help:"Maximum all-in paper capital for the two simultaneous $100 NO legs, including modeled fees.",min:202,max:1e4,step:1},{key:"ml_pair_min_edge",label:"Minimum edge per leg",help:"Each NO leg must independently clear this calibrated fair-minus-fill edge.",min:0,max:100,step:.5,scale:100},{key:"ml_pair_min_expected_roi",label:"Minimum return per leg",help:"Each NO leg must independently clear this expected return after modeled fees.",min:0,max:1e3,step:1,scale:100},{key:"ml_pair_min_confidence",label:"Minimum confidence",help:"Minimum held-out cross-market support required on both NO legs.",min:0,max:100,step:1,scale:100},{key:"ml_pair_min_price",label:"Minimum NO price",help:"Reject either NO token below this executable price.",min:1,max:98,step:1,scale:100},{key:"ml_pair_max_price",label:"Maximum NO price",help:"Reject either NO token above this executable price.",min:2,max:99,step:1,scale:100},{key:"ml_pair_max_spread",label:"Maximum spread",help:"Both direct NO books must remain inside this bid-ask spread.",min:0,max:50,step:.5,scale:100},{key:"ml_pair_max_quote_age_ms",label:"Maximum quote age",help:"Both exact-L2 snapshots must be no older than this many milliseconds.",min:1e3,max:12e4,step:1e3}],rR=[{key:"inventory_seed_usd",label:"Seed size",help:"First paper position opened on an independently confirmed value candidate.",min:1,max:1e4,step:5},{key:"inventory_add_usd",label:"Add size",help:"Paper size of each later inventory add.",min:1,max:1e4,step:5},{key:"inventory_max_event_usd",label:"Per-match cap",help:"Maximum all-in paper capital across every market and side in one match.",min:1,max:1e5,step:25},{key:"inventory_max_conditions",label:"Unpaired conditions",help:"Maximum distinct conditions that may remain directionally unpaired.",min:1,max:10,step:1},{key:"inventory_max_tranches",label:"Tranches per side",help:"Maximum seed/add count on one exact token side.",min:1,max:10,step:1},{key:"inventory_min_edge",label:"Minimum edge",help:"Independent fair probability minus executable price.",min:0,max:100,step:.5,scale:100},{key:"inventory_min_expected_roi",label:"Minimum expected return",help:"Expected profit divided by all-in paper cost.",min:0,max:1e3,step:1,scale:100},{key:"inventory_min_confidence",label:"Minimum confidence",help:"Minimum cross-market calibration support.",min:0,max:100,step:1,scale:100},{key:"inventory_min_price",label:"Minimum token price",help:"Reject cheaper tokens outside the calibrated range.",min:1,max:98,step:1,scale:100},{key:"inventory_max_price",label:"Maximum token price",help:"Reject expensive tokens outside the calibrated range.",min:2,max:99,step:1,scale:100},{key:"inventory_max_spread",label:"Maximum spread",help:"Reject wider executable books.",min:0,max:50,step:.5,scale:100},{key:"inventory_pair_ceiling",label:"Pair all-in ceiling",help:"Maximum combined unit cost allowed when buying the complement to lock inventory value.",min:0,max:120,step:.5,scale:100},{key:"inventory_quote_age_ms",label:"Maximum quote age",help:"Reject stale L2 snapshots older than this many milliseconds.",min:1e3,max:12e4,step:1e3}],rO=rR.filter(e=>["inventory_min_edge","inventory_min_expected_roi","inventory_min_confidence","inventory_min_price","inventory_max_price","inventory_max_spread","inventory_pair_ceiling","inventory_quote_age_ms"].includes(e.ke
8y));function rL({title:e,config:t,fields:a,dirty:s,saving:r,onChange:n,onMirrorChange:l,continuousSizing:i=!1,onReset:o,onSave:c}){return(0,b.jsxs)("details",{className:"wc-copier-config",children:[(0,b.jsxs)("summary",{children:[(0,b.jsxs)("span",{children:["⚙ ",e]}),(0,b.jsx)("small",{children:s?"unsaved changes":"all active execution rails"})]}),(0,b.jsxs)("div",{className:"wc-copier-config-grid",children:[a.map(e=>{if("text"===e.kind)return(0,b.jsxs)("label",{className:"wc-bot-field wc-under-rail-field wc-under-rail-field-wide",children:[(0,b.jsx)("span",{children:e.label}),(0,b.jsx)("input",{type:"text",value:String(t[e.key]??""),placeholder:e.placeholder,onChange:t=>n(e.key,t.target.value)}),(0,b.jsx)("small",{children:e.help})]},e.key);let a=e.scale||1,s=Number(t[e.key]??0);return(0,b.jsxs)("label",{className:"wc-bot-field wc-under-rail-field",children:[(0,b.jsxs)("span",{children:[e.label,100===a?" (%)":e.key.endsWith("_usd")?" ($)":e.key.includes("_sec")?" (sec)":""]}),(0,b.jsx)("input",{type:"number",min:e.min,max:e.max,step:e.step,value:Number.isFinite(s)?Number((s*a).toFixed(4)):0,onChange:t=>n(e.key,Number(t.target.value)/a)}),(0,b.jsx)("small",{children:e.help})]},e.key)}),l&&(0,b.jsxs)("label",{className:"wc-copier-toggle",children:[(0,b.jsx)("input",{type:"checkbox",checked:!1!==t.copy_mirror_exits,onChange:e=>l(e.target.checked)}),(0,b.jsxs)("span",{children:[(0,b.jsx)("b",{children:"Mirror source exits"}),(0,b.jsx)("small",{children:"Only sells copier-attributed shares; manual inventory stays isolated."})]})]})]}),(0,b.jsxs)("div",{className:"wc-copier-config-actions",children:[(0,b.jsx)("button",{className:"wc-bot-apply",disabled:!s||r,onClick:c,children:r?"saving…":"Save live configuration"}),(0,b.jsx)("button",{className:"wc-copier-reset",disabled:!s||r,onClick:o,children:"Discard edits"}),(0,b.jsx)("span",{children:i?"Changes apply on the next scan; open positions continuously move toward the configured source proportion.":"Changes apply on the agent's next scan. Existing positions are never resized retroactively."})]})]})}let rI=["total","daily","weekly","monthly"],rD={total:"all",daily:"1d",weekly:"7d",monthly:"30d"};function rz({pts:e}){let[t,a]=(0,_.useState)(null),s=(0,_.useRef)(null);if(e.length<2)return(0,b.jsx)("div",{className:"wc-power-sub",style:{height:56,display:"flex",alignItems:"center"},children:"not enough settles yet"});let r=Math.min(0,...e.map(e=>e.v)),n=Math.max(0,...e.map(e=>e.v)),l=Math.max(1e-6,n-r),i=t=>t/(e.length-1)*100,o=e=>40-(e-r)/l*36-2,c=e.map((e,t)=>`${i(t).toFixed(2)},${o(e.v).toFixed(2)}`).join(" "),d=e[e.length-1].v>=0,u=null!=t?e[t]:null;return(0,b.jsxs)("div",{ref:s,style:{position:"relative"},onMouseMove:t=>{let r=s.current?.getBoundingClientRect();!r||r.width<2||a(Math.round(Math.min(1,Math.max(0,(t.clientX-r.left)/r.width))*(e.length-1)))},onMouseLeave:()=>a(null),children:[(0,b.jsxs)("svg",{viewBox:"0 0 100 42",preserveAspectRatio:"none",style:{width:"100%",height:56,display:"block"},children:[r<0&&n>0&&(0,b.jsx)("line",{x1:"0",x2:"100",y1:o(0),y2:o(0),stroke:"currentColor",opacity:"0.15",strokeWidth:"0.5"}),(0,b.jsx)("polyline",{points:c,fill:"none",stroke:d?"#31c48d":"#f05252",strokeWidth:"1.4",vectorEffect:"non-scaling-stroke"}),u&&(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)("line",{x1:i(t),x2:i(t),y1:"0",y2:"42",stroke:"currentColor",opacity:"0.25",strokeWidth:"0.5",vectorEffect:"non-scaling-stroke"}),(0,b.jsx)("circle",{cx:i(t),cy:o(u.v),r:"1.8",fill:u.v>=0?"#31c48d":"#f05252"})]})]}),u&&(0,b.jsxs)("div",{style:{position:"absolute",top:-6,left:`${Math.min(78,Math.max(0,i(t)))}%`,transform:"translateY(-100%)",background:"rgba(20,24,32,0.95)",border:"1px solid rgba(255,255,255,0.15)",borderRadius:6,padding:"4px 8px",fontSize:11,whiteSpace:"nowrap",pointerEvents:"none",zIndex:5},children:[(0,b.jsxs)("b",{style:{color:u.v>=0?"#31c48d":"#f05252"},children:[u.v>=0?"+":"−","$",Math.abs(u.v).toFixed(2)]}),(0,b.jsxs)("span",{style:{opacity:.7},children:[" · settle #",t+1," · ",new Date(u.t).toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})]})]})]})}let rB=e=>`${e<0?"−":""}
8$${Math.abs(e).toLocaleString(void 0,{maximumFractionDigits:0})}`,rW=e=>({color:e>0?"#31c48d":e<0?"#f05252":void 0,fontWeight:600});function rU(){let[e,t]=(0,_.useState)([]),[a,s]=(0,_.useState)(""),[r,n]=(0,_.useState)(""),[l,i]=(0,_.useState)(null),[o,c]=(0,_.useState)(!1),[d,u]=(0,_.useState)(null);(0,_.useEffect)(()=>{(0,er.authGetJson)("/api/worldcup/autotrade/compare").then(e=>t(e?.data?.options||[])).catch(()=>u("couldn’t load the account list"))},[]),(0,_.useEffect)(()=>{if(!a||!r||a===r)return void i(null);let e=!1;return c(!0),u(null),(0,er.authGetJson)(`/api/worldcup/autotrade/compare?a=${encodeURIComponent(a)}&b=${encodeURIComponent(r)}`).then(t=>{e||i(t?.data?.a?{a:t.data.a,b:t.data.b,shared:t.data.shared,window:t.data.window,names:t.data.match_names||{},sharedIds:new Set(t.data.shared_event_ids||[])}:null)}).catch(()=>{e||u("comparison failed — try again")}).finally(()=>{e||c(!1)}),()=>{e=!0}},[a,r]);let h=(t,a,s)=>(0,b.jsxs)("select",{className:"wc-bot-select",value:t,onChange:e=>a(e.target.value),children:[(0,b.jsx)("option",{value:"",children:"Pick a strategy…"}),e.filter(e=>e.account_id!==s).map(e=>(0,b.jsxs)("option",{value:e.account_id,children:[e.account_id," · ",e.mode||"?"," · ",e.settled," settled"]},e.account_id))]}),p=[["Mode",e=>e.mode||"—"],["Settled trades",e=>e.settled],["Win rate",e=>`${e.win_pct}%`],["Capital deployed",e=>rB(e.staked)],["Total PnL",e=>(0,b.jsx)("span",{style:rW(e.pnl),children:rB(e.pnl)})],["ROI",e=>(0,b.jsxs)("span",{style:rW(e.roi_pct),children:[e.roi_pct>0?"+":"",e.roi_pct,"%"]})],["Open now",e=>e.open?`${e.open} (${rB(e.open_usd)})`:"—"]],m=(e,t,a)=>(0,b.jsx)("div",{style:{maxHeight:320,overflowY:"auto"},children:(0,b.jsxs)("table",{className:"wc-bot-pos",style:{width:"100%"},children:[(0,b.jsx)("thead",{children:(0,b.jsxs)("tr",{children:[(0,b.jsx)("th",{children:"Date"}),(0,b.jsx)("th",{children:"Match"}),(0,b.jsx)("th",{children:"Line"}),(0,b.jsx)("th",{children:"Staked"}),(0,b.jsx)("th",{children:"PnL"})]})}),(0,b.jsx)("tbody",{children:e.rows.map((e,s)=>(0,b.jsxs)("tr",{style:a.has(e.event_id)?{background:"rgba(122,162,255,0.07)"}:void 0,children:[(0,b.jsx)("td",{style:{whiteSpace:"nowrap"},children:e.closed_ms?new Date(e.closed_ms).toLocaleDateString([],{month:"short",day:"numeric"}):"—"}),(0,b.jsxs)("td",{title:a.has(e.event_id)?"both accounts traded this match":void 0,children:[a.has(e.event_id)?"⚑ ":"",t[e.event_id]||`match ${e.event_id}`]}),(0,b.jsx)("td",{children:e.label}),(0,b.jsx)("td",{children:rB(e.staked)}),(0,b.jsx)("td",{style:rW(e.pnl),children:rB(e.pnl)})]},`${e.event_id}-${e.label}-${s}`))})]})}),x=e=>(0,b.jsxs)("table",{className:"wc-bot-pos",style:{width:"100%"},children:[(0,b.jsx)("thead",{children:(0,b.jsxs)("tr",{children:[(0,b.jsx)("th",{children:"Line"}),(0,b.jsx)("th",{children:"n"}),(0,b.jsx)("th",{children:"Win"}),(0,b.jsx)("th",{children:"Staked"}),(0,b.jsx)("th",{children:"PnL"}),(0,b.jsx)("th",{children:"ROI"})]})}),(0,b.jsx)("tbody",{children:e.per_line.map(e=>(0,b.jsxs)("tr",{children:[(0,b.jsx)("td",{children:e.label}),(0,b.jsx)("td",{children:e.n}),(0,b.jsxs)("td",{children:[e.win_pct,"%"]}),(0,b.jsx)("td",{children:rB(e.staked)}),(0,b.jsx)("td",{style:rW(e.pnl),children:rB(e.pnl)}),(0,b.jsxs)("td",{style:rW(e.roi_pct),children:[e.roi_pct>0?"+":"",e.roi_pct,"%"]})]},e.label))})]});return(0,b.jsxs)("div",{className:"wc-bot",children:[(0,b.jsx)("div",{className:"wc-bot-head",children:(0,b.jsxs)("div",{children:[(0,b.jsx)("b",{children:"Strategy Comparer"})," ",(0,b.jsx)("span",{className:"wc-power-sub",children:"— any two accounts, paper or live, all-time. The shared-matches row is the only apples-to-apples read."})]})}),(0,b.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10,marginBottom:10},children:[h(a,s,r),h(r,n,a)]}),d&&(0,b.jsx)("div",{className:"wc-ledger-error",children:d}),o&&(0,b.jsxs)("div",{className:"wc-bot-loading",children:[(0,b.jsx)("span",{className:"wc-bot-spin"})," comparing…"]}),l&&!o&&(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)("table",{className:"wc-bot-pos",style:{width:"100%",marginBottom:10},children:[(0,b.jsx)("thead",{children:(0,b.jsxs)("tr",{children:[(0,b.jsx)("th",{style:{width:"34%"}}),(0,b.jsx)("th",{children:l.a.account_id}),(0,b.jsx)("th",{children:l.b.account_id})]})}),(0,b.jsx)("tbody",{children:p.map(([e,t])=>(0,b.jsxs)("tr",{children:[(0,b.jsx)("td",{style:{opacity:.7},children:e}),(0,b.jsx)("td",{children:t(l.a)}),(0,b.jsx)("td",{children:t(l.b)})]},e))})]}),l.window&&l.window.end_ms>l.window.start_ms&&(0,b.jsxs)("div",{className:"wc-bot-adv",style:{marginBottom:10},children:[(0,b.jsx)("b",{children:"Same period, full books"}),(0,b.jsxs)("span",{className:"wc-power-sub",children:[" ","— ",new Date(l.window.start_ms).toLocaleDateString([],{month:"short",day:"numeric"})," → ",new Date(l.window.end_ms).toLocaleDateString([],{month:"short",day:"numeric"})," ","(the span both were active); every trade each made counts, including matches the other skipped."]}),(0,b.jsxs)("table",{className:"wc-bot-pos",style:{width:"100%",marginTop:6},children:[(0,b.jsx)("thead",{children:(0,b.jsxs)("tr",{children:[(0,b.jsx)("th",{}),(0,b.jsx)("th",{children:"Trades"}),(0,b.jsx)("th",{children:"Win"}),(0,b.jsx)("th",{children:"Deployed"}),(0,b.jsx)("th",{children:"PnL"}),(0,b.jsx)("th",{children:"ROI"})]})}),(0,b.jsx)("tbody",{children:[["a",l.a],["b",l.b]].map(([e,t])=>{let a=l.window[e];return(0,b.jsxs)("tr",{children:[(0,b.jsx)("td",{children:t.account_id}),(0,b.jsx)("td",{children:a.trades}),(0,b.jsxs)("td",{children:[a.win_pct,"%"]}),(0,b.jsx)("td",{children:rB(a.staked)}),(0,b.jsx)("td",{style:rW(a.pnl),children:rB(a.pnl)}),(0,b.jsxs)("td",{style:rW(a.roi_pct),children:[a.roi_pct>0?"+":"",a.roi_pct,"%"]})]},e)})})]})]}),(0,b.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10,marginBottom:10},children:[(0,b.jsx)("div",{children:x(l.a)}),(0,b.jsx)("div",{children:x(l.b)})]}),(0,b.jsx)("div",{className:"wc-power-sub",style:{marginBottom:6},children:"Match-by-match ledger (⚑ = both accounts traded it, newest first)"}),(0,b.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[(0,b.jsx)("div",{children:m(l.a,l.names,l.sharedIds)}),(0,b.jsx)("div",{children:m(l.b,l.names,l.sharedIds)})]})]})]})}function rH(){let[e,t]=(0,_.useState)(null),[a,s]=(0,_.useState)(!1),[r,n]=(0,_.useState)({}),[l,i]=(0,_.useState)(null),[o,c]=(0,_.useState)(null),[d,u]=(0,_.useState)({}),[h,p]=(0,_.useState)({}),[m,x]=(0,_.useState)({}),g=(0,_.useRef)({}),f=(0,_.useRef)(new Set),[v,y]=(0,_.useState)(null),[j,w]=(0,_.useState)(null),[N,k]=(0,_.useState)(()=>Date.now()),S=(0,_.useRef)(!0),$=(0,_.useRef)(null),C=(0,_.useCallback)(async(e,t=!1,a=0)=>{for(;g.current[e];){if(!t)return g.current[e];await g.current[e]}t&&y(`ledger:${e}`);let s=(async()=>{let t=500*Math.max(0,a);for(let a=0;a<2;a+=1)try{let a=await (0,er.authGetJson)(`/api/worldcup/autotrade/history?account_id=${encodeURIComponent(e)}&position_limit=500&order_limit=500&position_offset=${t}&order_offset=${t}`);if(!a.ok)throw Error("ledger response was not ok");return u(t=>({...t,[e]:a.data})),x(t=>({...t,[e]:!1})),f.current.add(e),!0}catch{0===a&&await new Promise(e=>setTimeout(e,500))}return f.current.has(e)||x(t=>({...t,[e]:!0})),!1})();g.current[e]=s;try{return await s}finally{g.current[e]===s&&delete g.current[e],t&&y(null)}},[]),M=(0,_.useCallback)((e=!1)=>{let a;return $.current?$.current:(a=(0,er.authGetJson)("/api/worldcup/autotrade/status").then(a=>{S.current&&(a.ok?(t(a.data),k(Date.now()),s(!1)):e||s(!0))}).catch(()=>{S.current&&!e&&s(!0)}).finally(()=>{$.current===a&&($.current=null)}),$.current=a,a)},[]);(0,_.useEffect)(()=>{let e;S.current=!0;let t=!1,a=0,s=async(r=!1)=>{let n=++a;clearTimeout(e),await M(!r),t||n!==a||(e=setTimeout(()=>void s(!1),document.hidden?6e4:1e4))},r=()=>{document.hidden||s(!1)};return s(!0),document.addEventListener("visibilitychange",r),()=>{t=!0,a+=1,S.current=!1,clearTimeout(e),document.removeEventListener("visibilitychange",r)}},[M]),(0,_.useEffect)(()=>{let e=()=>{document.hidden||k(Date.now())},t=setInterval(e,15e3);return document.addEventListener("visibilitychange",e),()=>{clearInterval(t),document.removeEventListener("visibilitychange",e)}},[]),(0,_.useEffect)(()=>
8{if(!j)return;let e=setTimeout(()=>w(null),2500);return()=>clearTimeout(e)},[j]),(0,_.useEffect)(()=>{let e;if(!o)return;let t=h[o]||0,a=!1,s=async()=>{await C(o,!1,t),a||(e=setTimeout(s,15e3))};return e=setTimeout(s,15e3),()=>{a=!0,clearTimeout(e)}},[o,C,h]);let E=async(e,t,a="saved ✓")=>{y(e);try{await t(),await M(!0),w({msg:a,ok:!0})}catch{w({msg:"failed — try again",ok:!1})}finally{y(null)}},A=e=>(0,er.authPostJson)("/api/worldcup/autotrade/account",e),T=(e,t)=>E(`kill:${e.id}`,()=>(0,er.authPostJson)("/api/worldcup/autotrade/kill",{account_id:e.id,killed:t}),t?"manually paused":"resumed"),F=e=>{let t=r[e.id];t&&E(`adv:${e.id}`,async()=>{await A({id:e.id,config:t}),n(t=>{let a={...t};return delete a[e.id],a})},"live configuration saved ✓")},[P,R]=(0,_.useState)(null),[O,L]=(0,_.useState)("total"),[I,D]=(0,_.useState)({}),[z,B]=(0,_.useState)({});(0,_.useEffect)(()=>{let e,t=!1,a=!1,s=0,r=async()=>{if(a)return;a=!0;let n=++s;clearTimeout(e);try{let e=await (0,er.authGetJson)("/api/worldcup/autotrade/pnl-series");t||n!==s||B(e?.data||{})}catch{}finally{a=!1}
8t||n!==s||(e=setTimeout(()=>void r(),document.hidden?3e5:6e4))},n=()=>{document.hidden||r()};return r(),document.addEventListener("visibilitychange",n),()=>{t=!0,s+=1,clearTimeout(e),document.removeEventListener("visibilitychange",n)}},[]);let W=async e=>{o===e.id?c(null):(c(e.id),x(t=>({...t,[e.id]:!1})),p(t=>({...t,[e.id]:0})),await C(e.id,!0,0))},U=e=>{if(!e)return"—";let t=Math.max(0,Math.round((N-e)/1e3));return t<60?`${t}s ago`:t<3600?`${Math.round(t/60)}m ago`:`${Math.round(t/3600)}h ago`},H=e=>e?new Date(e).toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}):"—";if(!e)return(0,b.jsx)("div",{className:"wc-bot",children:(0,b.jsxs)("div",{className:"wc-bot-loading",children:[(0,b.jsx)("span",{className:"wc-bot-spin"})," ",a?"couldn’t reach the auto-trader — retrying…":"loading auto-trader…"]})});let q=e.rust_execution?.native_inventory,V=e.rust_inventory_ledger,G=q?{id:"paper:style-inventory-rust",label:"Inventory Brain · Full Rust",wallet_id:null,mode:"paper",enabled:!!q.enabled,readonly:!0,config:rw,killed:!1,kill_reason:null,today_pnl:Number(V?.today_pnl||0),exposure:Number(V?.open_exposure_usd||0),open_positions:V?.open_positions||[],recent:V?.recent||[]}:null,J=[...G?[G]:[],...(e.accounts||[]).filter(e=>["under_ai","style_under_value","style_under_value_rust_canary","style_under_value_12pp","style_inventory","style_moneyline_pair","style_trailing_no_value","us391_under_copy","rollobravado_moneyline_copy","over05_baseline","over05_defensive","over05_ai","over05_ai_continuous","us391_ml_paper","favorite_no_fade","first_goal_no_fomo","first_goal_no_risk","yrfi_paper","late_tail_paper","key_sub_over","pm15m_updown"].includes(e.config.strategy||""))],Y=J.filter(e=>e.enabled),K=Math.max(0,...J.filter(e=>"live"===e.mode).map(e=>Number(e.config.daily_max_loss_usd||0))),X=Y.reduce((e,t)=>e+(t.today_pnl||0),0),Z=Y.reduce((e,t)=>e+(t.exposure||0),0),Q=e.worker||{},ee=e.goalpilot_worker||{},et=e.copy_worker||{},ea=!Q.last_run_ms||N-Q.last_run_ms>3e4,es=!ee.last_run_ms||N-ee.last_run_ms>3e4,en=!et.last_run_ms||N-et.last_run_ms>75e3,el=J.find(e=>"live:style-under-value-canary"===e.id),ei=J.find(e=>"live:style-under-value-rust-canary"===e.id),eo=e.rust_execution?.direct_execution,ec=e.rust_execution?.native_under,ed=e.rust_execution?.native_trailing_no,eu=Object.entries(q?.hold_reasons||{}).sort((e,t)=>t[1]-e[1]).slice(0,3),eh=!!(el?.enabled&&!el?.killed),ep=!!(ei?.enabled&&!ei?.killed&&eo?.armed),em=J.find(e=>e.id===l)||null,ex=em?(em.recent||[]).map(e=>({...e,acct:em.label})).sort((e,t)=>(t.ts_ms||0)-(e.ts_ms||0)).slice(0,100):[],eg=t=>t&&e.match_names?.[t]||(t?`match ${t}`:"");return(0,b.jsxs)("div",{className:"wc-bot",children:[(0,b.jsx)("div",{className:"wc-bot-head",children:(0,b.jsxs)("div",{children:[(0,b.jsx)("b",{children:"Soccer Agents"})," ",(0,b.jsx)("span",{className:"wc-power-sub",children:"— paper cohorts stay as controls while wallet-bound GoalPilot, US391, and Rollo agents trade inside audited rails."})]})}),(0,b.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(240px, 1fr))",gap:8,margin:"8px 0"},children:[(0,b.jsxs)("div",{className:"wc-under-metrics",style:{alignContent:"start"},children:[(0,b.jsxs)("span",{children:["1 · PYTHON LIVE ",(0,b.jsx)("b",{className:eh?"radar-up":"radar-down",children:eh?"RUNNING":"OFF"})]}),(0,b.jsxs)("span",{children:["actual policy size · exposure ",(0,b.jsxs)("b",{children:["$",(el?.exposure||0).toFixed(0)]})]})]}),(0,b.jsxs)("div",{className:"wc-under-metrics",style:{alignContent:"start"},children:[(0,b.jsxs)("span",{children:["2 · PYTHON → RUST ",(0,b.jsx)("b",{className:ep?"radar-up":"radar-down",children:ep?"LIVE CANARY":"NOT ARMED"})]}),(0,b.jsxs)("span",{children:["$25/position · posts ",(0,b.jsx)("b",{children:eo?.posts??0})," · fills ",(0,b.jsx)("b",{children:eo?.fills??0})]}),eo?.last_error&&(0,b.jsx)("span",{className:"radar-down",children:eo.last_error})]}),(0,b.jsxs)("div",{className:"wc-under-metrics",style:{alignContent:"start"},children:[(0,b.jsxs)("span",{children:["3 · FULL RUST ",(0,b.jsx)("b",{className:ec?.enabled?"wc-power-sub":"radar-down",children:ec?.enabled?"DURABLE SHADOW":"OFF"})]}),(0,b.jsxs)("span",{children:["eval ",(0,b.jsx)("b",{children:ec?.evaluations??0})," · seeds ",(0,b.jsx)("b",{children:ec?.durable_seeds??0})," · open ",(0,b.jsx)("b",{children:ec?.open_positions??0})," · settled ",(0,b.jsx)("b",{children:ec?.settled_positions??0})]}),(0,b.jsxs)("span",{children:["P&L ",(0,b.jsxs)("b",{className:(ec?.realized_pnl_usd||0)>=0?"radar-up":"radar-down",children:[(ec?.realized_pnl_usd||0)>=0?"+":"−","$",Math.abs(ec?.realized_pnl_usd||0).toFixed(0)]})," · last ",(0,b.jsx)("b",{children:U(ec?.last_decision_ms)})]}),(0,b.jsx)("span",{className:"wc-power-sub",children:ec?.execution_armed?"execution armed":ec?.execution_block_reason||"execution disarmed"})]}),(0,b.jsxs)("div",{className:"wc-under-metrics",style:{alignContent:"start"},children:[(0,b.jsxs)("span",{children:["TRAILING-NO · FULL RUST ",(0,b.jsx)("b",{className:ed?.enabled?"wc-power-sub":"radar-down",children:ed?.enabled?"DURABLE SHADOW":"OFF"})]}),(0,b.jsxs)("span",{children:["eval ",(0,b.jsx)("b",{children:ed?.evaluations??0})," · seeds ",(0,b.jsx)("b",{children:ed?.durable_seeds??0})," · open ",(0,b.jsx)("b",{children:ed?.open_positions??0})," · settled ",(0,b.jsx)("b",{children:ed?.settled_positions??0})]}),(0,b.jsxs)("span",{children:["P&L ",(0,b.jsxs)("b",{className:(ed?.realized_pnl_usd||0)>=0?"radar-up":"radar-down",children:[(ed?.realized_pnl_usd||0)>=0?"+":"−","$",Math.abs(ed?.realized_pnl_usd||0).toFixed(0)]})," · last ",(0,b.jsx)("b",{children:U(ed?.last_decision_ms)})]}),(0,b.jsx)("span",{className:"wc-power-sub",children:ed?.execution_armed?"execution armed":ed?.execution_block_reason||"execution disarmed"})]})]}),(0,b.jsxs)("div",{className:"wc-bot-worker",children:[(0,b.jsx)("span",{className:`wc-bot-dot${ea?" stale":""}`}),(0,b.jsxs)("span",{children:["UnderPilot ",!1===Q.ok?"⚠ error":ea?"idle":"live"," · ",U(Q.last_run_ms)]}),null!=Q.matches&&(0,b.jsxs)("span",{className:"wc-power-sub",children:[" · ",Q.matches," live match",1===Q.matches?"":"es"," · ",Q.active_rungs??0," active rung",(Q.active_rungs??0)===1?"":"s"," · ",Q.acted??0," filled / ",Q.skipped??0," skipped last cycle"]}),Q.error&&(0,b.jsxs)("span",{className:"radar-down",children:[" · ",Q.error]}),(0,b.jsx)("span",{className:`wc-bot-dot${en?" stale":""}`}),(0,b.jsxs)("span",{children:["Source Copiers ",!1===et.ok?"⚠ error":en?"idle":"live"," · ",U(et.last_run_ms)]}),null!=et.duration_ms&&(0,b.jsxs)("span",{className:"wc-power-sub",children:[" · ",(et.duration_ms/1e3).toFixed(1),"s tape scan"]}),et.error&&(0,b.jsxs)("span",{className:"radar-down",children:[" · ",et.error]}),(0,b.jsx)("span",{className:`wc-bot-dot${es?" stale":""}`}),(0,b.jsxs)("span",{children:["GoalPilot ",!1===ee.ok?"⚠ error":es?"idle":"live"," · ",U(ee.last_run_ms)]}),null!=ee.duration_ms&&(0,b.jsxs)("span",{className:"wc-power-sub",children:[" · ",(ee.duration_ms/1e3).toFixed(1),"s scan"]}),ee.error&&(0,b.jsxs)("span",{className:"radar-down",children:[" · ",ee.error]}),(0,b.jsx)("span",{className:"wc-bot-spacer"}),(0,b.jsx)("span",{className:"wc-under-no-stop",children:ee.automatic_daily_stop||et.automatic_daily_stop?`LIVE −$${K.toFixed(0)} max account hard stop`:"paper agents have no automatic daily stop"}),(0,b.jsx)("span",{className:"wc-power-sub wc-bot-refresh",children:"● live status 10s · P&L 60s"})]}),Y.length>0&&(0,b.jsxs)("div",{className:`wc-bot-pill${X<0?" neg":""}`,children:["● ",Y.some(e=>"live"===e.mode)?"SOCCER AGENTS":"PAPER AGENTS"," running · today ",(0,b.jsxs)("b",{className:X>=0?"radar-up":"radar-down",children:[X>=0?"+":"","$",X.toFixed(0)]})," · exposure $",Z.toFixed(0)]}),(0,b.jsxs)("div",{style:{display:"flex",gap:6,alignItems:"center",margin:"8px 0 6px"},children:[(0,b.jsx)("span",{className:"wc-power-sub",children:"P&L window (all cards)"}),rI.map(e=>(0,b.jsx)("button",{className:`wc-bot-log${O===e&&!Object.keys(I).length?" on":""}`,onClick:()=>{L(e),D({})},children:rD[e]},e))]}),(0,b.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(300px, 1fr))",gap:10,alignItems:"start"},children:J.map(t=>{let a,s,u,x,g,f,_,j,w,N,k=r[t.id]||t.config,S=e.under_agent?.[t.id],$=e.copy_agent?.[t.id],L=e.over05_agent?.[t.id],B=e.key_sub_agent?.[t.id],G=e.pm15m_agent?.[t.id],J=e.moneyline_no_agent?.[t.id],Y=e.moneyline_pair_agent?.[t.id],K=e.first_goal_no_agent?.[t.id],X="first_goal_no_risk"===t.config.strategy,Z=X&&"live"===t.mode,Q="style_under_value_12pp"===t.config.strategy,ee="style_under_value_rust_canary"===t.config.strategy,et="over05_ai"===t.config.strategy||"over05_ai_continuous"===t.config.strategy,ea=!!(L?.one_shot??k.over05_one_shot),es=L?.line_cap_usd??L?.match_cap_usd??k.over05_match_cap_usd??1e3,er=L?.max_total_match_usd??es*(et?3:1),en=Number(k.per_match_cap_usd||0),el=Number(k.under_max_matches||1),ei=Number(k.under_probe_usd??50),eo=Number(k.under_entry_max_usd??300),ec=Number(k.under_add_usd??100),ed=Number(k.under_soft_match_cap_usd??1500),eh=100*Number(k.under_trim_fraction??.5),ep=Number(k.daily_max_loss_usd||0),em=t.execution_kernel,ex=em?.ledger?.latency_ms,ef=em?.execution_parity||em?.ledger?.execution_parity,eb=em?.readiness||(ef?.proven?ef?.healthy?"healthy":"degraded":"unproven"),e_=!!(em?.running&&"healthy"===eb&&em?.slo?.healthy&&!em?.last_error),ev=e=>null==e?"—":e<1e3?`${Math.round(e)}ms`:`${(e/1e3).toFixed(1)}s`;return(0,b.jsxs)("div",{className:`wc-bot-acct${t.enabled?" on":""}${l===t.id?" sel":""}`,style:P===t.id?{gridColumn:"1 / -1"}:void 0,children:[(0,b.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,b.jsx)("span",{className:`wc-bot-mode ${t.mode}`,children:t.mode.toUpperCase()}),(0,b.jsx)("b",{style:{flex:1,fontSize:13,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.label}),t.killed&&(0,b.jsx)("span",{title:t.kill_reason||"paused",children:"🛑"}),!t.enabled&&!t.killed&&(0,b.jsx)("span",{className:"wc-power-sub",children:"off"}),(0,b.jsx)("button",{className:`wc-bot-log${P===t.id?" on":""}`,onClick:()=>R(P===t.id?null:t.id),children:P===t.id?"close ×":"open"})]}),(s=((a=z[t.id])||[]).reduce((e,[,t])=>e+t,0),u=I[t.id]||O,(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)("div",{style:{display:"flex",gap:16,margin:"6px 0 4px",alignItems:"baseline"},children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{className:"wc-power-sub",children:"pm15m_updown"===t.config.strategy?"year seed + live ":"key_sub_over"===t.config.strategy?"cap-stress + forward ":t.config.strategy?.startsWith("first_goal_no_")||["style_under_value","style_under_value_rust_canary","style_under_value_12pp","style_moneyline_pair"].includes(t.config.strategy||"")?"backtest + forward ":"total "}),(0,b.jsxs)("b",{className:s>=0?"radar-up":"radar-down",children:[s>=0?"+":"−","$",Math.abs(s).toFixed(0)]})]}),(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{className:"wc-power-sub",children:"today "}),(0,b.jsxs)("b",{className:t.today_pnl>=0?"radar-up":"radar-down",children:[t.today_pnl>=0?"+":"−","$",Math.abs(t.today_pnl).toFixed(0)]})]}),t.exposure>0&&(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{className:"wc-power-sub",children:"open "}),(0,b.jsxs)("b",{children:["$",t.exposure.toFixed(0)]})]}),(0,b.jsx)("span",{style:{flex:1}}),rI.map(e=>(0,b.jsx)("button",{style:{fontSize:10,padding:"1px 5px",opacity:u===e?1:.45,background:"none",border:"1px solid rgba(255,255,255,0.18)",borderRadius:4,cursor:"pointer",color:"inherit"},onClick:()=>D(a=>({...a,[t.id]:e})),children:rD[e]},e))]}),(0,b.jsx)(rz,{pts:function(e,t){if(!e||!e.length)return[];let a="daily"===t?Date.now()-864e5:"weekly"===t?Date.now()-6048e5:"monthly"===t?Date.now()-2592e6:0,s=0,r=[];for(let[t,n]of e)a&&t<a||(s+=n,r.push({t,v:Math.round(100*s)/100}));return r}(a,u)})]})),P===t.id&&(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)("div",{className:"wc-bot-acct-head",children:[(0,b.jsx)("span",{className:`wc-bot-mode ${t.mode}`,title:"live"===t.mode?"Real orders through the bound Wallet Management wallet.":"Simulation only; no wallet orders.",children:t.mode.toUpperCase()}),(0,b.jsx)("b",{children:t.label}),t.readonly?(0,b.jsx)("span",{className:"radar-up",children:"RUNNING"}):(0,b.jsx)("button",{className:`wc-bot-sw${t.enabled?" on":""}`,disabled:v===`tog:${t.id}`,onClick:()=>E(`tog:${t.id}`,()=>
8A({id:t.id,label:t.label,mode:t.mode,wallet_id:t.wallet_id,config:t.config,enabled:!t.enabled}),t.enabled?"turned OFF":"turned ON ✓"),title:`Enable or pause this ${t.mode} agent.`,children:v===`tog:${t.id}`?"···":t.enabled?"ON":"OFF"}),(0,b.jsx)("button",{className:`wc-bot-log${l===t.id?" on":""}`,onClick:()=>i(l===t.id?null:t.id),title:"show this account's decision log below",children:"📋 log"}),(0,b.jsx)("button",{className:`wc-bot-log${o===t.id?" on":""}`,disabled:v===`ledger:${t.id}`,onClick:()=>W(t),title:"show settled positions, lifetime P&L and the complete execution ledger",children:v===`ledger:${t.id}`?"loading…":"▤ history"}),(0,b.jsx)("span",{className:"wc-bot-spacer"}),(0,b.jsx)("span",{className:"wc-power-sub",title:`Realized ${t.mode} profit and loss since the UTC day began.`,children:"today "}),(0,b.jsxs)("b",{className:t.today_pnl>=0?"radar-up":"radar-down",children:[t.today_pnl>=0?"+":"","$",t.today_pnl.toFixed(0)]}),(0,b.jsxs)("span",{className:"wc-power-sub",title:`${"live"===t.mode?"Live":"Paper"} capital currently deployed in unresolved positions.`,children:[" · open $",t.exposure.toFixed(0)]}),null!=t.avg_clv&&(0,b.jsxs)("span",{className:"wc-power-sub",title:`avg closing-line value over ${t.clv_n} graded fills — above 0 means you beat the market (≈ your real edge, readable in ~50 bets)`,children:[" · CLV ",(0,b.jsxs)("b",{className:t.avg_clv>=0?"radar-up":"radar-down",children:[t.avg_clv>=0?"+":"",(100*t.avg_clv).toFixed(1),"%"]})]}),!t.readonly&&(t.killed?(0,b.jsx)("button",{className:"wc-bot-kill killed",disabled:v===`kill:${t.id}`,onClick:()=>T(t,!1),title:t.kill_reason||"",children:v===`kill:${t.id}`?"…":"🛑 paused — resume"}):(0,b.jsx)("button",{className:"wc-bot-kill",disabled:v===`kill:${t.id}`,onClick:()=>T(t,!0),title:"live"===t.mode?`Manual emergency pause. New entries also stop after −$${ep.toFixed(0)} since the UTC day began or since your latest manual resume.`:"Manual emergency pause.",children:v===`kill:${t.id}`?"…":"⏻ manual pause"}))]}),"live"===t.mode&&(0,b.jsxs)("div",{className:"wc-bot-adv",style:{display:"flex",alignItems:"center",gap:8,padding:"4px 0"},children:[(0,b.jsx)("span",{className:"wc-power-sub",title:"Which Wallet Management wallet this agent trades through. Unset = the wallet marked active on the Wallets tab. Give each live agent its own wallet: the on-chain reconciler treats a wallet's holdings as one account's truth, so two agents sharing a wallet in the same market double-count.",children:"Wallet"}),(0,b.jsxs)("select",{value:t.wallet_id||"",disabled:v===`wallet:${t.id}`,onChange:async e=>{let a=e.target.value;if(a){y(`wallet:${t.id}`);try{await A({id:t.id,wallet_id:a}),await M(!0)}finally{y(null)}}},children:[(0,b.jsx)("option",{value:"",children:"— active wallet (default) —"}),(e.wallets||[]).map(e=>(0,b.jsxs)("option",{value:e.id,children:[e.name||(e.address?`${e.address.slice(0,6)}…${e.address.slice(-4)}`:e.id.slice(0,8)),e.is_active?" · active":""]},e.id))]}),!t.wallet_id&&(0,b.jsx)("span",{className:"wc-power-sub",children:"using the active wallet"})]}),"style_inventory_rust"===t.config.strategy&&(0,b.jsxs)("div",{className:"wc-under-agent",children:[(0,b.jsxs)("div",{className:"wc-under-agent-head",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{className:"wc-under-agent-kicker",children:"INVENTORY BRAIN // FULL RUST"}),(0,b.jsx)("b",{children:" Spread-2.5 NO recycler"})]}),(0,b.jsx)("span",{className:"wc-under-paper",children:"PAPER · DURABLE WAL"})]}),(0,b.jsx)("div",{className:"wc-under-agent-note",children:"Native Rust reads the direct match and CLOB feeds, seeds value-qualified spread 2.5 NO positions, then continuously buys the exact complement when the pair locks profit below its all-in ceiling. The card, curve, open book, decisions, and history all read the same durable Rust ledger."}),(0,b.jsxs)("div",{className:"wc-under-metrics",children:[(0,b.jsxs)("span",{children:["evaluations ",(0,b.jsx)("b",{children:q?.autonomous_evaluations??q?.evaluations??0})]}),(0,b.jsxs)("span",{children:["seeds ",(0,b.jsx)("b",{children:q?.durable_seeds??q?.autonomous_seeds??0})]}),(0,b.jsxs)("span",{children:["open ",(0,b.jsx)("b",{children:V?.open_positions?.length??q?.open_unpaired??0})]}),(0,b.jsxs)("span",{children:["pair locks ",(0,b.jsx)("b",{children:q?.pair_locks??0})]}),(0,b.jsxs)("span",{children:["terminal ",(0,b.jsx)("b",{children:q?.terminal_unpaired??0})]}),(0,b.jsxs)("span",{children:["rejected ",(0,b.jsx)("b",{children:q?.rejected_decisions??0})]}),(0,b.jsxs)("span",{children:["last ",(0,b.jsx)("b",{children:U(q?.last_decision_ms)})]})]}),(0,b.jsxs)("div",{className:"wc-under-metrics",children:[(0,b.jsxs)("span",{className:q?.direct_feed?.ready?"radar-up":"radar-down",children:["FEED ",(0,b.jsx)("b",{children:q?.direct_feed?.ready?"READY":"WAITING"})]}),(0,b.jsxs)("span",{children:["matches ",(0,b.jsx)("b",{children:q?.direct_feed?.matches??0})]}),(0,b.jsxs)("span",{children:["tokens ",(0,b.jsx)("b",{children:q?.direct_feed?.tokens??0})]}),(0,b.jsxs)("span",{children:["locked P&L ",(0,b.jsxs)("b",{className:(q?.locked_pnl_usd||0)>=0?"radar-up":"radar-down",children:[(q?.locked_pnl_usd||0)>=0?"+":"−","$",Math.abs(q?.locked_pnl_usd||0).toFixed(2)]})]}),(0,b.jsx)("span",{className:"wc-power-sub",children:"paper ledger only · wallet path absent"})]}),eu.length>0&&(0,b.jsxs)("div",{className:"wc-under-foot",children:["Top holds: ",eu.map(([e,t])=>`${e.replaceAll("_"," ")} \xd7${t}`).join(" · ")]})]}),"style_inventory"===t.config.strategy&&(0,b.jsxs)("div",{className:"wc-under-agent",children:[(0,b.jsxs)("div",{className:"wc-under-agent-head",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{className:"wc-under-agent-kicker",children:"TRADER-STYLE // INVENTORY BRAIN"}),(0,b.jsx)("b",{children:" Independent value + inventory mechanics"})]}),(0,b.jsx)("span",{className:"live"===t.mode?"wc-under-live":"wc-under-paper",children:"live"===t.mode?"LIVE · PROBE-LOCK V3":"PAPER CONTROL"})]}),(0,b.jsx)("div",{className:"wc-under-agent-note",children:"live"===t.mode?(0,b.jsxs)(b.Fragment,{children:["Consumes the paper control's immutable L2 decision row, but contains directional risk with an independently sized ",(0,b.jsx)("b",{children:"$5 team-total/spread probe"}),". It never adds while naked: the complement gets five minutes to lock equal shares, otherwise the probe exits through fee-aware FAK execution and authenticated reconciliation."]}):(0,b.jsx)(b.Fragment,{children:"The calibrated cross-market model independently chooses value, then seeds, adds, or buys a complement. It remains the broad decision control; the live v3 canary deliberately transforms those decisions into smaller probe-lock inventory instead of mirroring paper size."})}),(0,b.jsx)("div",{className:"wc-under-sizing-summary",children:"live"===t.mode?(0,b.jsxs)(b.Fragment,{children:["Probe ",(0,b.jsx)("b",{children:"$5"})," · ",(0,b.jsx)("b",{children:"team totals + spreads only"})," · lock window ",(0,b.jsx)("b",{children:"5m"})," · ",(0,b.jsx)("b",{children:"no naked adds"})," · ",(0,b.jsx)("b",{children:"no pair scaling"})," · edge ≥",(0,b.jsxs)("b",{children:[(100*Number(k.inventory_min_edge??.045)).toFixed(1),"pp"]})," · pair all-in ≤",(0,b.jsxs)("b",{children:[(100*Number(k.inventory_pair_ceiling??.995)).toFixed(1),"¢"]}),"."]}):(0,b.jsxs)(b.Fragment,{children:["Seed ",(0,b.jsxs)("b",{children:["$",Number(k.inventory_seed_usd??25).toFixed(0)]})," · add ",(0,b.jsxs)("b",{children:["$",Number(k.inventory_add_usd??25).toFixed(0)]})," · match cap ",(0,b.jsxs)("b",{children:["$",Number(k.inventory_max_event_usd??150).toFixed(0)]})," · edge ≥",(0,b.jsxs)("b",{children:[(100*Number(k.inventory_min_edge??.045)).toFixed(1),"pp"]})," · expected return ≥",(0,b.jsxs)("b",{children:[(100*Number(k.inventory_min_expected_roi??.08)).toFixed(0),"%"]})," · pair all-in ≤",(0,b.jsxs)("b",{children:[(100*Number(k.inventory_pair_ceiling??.995)).toFixed(1),"¢"]}),"."]})}),(0,b.jsx)(rL,{title:"live"===t.mode?"Shared selection thresholds · v3 sizing is fixed":"Inventory Brain paper configuration",config:k,fields:"live"===t.mode?rO:rR,dirty:!!r[t.id],saving:v===`adv:${t.id}
8`,onChange:(e,a)=>n(s=>({...s,[t.id]:{...k,[e]:a}})),onReset:()=>n(e=>{let a={...e};return delete a[t.id],a}),onSave:()=>F(t)})]}),["style_under_value","style_under_value_rust_canary","style_under_value_12pp"].includes(t.config.strategy||"")&&(0,b.jsxs)("div",{className:"wc-under-agent",children:[(0,b.jsxs)("div",{className:"wc-under-agent-head",children:[(0,b.jsxs)("div",{children:[(0,b.jsxs)("span",{className:"wc-under-agent-kicker",children:["UNDER VALUE // ",ee?"PYTHON → RUST CANARY":"live"===t.mode?"PROMOTION CANARY":Q?"12PP · FIVE-SLOT CHALLENGER":"FORWARD CHALLENGER"]}),(0,b.jsx)("b",{children:" Totals NO + BTTS NO"})]}),(0,b.jsx)("span",{className:"wc-under-paper",children:ee?"LIVE · RUST EXECUTION · $25":"live"===t.mode?"LIVE · $100 BASE · $125 STRONG":Q?"PAPER · $100 TOTALS · $50 BTTS":"PAPER · $100 BASE · $125 STRONG"})]}),"live"===t.mode?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)("div",{className:"wc-under-agent-note",children:["Executes every immutable seed chosen by the Under Value paper engine—same event, condition, token, side, score and decision timestamp. Live does ",(0,b.jsx)("b",{children:"not"})," re-run model edge, ROI, spread, cadence, headroom, or condition-slot gates. ",ee?(0,b.jsxs)(b.Fragment,{children:["Rust owns signing and direct FAK submission at a fixed ",(0,b.jsx)("b",{children:"$25 per position"})," with a ",(0,b.jsx)("b",{children:"$500 daily deployment cap"}),"."]}):(0,b.jsxs)(b.Fragment,{children:["Every 12pp decision receives ",(0,b.jsx)("b",{children:"$100"}),"; strong cross-market support raises the exact source target to ",(0,b.jsx)("b",{children:"$125"}),", with a ",(0,b.jsx)("b",{children:"−$2,000 daily/session loss stop"}),"."]})]}),(0,b.jsxs)("div",{className:"wc-under-sizing-summary",children:["Paper decision ",(0,b.jsx)("b",{children:"1:1"})," · raw token cap = source fill +",(0,b.jsx)("b",{children:"5¢"})," · immediate ",(0,b.jsx)("b",{children:"FAK"})," sweep only · exact partial fills retained · authenticated residuals retry without leaving adverse resting exposure."]}),em&&(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)("div",{className:"wc-under-metrics",title:"Durable single-writer execution ledger. Paper state and source intent commit atomically; each exchange attempt is write-ahead journaled and each fill materializes order, position, allocation, and intent in one transaction.",children:[(0,b.jsxs)("span",{className:e_?"radar-up":"unproven"===eb?"wc-power-sub":"radar-down",children:["DECISION PARITY ",(0,b.jsx)("b",{children:eb.toUpperCase()})]}),(0,b.jsxs)("span",{children:["contract ",(0,b.jsx)("b",{children:ef?.contract_version||"—"})]}),(0,b.jsxs)("span",{children:["source ",(0,b.jsx)("b",{children:ef?.source_decisions??0})]}),(0,b.jsxs)("span",{children:["attempted ",(0,b.jsx)("b",{children:ef?.attempted??0})]}),(0,b.jsxs)("span",{children:["delivered ",(0,b.jsx)("b",{children:ef?.delivered??0})]}),(0,b.jsxs)("span",{className:(ef?.software_violations||0)>0?"radar-down":"radar-up",children:["violations ",(0,b.jsx)("b",{children:ef?.software_violations??0})]}),(0,b.jsxs)("span",{children:["heartbeat ",(0,b.jsx)("b",{children:U(em.last_run_ms)})]}),(0,b.jsxs)("span",{children:["active ",(0,b.jsx)("b",{children:em.ledger?.active??0})]}),(0,b.jsxs)("span",{children:["overdue ",(0,b.jsx)("b",{children:em.ledger?.overdue??em.slo?.overdue_intents??0})]}),(0,b.jsxs)("span",{children:["decision→claim p95 ",(0,b.jsx)("b",{children:ev(ex?.create_to_claim_p95)})]}),(0,b.jsxs)("span",{children:["claim→submit p95 ",(0,b.jsx)("b",{children:ev(ex?.claim_to_submit_p95)})]}),(0,b.jsxs)("span",{children:["submit→terminal p95 ",(0,b.jsx)("b",{children:ev(ex?.submit_to_terminal_p95)})]})]}),(0,b.jsxs)("div",{className:"wc-under-metrics",title:"Four-way parity separates synthetic research, historical execution proxy, forward model qualification, and exact live delivery.",children:[(0,b.jsxs)("span",{children:["HIST SYNTH ",(0,b.jsx)("b",{children:ef?.historical_synthetic?.positions??0})," positions / ",(0,b.jsx)("b",{children:ef?.historical_synthetic?.matches??0})," matches"]}),(0,b.jsxs)("span",{children:["HIST PROXY ",(0,b.jsx)("b",{children:ef?.historical_execution_proxy?.positions??0})," positions / ",(0,b.jsx)("b",{children:ef?.historical_execution_proxy?.matches_traded??0})," matches"]}),(0,b.jsxs)("span",{children:["FORWARD MODEL ",(0,b.jsx)("b",{children:ef?.forward_funnel?.model_qualified??0})]}),(0,b.jsxs)("span",{children:["FORWARD EXEC ",(0,b.jsx)("b",{children:ef?.forward_funnel?.executable_decisions??0})]}),(0,b.jsxs)("span",{children:["EXACT LIVE ",(0,b.jsx)("b",{children:ef?.forward_funnel?.delivered??ef?.delivered??0})]}),(0,b.jsxs)("span",{children:["model→exec ",(0,b.jsxs)("b",{children:[((ef?.forward_funnel?.model_to_executable_rate??0)*100).toFixed(1),"%"]})]}),(0,b.jsxs)("span",{children:["source→fill ",(0,b.jsxs)("b",{children:[((ef?.forward_funnel?.source_to_delivery_rate??0)*100).toFixed(1),"%"]})]})]}),(ef?.recent_violations||[]).length>0&&(0,b.jsxs)("div",{className:"wc-under-blocked",children:["Parity alert: ",(ef?.recent_violations||[]).slice(0,3).map(e=>`${e.kind||"unknown"}${e.event_id?` \xb7 ${e.event_id}`:""}`).join("; ")]}),em.last_error&&(0,b.jsxs)("div",{className:"wc-under-blocked",children:["Execution kernel: ",em.last_error]})]})]}):(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)("div",{className:"wc-under-agent-note",children:Q?(0,b.jsxs)(b.Fragment,{children:["Frozen research challenger using a global ",(0,b.jsx)("b",{children:"12pp calibrated edge floor"})," and capacity for ",(0,b.jsx)("b",{children:"five independent conditions per match"}),". The seeded curve uses the audited 2026 replay with an additional 2¢ execution stress; new forward positions use exact live L2 and remain completely paper-only."]}):(0,b.jsxs)(b.Fragment,{children:["Historical seed remains frozen; new forward decisions use the audited ",(0,b.jsx)("b",{children:"12pp / five-slot"})," policy with exact L2. Every qualifying position receives ",(0,b.jsx)("b",{children:"$100"}),"; support from at least two families, four market quotes and 30% confidence raises it to ",(0,b.jsx)("b",{children:"$125"}),". ",(0,b.jsx)("b",{children:"BTTS NO"})," still requires an independent raw edge of at least ",(0,b.jsx)("b",{children:"10pp"}),"."]})}),(0,b.jsx)("div",{className:"wc-under-sizing-summary",children:Q?(0,b.jsxs)(b.Fragment,{children:["Totals ",(0,b.jsxs)("b",{children:["$",Number(k.style_under_totals_position_usd??100).toFixed(0)]})," · BTTS ",(0,b.jsxs)("b",{children:["$",Number(k.style_under_btts_position_usd??50).toFixed(0)]})," · up to ",(0,b.jsx)("b",{children:Number(k.style_under_max_conditions??5)})," conditions · all-in match cap ",(0,b.jsxs)("b",{children:["$",Number(k.style_under_max_event_usd??550).toFixed(0)]})," · calibrated edge ≥",(0,b.jsxs)("b",{children:[(100*Number(k.style_under_min_edge??.12)).toFixed(1),"pp"]})," · spread ≤",(0,b.jsxs)("b",{children:[(100*Number(k.style_under_max_spread??.08)).toFixed(1),"¢"]}),"."]}):(0,b.jsxs)(b.Fragment,{children:["Base ",(0,b.jsxs)("b",{children:["$",Number(k.style_under_base_position_usd??100).toFixed(0)]})," · strong support ",(0,b.jsxs)("b",{children:["$",Number(k.style_under_strong_position_usd??125).toFixed(0)]})," · BTTS raw edge ≥",(0,b.jsx)("b",{children:"10pp"})," · up to ",(0,b.jsx)("b",{children:Number(k.style_under_max_conditions??5)})," conditions · all-in match cap ",(0,b.jsxs)("b",{children:["$",Number(k.style_under_max_event_usd??650).toFixed(0)]})," · calibrated edge ≥",(0,b.jsxs)("b",{children:[(100*Number(k.style_under_min_edge??.12)).toFixed(1),"pp"]})," · spread ≤",(0,b.jsxs)("b",{children:[(100*Number(k.style_under_max_spread??.08)).toFixed(1),"¢"]}),"."]})}),!Q&&(0,b.jsx)(rL,{title:"Under Value paper configuration",config:k,fields:rF,dirty:!!r[t.id],saving:v===`adv:${t.id}
8`,onChange:(e,a)=>n(s=>({...s,[t.id]:{...k,[e]:a}})),onReset:()=>n(e=>{let a={...e};return delete a[t.id],a}),onSave:()=>F(t)})]})]}),"style_moneyline_pair"===t.config.strategy&&(0,b.jsxs)("div",{className:"wc-under-agent",children:[(0,b.jsxs)("div",{className:"wc-under-agent-head",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{className:"wc-under-agent-kicker",children:"MONEYLINE ROUTER // PAIR CONFIRMED"}),(0,b.jsx)("b",{children:" Two independent NO lanes"})]}),(0,b.jsx)("span",{className:"wc-under-paper",children:"PAPER · 2 × $100"})]}),(0,b.jsxs)("div",{className:"wc-under-agent-note",children:["Enters only while the score is non-level and ",(0,b.jsx)("b",{children:"Draw NO"})," plus ",(0,b.jsx)("b",{children:"the trailing team's win NO"})," independently clear the same held-out cross-market model on one exact-L2 snapshot. Both legs fill atomically, pause for ",(0,b.jsxs)("b",{children:[Number(Y?.post_goal_cooldown_seconds??180)/60," minutes after a goal"]}),", and hold to settlement."]}),Y?.research&&(0,b.jsxs)("div",{className:"wc-under-metrics",children:[(0,b.jsxs)("span",{children:["exact-clock sample ",(0,b.jsxs)("b",{children:[Y.research.exact_clock_matches||0," matches"]})]}),(0,b.jsxs)("span",{children:["deployed ",(0,b.jsxs)("b",{children:["$",Number(Y.research.exact_clock_deployed_usd||0).toLocaleString()]})]}),(0,b.jsxs)("span",{className:"radar-up",children:["P&L ",(0,b.jsxs)("b",{children:["+$",Number(Y.research.exact_clock_pnl_usd||0).toLocaleString()]})]}),(0,b.jsxs)("span",{className:"radar-up",children:["ROI ",(0,b.jsxs)("b",{children:[(100*(Y.research.exact_clock_roi||0)).toFixed(1),"%"]})]}),(0,b.jsxs)("span",{children:["settlement WR ",(0,b.jsxs)("b",{children:[(100*(Y.research.exact_clock_win_rate||0)).toFixed(1),"%"]})]}),(0,b.jsxs)("span",{children:["max drawdown ",(0,b.jsxs)("b",{children:["$",Number(Y.research.exact_clock_max_drawdown_usd||0).toLocaleString()]})]}),(0,b.jsxs)("span",{children:["2025 development ",(0,b.jsxs)("b",{children:[Y.research.development_2025_matches||0," · ",(100*(Y.research.development_2025_roi||0)).toFixed(1),"%"]})]})]}),(0,b.jsxs)("div",{className:"wc-under-sizing-summary",children:["Fixed ",(0,b.jsx)("b",{children:"$100 per NO leg"})," · one atomic pair per match · all-in cap ",(0,b.jsxs)("b",{children:["$",Number(k.ml_pair_max_event_usd??205).toFixed(0)]})," · edge ≥",(0,b.jsxs)("b",{children:[(100*Number(k.ml_pair_min_edge??.08)).toFixed(1),"pp each"]})," · return ≥",(0,b.jsxs)("b",{children:[(100*Number(k.ml_pair_min_expected_roi??.15)).toFixed(0),"% each"]})," · spread ≤",(0,b.jsxs)("b",{children:[(100*Number(k.ml_pair_max_spread??.08)).toFixed(1),"¢ each"]}),"."]}),(0,b.jsx)(rL,{title:"Moneyline pair paper configuration",config:k,fields:rP,dirty:!!r[t.id],saving:v===`adv:${t.id}`,onChange:(e,a)=>n(s=>({...s,[t.id]:{...k,[e]:a}})),onReset:()=>n(e=>{let a={...e};return delete a[t.id],a}),onSave:()=>F(t)}),(0,b.jsx)("div",{className:"wc-under-foot",children:"The direct leader-YES route is measured beside the equivalent equal-share two-NO route, but execution remains frozen to the tested equal-dollar pair. This is not live-promotable until the exact-L2 forward sample reaches 300 opportunities across at least three months with positive realized fills."})]}),"style_trailing_no_value"===t.config.strategy&&(0,b.jsxs)("div",{className:"wc-under-agent",children:[(0,b.jsxs)("div",{className:"wc-under-agent-head",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{className:"wc-under-agent-kicker",children:"MONEYLINE NO // SCORE-STATE VALUE"}),(0,b.jsx)("b",{children:" Fade the trailing team"})]}),(0,b.jsx)("span",{className:"live"===t.mode?"wc-under-live":"wc-under-paper",children:"live"===t.mode?"LIVE · DURABLE FAK":"PAPER CONTROL"})]}),(0,b.jsxs)("div",{className:"wc-under-agent-note",children:["Holds out the entire moneyline family, prices it from independent totals, BTTS, spread, team-total and exact-score markets, then buys only ",(0,b.jsx)("b",{children:"NO on the team currently trailing"}),". It never buys Draw NO, never adds a second match leg, and holds to settlement."]}),(0,b.jsxs)("div",{className:"wc-under-sizing-summary",children:[(0,b.jsx)("b",{children:"$100"})," per match · calibrated executable edge ≥",(0,b.jsx)("b",{children:"12pp"})," · expected return ≥",(0,b.jsx)("b",{children:"15%"})," · spread ≤",(0,b.jsx)("b",{children:"8¢"})," · source price +",(0,b.jsx)("b",{children:"5¢"})," maximum FAK chase."]}),"live"===t.mode&&em&&(0,b.jsxs)("div",{className:"wc-under-metrics",children:[(0,b.jsxs)("span",{className:e_?"radar-up":"radar-down",children:["OMS ",(0,b.jsx)("b",{children:eb.toUpperCase()})]}),(0,b.jsxs)("span",{children:["heartbeat ",(0,b.jsx)("b",{children:U(em.last_run_ms)})]}),(0,b.jsxs)("span",{children:["active ",(0,b.jsx)("b",{children:em.ledger?.active??0})]}),(0,b.jsxs)("span",{children:["decision→claim p95 ",(0,b.jsx)("b",{children:ev(ex?.create_to_claim_p95)})]}),(0,b.jsxs)("span",{children:["claim→submit p95 ",(0,b.jsx)("b",{children:ev(ex?.claim_to_submit_p95)})]})]})]}),"under_ai"===t.config.strategy&&(0,b.jsxs)("div",{className:"wc-under-agent",children:[(0,b.jsxs)("div",{className:"wc-under-agent-head",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{className:"wc-under-agent-kicker",children:"UNDERPILOT // 5-MIN + EVENT BRAIN"}),(0,b.jsx)("b",{children:" AI-managed Under portfolio"})]}),(0,b.jsx)("span",{className:"wc-under-paper",children:"PAPER ONLY"})]}),(0,b.jsxs)("div",{className:"wc-under-agent-note",children:["Reads every five minutes from 15′ and immediately after material events. A goal by 15′ pauses entries until 25′; two goals by 20′ permanently lock out full-match Unders. It may paper-trade up to ",S?.max_matches||k.under_max_matches||10," live soccer matches across all leagues. Narration + recent stats + Scout/lineups + exact smart-money totals books + CLOB tape drive the AI."]}),S?.blocked&&(0,b.jsx)("div",{className:"wc-under-blocked",children:S.blocked}),!S?.blocked&&0===(S?.matches||[]).length&&(0,b.jsx)("div",{className:"wc-under-empty",children:t.enabled?"Waiting for an eligible live match and its first 15′ AI read.":"Turn this paper account ON to start the five-minute/event recorder."}),(S?.matches||[]).map(e=>(0,b.jsxs)("div",{className:"wc-under-row",children:[(0,b.jsxs)("div",{className:"wc-under-row-main",children:[(0,b.jsx)("span",{className:`wc-under-state s-${e.state.toLowerCase()}`,children:e.state}),(0,b.jsx)("b",{children:e.match}),(0,b.jsxs)("span",{className:"wc-power-sub",children:[e.minute,"' · ",e.score," · ",e.regime.replace("_"," ")]}),null!=e.line&&e.line>0&&(0,b.jsxs)("span",{className:"wc-under-line",children:["U",e.line]})]}),(0,b.jsx)("div",{className:"wc-under-metrics",children:null!=e.position_usd&&e.position_usd>0&&(0,b.jsxs)("span",{className:"radar-up",children:["held ",(0,b.jsxs)("b",{children:["$",e.position_usd.toFixed(0)," · ",e.position_legs||1," tranche",1===(e.position_legs||1)?"":"s"]})]})}),(e.decisions||[]).length>0?(e.decisions||[]).map((t,a)=>(0,b.jsxs)("div",{children:[(0,b.jsxs)("div",{className:"wc-under-thesis",children:[(0,b.jsxs)("span",{children:[t.state," · ",null!=t.line?`U${t.line}`:t.action,t.stake_usd?` \xb7 $${t.stake_usd}`:""]}),t.reason]}),(0,b.jsxs)("div",{className:"wc-under-metrics",children:[null!=t.price&&(0,b.jsxs)("span",{children:["ask ",(0,b.jsxs)("b",{children:[(100*t.price).toFixed(1),"¢"]})]}),null!=t.fair&&(0,b.jsxs)("span",{children:["fair ",(0,b.jsxs)("b",{children:[(100*t.fair).toFixed(1),"%"]})]}),null!=t.edge&&(0,b.jsxs)("span",{className:t.edge>=0?"radar-up":"radar-down",children:["edge ",(0,b.jsxs)("b",{children:[t.edge>=0?"+":"",(100*t.edge).toFixed(1),"pp"]})]}),null!=t.fill_usd&&(0,b.jsxs)("span",{className:"radar-up",children:["paper fill ",(0,b.jsxs)("b",{children:["$",t.fill_usd.toFixed(0)," @ ",(100*(t.fill_price||0)).toFixed(1),"¢"]})]}),null!=t.trim_fraction&&(0,b.jsxs)("span",{children:["trimmed ",(0,b.jsxs)("b",{children:[(100*t.trim_fraction).toFixed(0),"%"]})]})]})]},`${e.event_id}:${t.line??"none"}:${a}`)):(0,b.jsxs)("div",{className:"wc-under-thesis",children:[(0,b.jsxs)("span",{children:[e.action||"awaiting AI",e.confidence?` \xb7 ${e.confidence}`:""]}),e.reason]})]},e.event_id)),S?.entry_checkpoints&&(0,b.jsx)("div",{className:"wc-under-foot",children:"AI reads every minute from 15′. It may sequentially build the first-half ladder during 15–30′ and 40–45′; later first entries remain near 58′ / 75′. Adds, holds, trims and exits can happen between those windows. This is forward-paper research, not a live-wallet rule."})]}),"us391_ml_paper"===t.config.strategy&&(0,b.jsx)("div",{className:"wc-bot-adv",children:(0,b.jsxs)("div",{className:"wc-under-rails-intro",children:[(0,b.jsx)("b",{children:"Prematch ML-NO paper copier."}
8)," Forward-tests US391's biggest bucket (+$338k at +4.0% ROI) restricted to the slice his Entry Clock says is real: NO buys on tracked soccer moneylines ",(0,b.jsx)("b",{children:"before kickoff only"}),", 2% proportional, capped $200/market, never above 65¢ (his 90–95¢ band lost $193k on 4 trades). Skipped in-play source entries are logged in the decision ledger with reasons."]})}),"favorite_no_fade"===t.config.strategy&&(0,b.jsxs)("div",{className:"wc-under-agent",children:[(0,b.jsxs)("div",{className:"wc-under-agent-head",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{className:"wc-under-agent-kicker",children:"FAVORITE-NO // FIRST-GOAL FADE"}),(0,b.jsx)("b",{children:" Validated settlement lane"})]}),(0,b.jsx)("span",{className:"wc-under-paper",children:"PAPER ONLY"})]}),(0,b.jsxs)("div",{className:"wc-under-agent-note",children:["One direct NO only: a ",(0,b.jsx)("b",{children:"55–70% observable favorite"})," concedes first, remains exactly one goal behind for ",(0,b.jsx)("b",{children:"five minutes"}),", and its NO is still offered at ",(0,b.jsx)("b",{children:"50–70¢"}),". Entry requires ≤2¢ spread and ≥100 shares at the top ask. Club friendlies and Leagues Cup are excluded; qualifying positions hold to settlement."]}),J?.research&&(0,b.jsxs)("div",{className:"wc-under-metrics",children:[(0,b.jsxs)("span",{children:["historical ",(0,b.jsxs)("b",{children:[J.research.historical_trades||0," · ",(100*(J.research.historical_roi||0)).toFixed(1),"% ROI"]})]}),(0,b.jsxs)("span",{children:["archive holdout ",(0,b.jsxs)("b",{children:[(100*(J.research.archive_holdout_roi||0)).toFixed(1),"%"]})]}),(0,b.jsxs)("span",{className:"radar-up",children:["actual quotes ",(0,b.jsxs)("b",{children:[J.research.live_quote_trades||0," · ",(100*(J.research.live_quote_roi||0)).toFixed(1),"% ROI"]})]}),(0,b.jsxs)("span",{children:["quote WR ",(0,b.jsxs)("b",{children:[(100*(J.research.live_quote_win_rate||0)).toFixed(1),"%"]})]}),(0,b.jsxs)("span",{className:"radar-down",children:["rejected broad lane ",(0,b.jsxs)("b",{children:[(100*(J.research.rejected_broad_forward_roi||0)).toFixed(1),"%"]})]})]}),0===(J?.matches||[]).length&&(0,b.jsx)("div",{className:"wc-under-empty",children:t.enabled?"Waiting for a 55–70% favorite to concede first and remain behind for five minutes.":"Turn this paper account ON to continue forward validation."}),(J?.matches||[]).map(e=>(0,b.jsxs)("div",{className:"wc-under-row",children:[(0,b.jsxs)("div",{className:"wc-under-row-main",children:[(0,b.jsx)("span",{className:`wc-under-state s-${"wait"===e.action?"watch":"entry"}`,children:e.action.replace("_"," ")}),(0,b.jsx)("b",{children:e.match}),(0,b.jsxs)("span",{className:"wc-power-sub",children:[e.status,"live"===e.status?` \xb7 ${e.minute}′`:""," · ",e.confidence]}),e.fade_outcomes.length>0&&(0,b.jsxs)("span",{className:"wc-under-line",children:["NO ",e.fade_outcomes.join(" + NO ")]})]}),(0,b.jsxs)("div",{className:"wc-under-metrics",children:[null!=e.favorite_price&&(0,b.jsxs)("span",{children:["favorite before goal ",(0,b.jsxs)("b",{children:[(100*e.favorite_price).toFixed(1),"%"]})]}),null!=e.no_ask&&(0,b.jsxs)("span",{children:["NO ask ",(0,b.jsxs)("b",{children:[(100*e.no_ask).toFixed(1),"¢"]})]}),null!=e.spread&&(0,b.jsxs)("span",{children:["spread ",(0,b.jsxs)("b",{children:[(100*e.spread).toFixed(1),"¢"]})]}),null!=e.ask_size&&(0,b.jsxs)("span",{children:["top ask ",(0,b.jsxs)("b",{children:[e.ask_size.toFixed(0)," shares"]})]})]}),(0,b.jsxs)("div",{className:"wc-under-thesis",children:[(0,b.jsx)("span",{children:"RULE READ"}),e.reason||"No thesis returned."]})]},`${e.event_id}:${e.minute}:${e.action}`)),(0,b.jsx)("div",{className:"wc-under-foot",children:"The previous forced prematch single-NO and two-NO products were removed after negative after-cost results. This narrower lane survived development, validation, archive holdout, and actual captured quote checks, but remains paper-only because the executable sample is still small."})]}),["first_goal_no_fomo","first_goal_no_risk"].includes(t.config.strategy||"")&&(0,b.jsxs)("div",{className:"wc-under-agent",children:[(0,b.jsxs)("div",{className:"wc-under-agent-head",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{className:"wc-under-agent-kicker",children:X?"FOMO FADE // RISK ROUTER":"FOMO FADE // DIRECT-NO SHOCK"}),(0,b.jsx)("b",{children:" Early first-goal sentiment challenger"})]}),(0,b.jsx)("span",{className:Z?"wc-under-live":"wc-under-paper",children:Z?"LIVE CANARY":"PAPER ONLY"})]}),(0,b.jsxs)("div",{className:"wc-under-agent-note",children:["Fades only the new leader after a ",(0,b.jsxs)("b",{children:[Number(k.fomo_no_min_minute??10),"′–",Number(k.fomo_no_max_minute??29),"′ first goal"]}),": direct NO must collapse ",(0,b.jsxs)("b",{children:[(100*Number(k.fomo_no_min_compression??.3)).toFixed(0),"–",(100*Number(k.fomo_no_max_compression??.7)).toFixed(0),"%"]}),", remain buyable at ",(0,b.jsxs)("b",{children:[(100*Number(k.fomo_no_min_price??.1)).toFixed(0),"–",(100*Number(k.fomo_no_max_price??.25)).toFixed(0),"¢"]}),", and clear the depth/spread rails after a ",(0,b.jsxs)("b",{children:[Number(k.fomo_no_min_goal_age_seconds??120),"–",Number(k.fomo_no_max_goal_age_seconds??240),"s"]})," reaction window. ",X?Z?(0,b.jsxs)(b.Fragment,{children:["For ",Number(k.fomo_no_recovery_window_seconds??300)/60," minutes it takes the full rebound target or half-price stop through executable direct-NO depth."]}):(0,b.jsx)(b.Fragment,{children:"For five minutes it fully exits at the rebound target or half-price stop, routing through two alternate YES books only when both can fill the entire position for better net proceeds."}):(0,b.jsx)(b.Fragment,{children:"A fast rebound recovers principal; the remaining free NO shares settle."})]}),K?.research&&(0,b.jsxs)("div",{className:"wc-under-metrics",children:[(0,b.jsxs)("span",{children:["historical ",(0,b.jsxs)("b",{children:[K.research.historical_trades||0," × $400"]})]}),(0,b.jsxs)("span",{children:["deployed ",(0,b.jsxs)("b",{children:["$",Number(K.research.historical_deployed_usd||0).toLocaleStr
8ing()]})]}),(0,b.jsxs)("span",{className:"radar-up",children:["modeled P&L ",(0,b.jsxs)("b",{children:["+$",Number(K.research.historical_pnl_usd||0).toLocaleString(void 0,{maximumFractionDigits:0})]})]}),(0,b.jsxs)("span",{className:"radar-up",children:["combined ",(0,b.jsxs)("b",{children:[(100*(K.research.historical_roi||0)).toFixed(1),"% ROI"]})]}),(0,b.jsxs)("span",{children:[X?"profitable trades":"NO settles"," ",(0,b.jsxs)("b",{children:[(100*(K.research.settlement_win_rate||0)).toFixed(1),"%"]})]}),(0,b.jsxs)("span",{children:["2025–26 ",(0,b.jsxs)("b",{children:[(100*(K.research.five_minute_principal_runner_roi||0)).toFixed(1),"% ROI"]})]}),(0,b.jsxs)("span",{children:["2024 reverse holdout ",(0,b.jsxs)("b",{children:[K.research.reverse_holdout_trades||0," · ",(100*(K.research.reverse_holdout_roi||0)).toFixed(1),"%"]})]}),(0,b.jsxs)("span",{children:["3¢ stress ",(0,b.jsxs)("b",{children:[(100*(K.research.slippage_stress_roi_at_3c||0)).toFixed(1),"%"]})]}),X&&(0,b.jsxs)("span",{children:["target / stop ",(0,b.jsxs)("b",{children:[K.research.target_exits||0," / ",K.research.stop_exits||0]})]}),X&&(0,b.jsxs)("span",{children:["max drawdown ",(0,b.jsxs)("b",{children:["$",Number(K.research.max_drawdown_usd||0).toLocaleString()]})]}),X&&(0,b.jsxs)("span",{className:"radar-down",children:["retained L2 ",(0,b.jsxs)("b",{children:[K.research.depth_replay_trades||0," · ",(100*(K.research.depth_replay_roi||0)).toFixed(1),"% ROI"]})]}),X&&(0,b.jsxs)("span",{children:["full $400 depth ",(0,b.jsxs)("b",{children:[K.research.depth_replay_full_fills||0,"/",K.research.depth_replay_trades||0]})]}),X&&(0,b.jsxs)("span",{children:["mean fill ",(0,b.jsxs)("b",{children:[(100*(K.research.depth_replay_mean_fill||0)).toFixed(1),"%"]})]})]}),0===(K?.matches||[]).length&&(0,b.jsx)("div",{className:"wc-under-empty",children:t.enabled?"Snapshotting both teams’ direct-NO books before an eligible first goal.":`Turn this ${t.mode} account ON to start the direct-book recorder.`}),(K?.matches||[]).map(e=>(0,b.jsxs)("div",{className:"wc-under-row",children:[(0,b.jsxs)("div",{className:"wc-under-row-main",children:[(0,b.jsx)("span",{className:`wc-under-state s-${"buy_no"===e.action?"entry":"watch"}`,children:e.action.replace("_"," ")}),(0,b.jsx)("b",{children:e.match}),(0,b.jsxs)("span",{className:"wc-power-sub",children:[e.minute,"′ · ","exit"===e.action?`${e.goal_age_seconds}s after entry`:`first goal ${e.goal_minute}′ \xb7 ${e.goal_age_seconds}s after shock`]}),(0,b.jsxs)("span",{className:"wc-under-line",children:["NO ",e.leader]})]}),(0,b.jsx)("div",{className:"wc-under-metrics",children:"exit"===e.action?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)("span",{children:["raw entry ",(0,b.jsxs)("b",{children:[(100*e.pre_goal_no).toFixed(1),"¢"]})]}),(0,b.jsxs)("span",{children:["direct bid ",(0,b.jsxs)("b",{children:[(100*e.no_ask).toFixed(1),"¢"]})]})]}):(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)("span",{children:["pre-goal NO ",(0,b.jsxs)("b",{children:[(100*e.pre_goal_no).toFixed(1),"¢"]})]}),(0,b.jsxs)("span",{children:["ask ",(0,b.jsxs)("b",{children:[(100*e.no_ask).toFixed(1),"¢"]})]}),(0,b.jsxs)("span",{className:e.compression>=.3&&e.compression<=.7?"radar-up":"radar-down",children:["compression ",(0,b.jsxs)("b",{children:[(100*e.compression).toFixed(1),"%"]})]}),(0,b.jsxs)("span",{children:["spread ",(0,b.jsxs)("b",{children:[(100*e.spread).toFixed(1),"¢"]})]})]})}),(0,b.jsxs)("div",{className:"wc-under-thesis",children:[(0,b.jsx)("span",{children:"BOOK READ"}),e.reason]})]},`${e.event_id}:${e.goal_age_seconds}:${e.action}`)),(0,b.jsx)("div",{className:"wc-under-foot",children:Z?"Experimental live canary: bounded taker entries, fee-aware accounting, direct-NO executable exits, and isolated wallet ledger. The retained L2 replay is negative, so keep sizing small until the forward live book proves otherwise.":X?"The profitable seed used price history without depth. The retained 40-level L2 replay is currently negative and overrides any promotion claim; only continued exact-book paper evidence can rehabilitate it.":"This is not the broad Aalesund-style late lottery. The late three-goal-lead cohort was negative. The initial untouched holdout remained positive but crossed zero; the stronger five-minute recent slice was used during sensitivity selection and is not a second holdout. Forward paper fills decide promotion."})]}),"key_sub_over"===t.config.strategy&&(0,b.jsxs)("div",{className:"wc-under-agent",children:[(0,b.jsxs)("div",{className:"wc-under-agent-head",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{className:"wc-under-agent-kicker",children:"KEYSUB // BENCH IMPACT"}),(0,b.jsx)("b",{children:" Late-goal Over paper agent"})]}),(0,b.jsx)("span",{className:"wc-under-paper",children:"PAPER ONLY"})]}),(0,b.jsxs)("div",{className:"wc-under-agent-note",children:["One forward O0.5 entry per match: the ",(0,b.jsx)("b",{children:"pre-match market favorite"})," must still be 0-0 and introduce a point-in-time balanced-key attacker from ",(0,b.jsxs)("b",{children:[Number(k.key_sub_min_minute??55),"′–",Number(k.key_sub_max_minute??64),"′"]}),". The book must remain at or below ",(0,b.jsxs)("b",{children:[(100*Number(k.key_sub_max_price??.7)).toFixed(0),"¢"]}),". Trailing-team substitutions and changes after 64′ are excluded because the larger historical cohorts deteriorated."]}),B?.research&&(0,b.jsxs)("div",{className:"wc-under-metrics",children:[(0,b.jsxs)("span",{children:["covered ",(0,b.jsxs)("b",{children:[B.research.universe_matches?.toLocaleStr
8ing()||"—"," matches"]})]}),(0,b.jsxs)("span",{children:["attacking subs ",(0,b.jsx)("b",{children:B.research.attacking_sub_groups?.toLocaleString()||"—"})]}),(0,b.jsxs)("span",{children:["broad balanced ",(0,b.jsxs)("b",{children:[B.research.broad_balanced_trades||0," trades"]})]}),(0,b.jsxs)("span",{children:["goalless balanced ",(0,b.jsx)("b",{children:B.research.goalless_balanced_trades||0})]}),(0,b.jsxs)("span",{className:"radar-up",children:["priced 2026 ",(0,b.jsxs)("b",{children:[B.research.focused_wins||0,"/",B.research.focused_trades||0]})]}),(0,b.jsxs)("span",{children:["2025 outcome ",(0,b.jsxs)("b",{children:[B.research.archive_2025_wins||0,"/",B.research.archive_2025_trades||0," · ",(100*(B.research.archive_2025_win_rate||0)).toFixed(1),"%"]})]}),(0,b.jsxs)("span",{children:["70¢ sensitivity ",(0,b.jsxs)("b",{children:[(100*(B.research.archive_2025_synthetic_roi_at_cap||0)).toFixed(1),"% ROI"]})]})]}),0===(B?.matches||[]).length&&(0,b.jsx)("div",{className:"wc-under-empty",children:t.enabled?"Watching live 0-0 favorites for a fresh key-attacker substitution.":"Turn this paper account ON to start the forward recorder."}),(B?.matches||[]).map(e=>(0,b.jsxs)("div",{className:"wc-under-row",children:[(0,b.jsxs)("div",{className:"wc-under-row-main",children:[(0,b.jsx)("span",{className:`wc-under-state s-${e.state.toLowerCase()}`,children:e.state}),(0,b.jsx)("b",{children:e.match}),(0,b.jsxs)("span",{className:"wc-power-sub",children:[e.minute,"' · ",e.score,e.favorite?` \xb7 favorite ${e.favorite}`:"",null!=e.sub_minute?` \xb7 sub ${e.sub_minute}′`:""]}),(0,b.jsx)("span",{className:"wc-under-line",children:"O0.5"})]}),(0,b.jsxs)("div",{className:"wc-under-metrics",children:[null!=e.profile_matches&&(0,b.jsxs)("span",{children:["profile ",(0,b.jsxs)("b",{children:[e.profile_matches," prior matches"]})]}),null!=e.price&&(0,b.jsxs)("span",{children:["ask ",(0,b.jsxs)("b",{children:[(100*e.price).toFixed(1),"¢"]})]}),null!=e.spread&&(0,b.jsxs)("span",{children:["spread ",(0,b.jsxs)("b",{children:[(100*e.spread).toFixed(1),"¢"]})]}),null!=e.fill_usd&&(0,b.jsxs)("span",{className:"radar-up",children:["paper fill ",(0,b.jsxs)("b",{children:["$",e.fill_usd.toFixed(0)," @ ",(100*(e.fill_price||0)).toFixed(1),"¢"]})]})]}),(e.incoming||[]).length>0&&(0,b.jsx)("div",{className:"wc-under-metrics",children:(e.incoming||[]).map(e=>(0,b.jsxs)("span",{children:[(0,b.jsx)("b",{children:e.name})," · ",e.position," · ",e.history.appearances," apps · ",(100*e.history.start_rate).toFixed(0),"% starts · ",(100*e.history.contrib_rate).toFixed(0),"% G+A/app"]},e.name))}),(0,b.jsxs)("div",{className:"wc-under-thesis",children:[(0,b.jsx)("span",{children:"FORWARD"}),e.reason]})]},e.event_id)),(0,b.jsx)("div",{className:"wc-under-foot",children:"Why so few priced trades: 1,672 is the recent covered market universe, not the signal count. The original 55′–75′ / ≤75¢ slice was tiny. A separate 2025 reconstruction added 1,694 real favorite-priced matches and found 51/70 late goals in the robust 55′–64′ window, but historical O0.5 was not archived—so 70¢ is a sensitivity ceiling, not a claimed 2025 fill. This remains paper-only."})]}),"pm15m_updown"===t.config.strategy&&(x=G?.service,g=x?.config,f=G?.live,_=G?.research,j=Number(G?.window_min||g?.window_min||15),w=g?.entry_minutes&&g.entry_minutes.length?`${g.entry_minutes[0]}–${g.entry_minutes[g.entry_minutes.length-1]}`:5===j?"2–3":"3–7",N=G?.study_only?"STUDY · NOT LIVE":G?G.ledger_available?x?.stale?"SERVICE STALE":x?.live_enabled?"LIVE · vad1":"ORDERS OFF":"LEDGER OFFLINE":"NO STATE",(0,b.jsxs)("div",{className:"wc-under-agent",children:[(0,b.jsxs)("div",{className:"wc-under-agent-head",children:[(0,b.jsxs)("div",{children:[(0,b.jsxs)("span",{className:"wc-under-agent-kicker",children:["CRYPTO ",j,"M // ",(G?.asset||t.id.replace("paper:pm15m-","").replace("5m","")).toUpperCase()," UP-DOWN"]}),(0,b.jsxs)("b",{children:[" Polymarket ",j,"-minute momentum taker",G?.study_only?" · sizing study":5===j?" · canary":""]})]}),(0,b.jsx)("span",{className:`wc-under-paper${"LIVE · vad1"===N?" radar-up":""}`,children:N})]}),(0,b.jsxs)("div",{className:"wc-under-agent-note",children:["Rule B: at the first minute ",(0,b.jsx)("b",{children:w})," of the window where the move from the open is at least ",(0,b.jsxs)("b",{children:[Number(g?.z_min??2),"σ"]})," of what the last hour's one-minute volatility predicts for the time left, buy the favoured side as a FAK taker at ",(0,b.jsxs)("b",{children:["≤",Math.round(100*Number(g?.price_cap??.96)),"¢"]})," and hold to Chainlink settlement. ",(0,b.jsxs)("b",{children:["$",Number(g?.stake_usd??300)]})," per window, one position per window",g?.daily_loss_pause_usd?(0,b.jsxs)(b.Fragment,{children:[", pause after ",(0,b.jsxs)("b",{children:["$",Number(g.daily_loss_pause_usd)]})," lost in a day"]}):null,". Real orders come from the vad1 service;
8 the curve is seeded with ",_?.trades?`${_.trades.toLocaleString()} real Polymarket windows (${_.start_date} to ${_.end_date})`:"real Polymarket windows"," at $",Number(_?.stake_usd??g?.stake_usd??300),"."]}),(0,b.jsxs)("div",{className:"wc-under-metrics",children:[(0,b.jsxs)("span",{children:["wallet ",(0,b.jsx)("b",{children:x?.health?.balance_usd!=null?`$${Number(x.health.balance_usd).toLocaleString(void 0,{maximumFractionDigits:0})}`:"—"})]}),(0,b.jsxs)("span",{children:["last check ",(0,b.jsx)("b",{children:((e,t)=>{if(!e)return"—";let a=Math.max(0,Math.round(((t||Date.now())-e)/1e3));return a<90?`${a}s ago`:a<5400?`${Math.round(a/60)}m ago`:`${(a/3600).toFixed(1)}h ago`})(x?.last_evaluated_at_ms,e.server_ms)})]}),(0,b.jsxs)("span",{children:["windows evaluated ",(0,b.jsx)("b",{children:f?.signals_evaluated??0})]}),(0,b.jsxs)("span",{className:(f?.pnl_usd||0)>=0?"radar-up":"radar-down",children:["live ",(0,b.jsxs)("b",{children:[f?.wins??0,"W · ",f?.losses??0,"L · ",rj(f?.pnl_usd,2)]}),f?.open?` \xb7 ${f.open} open`:""]}),(0,b.jsxs)("span",{children:["today ",(0,b.jsxs)("b",{children:[f?.today_trades??0," trades · ",rj(f?.today_pnl_usd,2)]})]}),_?.trades!=null&&(0,b.jsxs)("span",{children:["year seed ",(0,b.jsxs)("b",{children:[_.wins??0,"/",_.trades," · ",rj(_.pnl_usd)," · maxDD $",Math.round(_.max_drawdown_usd||0)]})]}),_?.loss_rate!=null&&(0,b.jsxs)("span",{children:["loss rate ",(0,b.jsxs)("b",{children:[(100*Number(_.loss_rate)).toFixed(1),"%"]})," vs break-even ",(0,b.jsxs)("b",{children:[(100*Number(_.break_even_loss_rate||0)).toFixed(1),"%"]})]})]}),0===(G?.signals||[]).length&&(0,b.jsx)("div",{className:"wc-under-empty",children:G?.study_only?"Nothing trades this card. It replays the live BTC 15m signals with price-tiered sizing so the curve can be compared before any live change.":G?.ledger_available?"No window evaluated yet.":G?.ledger_error||"The live ledger is not readable from this API host; showing the seed only."}),(G?.signals||[]).map(e=>{let[t,a]="filled"===e.execution?null==e.won?["build","OPEN"]:e.won?["add","WON"]:["exit","LOST"]:e.execution?["invalid",String(e.execution).replace(/_/g," ").toUpperCase()]:["wait","below_z"===e.skip?"NO SIGNAL":(e.skip||"skip").replace(/_/g," ").toUpperCase()];return(0,b.jsxs)("div",{className:"wc-under-row",children:[(0,b.jsxs)("div",{className:"wc-under-row-main",children:[(0,b.jsx)("span",{className:`wc-under-state s-${t}`,children:a}),(0,b.jsx)("b",{children:e.name}),(0,b.jsxs)("span",{className:"wc-power-sub",children:["minute ",e.minute," · z ",e.z.toFixed(2)," · ",e.side||"—"," ",e.move_bps>=0?"+":"",e.move_bps.toFixed(1)," bps · checked ",ry(e.evaluated_at_ms)]})]}),(0,b.jsxs)("div",{className:"wc-under-metrics",children:[null!=e.best_ask&&(0,b.jsxs)("span",{children:["ask ",(0,b.jsxs)("b",{children:[Math.round(100*Number(e.best_ask)),"¢"]})]}),null!=e.depth_usd_at_cap&&(0,b.jsxs)("span",{children:["depth at cap ",(0,b.jsxs)("b",{children:["$",Number(e.depth_usd_at_cap).toLocaleString(void 0,{maximumFractionDigits:0})]})]}),"filled"===e.execution&&(0,b.jsxs)("span",{className:"radar-up",children:["filled ",(0,b.jsxs)("b",{children:["$",Number(e.cost_usd||0).toFixed(0)," @ ",(100*Number(e.avg_price||0)).toFixed(1),"¢"]})]}),null!=e.won&&(0,b.jsxs)("span",{className:e.won?"radar-up":"radar-down",children:[e.won?"won":"lost"," ",(0,b.jsx)("b",{children:rj(e.pnl,2)})]})]})]},e.id)}),(G?.events||[]).length>0&&(0,b.jsxs)("div",{className:"wc-under-foot",children:["Service log: ",(G?.events||[]).slice(0,6).map(e=>`${ry(e.at_ms)} ${(e.kind||"").replace(/_/g," ")}${e.summary?` — ${e.summary}`:""}`).join(" · ")]}),(0,b.jsx)("div",{className:"wc-under-foot",children:G?.note||"Orders are placed by the openpoly-pm15m-live service on the vad1 wallet; this card only mirrors its ledger."})]})),"us391_under_copy"===t.config.strategy&&(0,b.jsxs)("div",{className:"wc-under-agent",children:[(0,b.jsxs)("div",{className:"wc-under-agent-head",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{className:"wc-under-agent-kicker",children:"US391 COPY // LIVE FAK"}),(0,b.jsx)("b",{children:" Proportional Under mirror"})]}),(0,b.jsx)("span",{className:"wc-under-paper",children:"LIVE FUNDS"})]}),(0,b.jsxs)("div",{className:"wc-under-agent-note",children:["Watches ",(0,b.jsx)("b",{children:$?.source_wallet?`${$.source_wallet.slice(0,6)}…${$.source_wallet.slice(-4)}`:"US391"})," every second using pending mempool observations with Data API reconciliation. Fragmented fills are mirrored cumulatively at ",(0,b.jsxs)("b",{children:[(100*Number($?.settings?.size_ratio??k.copy_size_ratio??.1)).toFixed(0),"%"]}),", then capped by ",(0,b.jsxs)("b",{children:[(100*Number($?.settings?.bankroll_fraction??k.copy_bankroll_fraction??.02)).toFixed(0),"% wallet equity"]}),", ",(0,b.jsxs)("b",{children:["$",Number($?.settings?.maximum_stake_usd??k.copy_max_stake_usd??500).toFixed(0)]}),", cash, and executable depth."]}),$?.blocked&&(0,b.jsx)("div",{className:"wc-under-blocked",children:$.blocked}),$?.api_ok===!1&&(0,b.jsx)("div",{className:"wc-under-blocked",children:$.mempool_
8connected?`${$.api_error||"Polymarket Data API reconciliation is unavailable"}; pending mempool detection remains active.`:$.api_error||"Polymarket source tape and pending feed are unavailable; no copy decisions are being made."}),(0,b.jsxs)("div",{className:"wc-under-metrics",children:[(0,b.jsxs)("span",{children:["source fills ",(0,b.jsx)("b",{children:$?.stats?.ingested||0})]}),(0,b.jsxs)("span",{children:["pending fills ",(0,b.jsx)("b",{children:$?.stats?.mempool_ingested||0})]}),(0,b.jsxs)("span",{className:"radar-up",children:["copied ",(0,b.jsx)("b",{children:$?.stats?.copied||0})]}),(0,b.jsxs)("span",{children:["pending exchange ",(0,b.jsx)("b",{children:$?.stats?.submitted||0})]}),(0,b.jsxs)("span",{children:["filtered ",(0,b.jsx)("b",{children:$?.stats?.skipped||0})]}),(0,b.jsxs)("span",{children:["mirrored exits ",(0,b.jsx)("b",{children:$?.stats?.exited||0})]}),$?.last_api_ok_ms&&(0,b.jsxs)("span",{children:["tape ",(0,b.jsx)("b",{children:U($.last_api_ok_ms)})]})]}),0===($?.queue||[]).length&&(0,b.jsx)("div",{className:"wc-under-empty",children:t.enabled?"Watching US391 for a new soccer match-total Under burst with live funds.":"Turn this live copier ON to follow future qualifying fills."}),($?.queue||[]).map(e=>(0,b.jsxs)("div",{className:"wc-under-row",children:[(0,b.jsxs)("div",{className:"wc-under-row-main",children:[(0,b.jsx)("span",{className:`wc-under-state s-${e.state.toLowerCase()}`,children:e.state}),(0,b.jsx)("b",{children:e.title}),(0,b.jsxs)("span",{className:"wc-under-line",children:["U",e.line]})]}),(0,b.jsxs)("div",{className:"wc-under-metrics",children:[(0,b.jsxs)("span",{children:["source ",(0,b.jsxs)("b",{children:["$",e.source_usd.toLocaleString(void 0,{maximumFractionDigits:0})," @ ",(100*e.source_average).toFixed(1),"¢"]})]}),(e.hedge_usd||0)>0&&(0,b.jsxs)("span",{children:["Over hedge ",(0,b.jsxs)("b",{children:["$",Number(e.hedge_usd).toLocaleString(void 0,{maximumFractionDigits:0})]})]}),null!=e.price&&(0,b.jsxs)("span",{children:["copy ask ",(0,b.jsxs)("b",{children:[(100*e.price).toFixed(1),"¢"]})]}),null!=e.spread&&(0,b.jsxs)("span",{children:["spread ",(0,b.jsxs)("b",{children:[(100*e.spread).toFixed(1),"¢"]})]}),null!=e.target_usd&&e.target_usd>0&&(0,b.jsxs)("span",{children:["target ",(0,b.jsxs)("b",{children:["$",e.target_usd.toFixed(0)]})]}),null!=e.wallet_equity&&(0,b.jsxs)("span",{children:["wallet equity ",(0,b.jsxs)("b",{children:["$",e.wallet_equity.toLocaleString(void 0,{maximumFractionDigits:0})]})]}),null!=e.fill_usd&&(0,b.jsxs)("span",{className:"radar-up",children:["live fill ",(0,b.jsxs)("b",{children:["$",e.fill_usd.toFixed(0)," @ ",(100*(e.fill_price||0)).toFixed(1),"¢"]})]}),e.last_activity_ms&&(0,b.jsxs)("span",{children:["source move ",(0,b.jsx)("b",{children:U(e.last_activity_ms)})]})]}),(0,b.jsxs)("div",{className:"wc-under-thesis",children:[(0,b.jsx)("span",{children:"US391"}),e.reason]})]},e.condition_id)),(0,b.jsx)("div",{className:"wc-under-foot",children:"The source decides the exact market and timing. A durable reservation is written before every FAK, so delayed or unknown exchange acknowledgements are reconciled from the wallet and never blindly resubmitted. Material source sells or Over flips mirror out only when the copier can prove it will not touch manual inventory."})]}),"rollobravado_moneyline_copy"===t.config.strategy&&(0,b.jsxs)("div",{className:"wc-under-agent",children:[(0,b.jsxs)("div",{className:"wc-under-agent-head",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{className:"wc-under-agent-kicker",children:"ROLLO COPY // LIVE FAK"}),(0,b.jsx)("b",{children:" Proportional moneyline-NO mirror"})]}),(0,b.jsx)("span",{className:"wc-under-paper",children:"LIVE FUNDS"})]}),(0,b.jsxs)("div",{className:"wc-under-agent-note",children:["Watches ",(0,b.jsx)("b",{children:$?.source_wallet?`${$.source_wallet.slice(0,6)}…${$.source_wallet.slice(-4)}`:"RolloBravado"})," for named-team moneyline NO positions that originate before kickoff. It continuously targets exactly ",(0,b.jsxs)("b",{children:[(100*Number($?.settings?.size_ratio??k.copy_size_ratio??.02)).toFixed(1),"%"]})," of each source position—including later live additions and reductions—with no source, order, market, portfolio, equity, or daily sizing cap. Wallet cash, exchange minimums, executable depth, and price-quality rails are the only constraints."]}),$?.blocked&&(0,b.jsx)("div",{className:"wc-under-blocked",children:$.blocked}),$?.api_ok===!1&&(0,b.jsx)("div",{className:"wc-under-blocked",children:$.mempool_
8connected?`${$.api_error||"Polymarket Data API reconciliation is unavailable"}; pending mempool detection remains active.`:$.api_error||"Polymarket source tape and pending feed are unavailable; no copy decisions are being made."}),(0,b.jsxs)("div",{className:"wc-under-metrics",children:[(0,b.jsxs)("span",{children:["source fills ",(0,b.jsx)("b",{children:$?.stats?.ingested||0})]}),(0,b.jsxs)("span",{children:["pending fills ",(0,b.jsx)("b",{children:$?.stats?.mempool_ingested||0})]}),(0,b.jsxs)("span",{className:"radar-up",children:["copied ",(0,b.jsx)("b",{children:$?.stats?.copied||0})]}),(0,b.jsxs)("span",{children:["pending exchange ",(0,b.jsx)("b",{children:$?.stats?.submitted||0})]}),(0,b.jsxs)("span",{children:["filtered ",(0,b.jsx)("b",{children:$?.stats?.skipped||0})]}),(0,b.jsxs)("span",{children:["mirrored exits ",(0,b.jsx)("b",{children:$?.stats?.exits||0})]}),$?.last_api_ok_ms&&(0,b.jsxs)("span",{children:["tape ",(0,b.jsx)("b",{children:U($.last_api_ok_ms)})]})]}),0===($?.queue||[]).length&&(0,b.jsx)("div",{className:"wc-under-empty",children:t.enabled?"Watching RolloBravado for new and expanded prematch-origin soccer moneyline-NO positions.":"Turn this live copier ON to follow future qualifying fills."}),($?.queue||[]).map(e=>(0,b.jsxs)("div",{className:"wc-under-row",children:[(0,b.jsxs)("div",{className:"wc-under-row-main",children:[(0,b.jsx)("span",{className:`wc-under-state s-${e.state.toLowerCase()}`,children:e.state}),(0,b.jsx)("b",{children:e.title}),(0,b.jsx)("span",{className:"wc-under-line",children:"NO"})]}),(0,b.jsxs)("div",{className:"wc-under-metrics",children:[(0,b.jsxs)("span",{children:["source ",(0,b.jsxs)("b",{children:["$",e.source_usd.toLocaleString(void 0,{maximumFractionDigits:0})," @ ",(100*e.source_average).toFixed(1),"¢"]})]}
8),null!=e.source_open_usd&&e.source_open_usd<e.source_usd&&(0,b.jsxs)("span",{children:["estimated still open ",(0,b.jsxs)("b",{children:["$",e.source_open_usd.toLocaleString(void 0,{maximumFractionDigits:0})]})]}),null!=e.price&&(0,b.jsxs)("span",{children:["copy ask ",(0,b.jsxs)("b",{children:[(100*e.price).toFixed(1),"¢"]})]}),null!=e.spread&&(0,b.jsxs)("span",{children:["spread ",(0,b.jsxs)("b",{children:[(100*e.spread).toFixed(1),"¢"]})]}),null!=e.allowed_slippage&&(0,b.jsxs)("span",{children:["tier allowance ",(0,b.jsxs)("b",{children:["+",(100*e.allowed_slippage).toFixed(0),"¢"]})]}),null!=e.price_cap&&(0,b.jsxs)("span",{children:["hard price ceiling ",(0,b.jsxs)("b",{children:[(100*e.price_cap).toFixed(1),"¢"]})]}),null!=e.target_usd&&e.target_usd>0&&(0,b.jsxs)("span",{children:["target ",(0,b.jsxs)("b",{children:["$",e.target_usd.toFixed(0)]})]}),null!=e.copied_usd&&e.copied_usd>0&&(0,b.jsxs)("span",{children:["copied exposure ",(0,b.jsxs)("b",{children:["$",e.copied_usd.toFixed(0)]})]}),null!=e.source_sell_ratio&&e.source_sell_ratio>0&&(0,b.jsxs)("span",{children:["source sold ",(0,b.jsxs)("b",{children:[(100*e.source_sell_ratio).toFixed(0),"%"]})]}),null!=e.fill_usd&&(0,b.jsxs)("span",{className:"radar-up",children:["live fill ",(0,b.jsxs)("b",{children:["$",e.fill_usd.toFixed(0)," @ ",(100*(e.fill_price||0)).toFixed(1),"¢"]})]}),e.last_activity_ms&&(0,b.jsxs)("span",{children:["source move ",(0,b.jsx)("b",{children:U(e.last_activity_ms)})]})]}),(0,b.jsxs)("div",{className:"wc-under-thesis",children:[(0,b.jsx)("span",{children:"ROLLO"}),e.reason]})]},e.condition_id)),(0,b.jsx)("div",{className:"wc-under-foot",children:"Pending RPC fills are acted on quickly, then reconciled to the authoritative activity tape. A position must originate prematch, but every later source add is eligible. Every nonzero source reduction is mirrored proportionally when the ledger proves no manual shares can be touched."})]}),("over05_baseline"===t.config.strategy||"over05_defensive"===t.config.strategy||"over05_ai"===t.config.strategy||"over05_ai_continuous"===t.config.strategy)&&(0,b.jsxs)("div",{className:"wc-under-agent",children:[(0,b.jsxs)("div",{className:"wc-under-agent-head",children:[(0,b.jsxs)("div",{children:[(0,b.jsxs)("span",{className:"wc-under-agent-kicker",children:["GOALPILOT // ","live"===t.mode?"LIVE CANARY":ea?"ONE-SHOT 49":"over05_ai_continuous"===t.config.strategy?"AI-CONTINUOUS":"over05_ai"===t.config.strategy?"AI-ARMED":"over05_defensive"===t.config.strategy?"DEFENSIVE EXIT":"PRICE BASELINE"]}),(0,b.jsxs)("b",{children:[" Full-match ",et?"Over 0.5 / 1.5 / 2.5":"Over 0.5"," ","live"===t.mode?"wallet execution":"forward paper"]})]}),(0,b.jsx)("span",{className:"wc-under-paper",children:"live"===t.mode?"LIVE FUNDS":"PAPER ONLY"})]}),(0,b.jsxs)("div",{className:"wc-under-agent-note",children:[et?"Each unresolved line needs its own fresh AI read at the current score":"0-0 only"," · ",ea?`takes the first executable entry from ${L?.start_minute??k.over05_start_minute??20}′–${L?.end_minute??k.over05_end_minute??49}′ and permanently disables later adds`:"over05_ai_continuous"===t.config.strategy?"attempts the first fill immediately when armed and watches every GoalPilot scan for entries/adds":"opens 20′, 30′, …, 80′ entry windows and retries thin/expensive books inside each window"," · buys at or below ",((L?.max_price??k.over05_max_price??.85)*100).toFixed(0),"¢ · up to ",L?.max_tranches??k.over05_max_tranches??3," ",ea?"entry":"tranches"," ",et?"per line":"per match"," of $",(L?.tranche_usd??(k.over05_match_cap_usd??1e3)/(k.over05_max_tranches??3)).toFixed(0)," · maximum $",es.toFixed(0)," ",et?`per line ($${er.toFixed(0)} maximum across all three research buckets)`:"per match",".","live"===t.mode?` Uses the trading widget’s signer, order classifier and exchange verification. Ambiguous submissions reserve exposure and are never automatically resubmitted. There is no daily deployment cap; concurrent matches are ${Number(k.over05_max_matches??0)>0?`capped at ${Number(k.over05_max_matches)}`:"unlimited"}, and new entries stop after −$${ep.toFixed(0)} since the UTC day began or the latest manual resume.`:ea?` This isolated hold-to-resolution challenger uses ${((L?.trap_price??k.over05_trap_price??.62)*100).toFixed(0)}\xa2 cagey / ${((L?.max_price??k.over05_max_price??.7)*100).toFixed(0)}\xa2 normal / ${((L?.open_price??k.over05_open_price??.74)*100).toFixed(0)}
8\xa2 goal-happy ceilings. Partial fills spend the campaign: no healing order is allowed.`:"over05_ai_continuous"===t.config.strategy?` Uses the exact AI-Armed line selector and risk rails. Only execution differs: no global checkpoints; same-line adds still require seven match minutes, five wall-clock minutes, and a 1\xa2 better ask.${L?.comparison_started_ms?` Forward A/B recorder started ${U(L.comparison_started_ms)}.`:""}`:"over05_ai"===t.config.strategy?" AI arms O0.5, O1.5, or O2.5 only after a fresh line-specific activity read and qualifying point-in-time scoring/conceding form; stale pre-goal reads cannot arm a new score state.":"over05_defensive"===t.config.strategy?` At ${L?.exit_minute??k.over05_exit_minute??75}′ it sells only available depth when the match is still 0-0 and the best bid is ≤${((L?.exit_max_bid??k.over05_exit_max_bid??.5)*100).toFixed(0)}\xa2; no profit-taking, and a triggered exit blocks later adds.`:" No AI, team-form, narration, model filter, or early exit is used in this hold-to-resolution control cohort."]}),0===(L?.matches||[]).length&&(0,b.jsx)("div",{className:"wc-under-empty",children:t.enabled?"Waiting for an eligible live match and totals line.":`Turn this ${t.mode} agent ON to start.`}),(L?.matches||[]).map(e=>(0,b.jsxs)("div",{className:"wc-under-row",children:[(0,b.jsxs)("div",{className:"wc-under-row-main",children:[(0,b.jsx)("span",{className:`wc-under-state s-${e.state.toLowerCase()}`,children:e.state}),(0,b.jsx)("b",{children:e.match}),(0,b.jsxs)("span",{className:"wc-power-sub",children:[e.minute,"' · ",e.score,"continuous"===e.execution?" · continuous watch":null!=e.checkpoint?` \xb7 ${e.checkpoint}′ checkpoint`:""]}),(0,b.jsxs)("span",{className:"wc-under-line",children:["O",e.line??.5]})]}),(0,b.jsxs)("div",{className:"wc-under-metrics",children:[null!=e.price&&(0,b.jsxs)("span",{children:["ask ",(0,b.jsxs)("b",{children:[(100*e.price).toFixed(1),"¢"]})]}),null!=e.spread&&(0,b.jsxs)("span",{children:["spread ",(0,b.jsxs)("b",{children:[(100*e.spread).toFixed(1),"¢"]})]}),null!=e.position_usd&&e.position_usd>0&&(0,b.jsxs)("span",{className:"radar-up",children:["held ",(0,b.jsxs)("b",{children:["$",e.position_usd.toFixed(0)," · ",e.position_legs||1," tranche",1===(e.position_legs||1)?"":"s"]})]}),null!=e.fill_usd&&(0,b.jsxs)("span",{className:"radar-up",children:["live"===t.mode?"live order":"paper fill"," ",(0,b.jsxs)("b",{children:["$",e.fill_usd.toFixed(0)," @ ",(100*(e.fill_price||0)).toFixed(1),"¢"]})]})]}),(0,b.jsxs)("div",{className:"wc-under-thesis",children:[(0,b.jsx)("span",{children:L?.cohort||"FORWARD"}),e.reason]})]},e.view_id||`${e.event_id}:O${e.line??.5}`))]}),"under_ai"===t.config.strategy&&(0,b.jsxs)("div",{className:"wc-bot-adv wc-under-controls",children:[(0,b.jsxs)("div",{className:"wc-under-rails-intro",children:[(0,b.jsx)("b",{children:"Execution rails—not trading logic."})," They never decide whether a match is toothless or which line is best; they only cap how much the AI may paper-deploy and reject bad books."]}),[["under_max_matches","max matches monitored/traded",1,"Maximum live soccer matches analyzed every five minutes and after material events across all leagues. There is no separate open-position count cap."],["under_probe_usd","$ / riskier starter",5,"Small first position, normally the U3.5 leg after safer lines are established."],["under_entry_max_usd","max $ / first build",5,"AI may request $200 for a standard build or up to this amount for the safest first-half line."],["under_add_usd","max $ / top-up",5,"Hard cap on each later add. The AI must identify a new price, checkpoint, score-state, or evidence update."],["under_soft_match_cap_usd","normal target $ / match",25,"Normal portfolio target. Only a high-confidence add to an existing line may cross it."],["per_match_cap_usd","absolute max $ / match",25,"Hard exposure ceiling across every Under line in the match."],["daily_max_loss_usd","daily/session loss stop",25,"Halts new entries once the session's realized P&L falls this far below zero, and shrinks position sizes as it approaches the limit. 0 disables the stop."],["under_trim_fraction","partial trim fraction",.05,"Fraction sold when the AI calls trim_under. 0.50 sells half; exit_under still sells all."],["under_max_price","highest acceptable ask",.01,"Reject buying an Under token above this price. 0.90 means never pay more than 90¢."],["under_max_spread","widest acceptable spread",.01,"Reject illiquid books whose Under ask minus bid exceeds this amount. 0.08 means 8¢."],["under_max_chase","max depth chase",.01,"Maximum price paid above the current best ask while walking depth. 0.03 means never chase more than 3¢."],["under_min_edge","legacy model edge veto",.01,"Optional execution veto: model fair minus ask must clear this value. -1 disables it so AI reasoning stays authoritative."]].map(([e,a,s,r])=>(0,b.jsxs)("label",{className:"wc-bot-field wc-under-rail-field",children:[(0,b.jsx)("span",{children:a}),(0,b.jsx)("input",{type:"number",step:s,value:k[e]??0,onChange:a=>n(s=>({...s,[t.id]:{...k,[e]:+a.target.value}}))}),(0,b.jsx)("small",{children:r})]},e)),(0,b.jsxs)("label",{className:"wc-bot-field wc-under-rail-field",children:[(0,b.jsx)("span",{children:"minimum AI conviction"}),(0,b.jsxs)("select",{value:k.under_min_confidence||"medium",onChange:e=>n(a=>({...a,[t.id]:{...k,under_min_confidence:e.target.value}})),children:[(0,b.jsx)("option",{value:"medium",children:"medium+"}),(0,b.jsx)("option",{value:"high",children:"high only"})]}),(0,b.jsx)("small",{children:"Blocks AI reads below this self-reported evidence quality. Medium+ currently excludes the low-confidence probes that were weakest historically."})]}),(0,b.jsxs)("div",{className:"wc-under-sizing-summary",children:["Trader-style ladder: never opens the active one-goal-away bucket · riskier starter ",(0,b.jsxs)("b",{children:["$",ei.toFixed(0)]})," · first build up to ",(0,b.jsxs)("b",{children:["$",eo.toFixed(0)]})," · each top-up capped at ",(0,b.jsxs)("b",{children:["$",ec.toFixed(0)]})," · normal target ",(0,b.jsxs)("b",{children:["$",ed.toFixed(0),"/match"]})," · absolute ceiling ",(0,b.jsxs)("b",{children:["$",en.toFixed(0),"/match"]})," · AI trim sells ",(0,b.jsxs)("b",{children:[eh.toFixed(0),"%"]}),". Multiple Under lines share the match ceiling; maximum simultaneous paper exposure is ",(0,b.jsxs)("b",{children:["$",(el*en).toFixed(0)]}),"."]}),(0,b.jsx)("button",{className:"wc-bot-apply",disabled:v===`adv:${t.id}`,onClick:()=>
8F(t),children:v===`adv:${t.id}`?"saving…":"Save risk rails"})]}),"live"===t.mode&&"over05_baseline"===t.config.strategy&&(0,b.jsxs)("div",{className:"wc-bot-adv wc-under-controls",children:[(0,b.jsxs)("div",{className:"wc-under-rails-intro",children:[(0,b.jsx)("b",{children:"Live GoalPilot rails."})," The O0.5 price-only strategy remains unchanged. You control its match sizing, tranche schedule, entry window, order-book tolerance, concurrent exposure, and loss stop."]}),(0,b.jsxs)("div",{className:"wc-under-sizing-summary",children:["Match cap ",(0,b.jsxs)("b",{children:["$",Number(k.over05_match_cap_usd??250).toFixed(0)]})," · first buy ",(0,b.jsxs)("b",{children:["$",(Number(k.over05_match_cap_usd??250)/(Math.max(1,Number(k.over05_max_tranches??5))-1+Math.max(1,Number(k.over05_first_tranche_mult??1)))*Math.max(1,Number(k.over05_first_tranche_mult??1))).toFixed(0)]})," then ",(0,b.jsx)("b",{children:Math.max(0,Number(k.over05_max_tranches??5)-1)})," × ",(0,b.jsxs)("b",{children:["$",(Number(k.over05_match_cap_usd??250)/(Math.max(1,Number(k.over05_max_tranches??5))-1+Math.max(1,Number(k.over05_first_tranche_mult??1)))).toFixed(0)]})," · entry window ",(0,b.jsxs)("b",{children:[Number(k.over05_start_minute??20),"′–",Number(k.over05_end_minute??80),"′"]})," every ",(0,b.jsxs)("b",{children:[Number(k.over05_cadence_minutes??10)," minutes"]})," · price ceiling ",(0,b.jsxs)("b",{children:[(100*Number(k.over05_max_price??.85)).toFixed(0),"¢"]})," · concurrent matches ",(0,b.jsx)("b",{children:Number(k.over05_max_matches??0)>0?Number(k.over05_max_matches):"unlimited"})," · daily/session stop ",(0,b.jsxs)("b",{children:["−$",Number(k.daily_max_loss_usd??800).toFixed(0)]}),"."]}),(0,b.jsx)(rL,{title:"Live GoalPilot configuration",config:k,fields:rN,dirty:!!r[t.id],saving:v===`adv:${t.id}`,onChange:(e,a)=>n(s=>({...s,[t.id]:{...k,[e]:a}})),onReset:()=>n(e=>{let a={...e};return delete a[t.id],a}),onSave:()=>F(t)})]}),"late_tail_paper"===t.config.strategy&&(0,b.jsxs)("div",{className:"wc-bot-adv wc-under-controls",children:[(0,b.jsxs)("div",{className:"wc-under-rails-intro",children:[(0,b.jsx)("b",{children:"Paper only — measuring whether the price is reachable."})," Late in a match the market prices another goal off how many have already been scored, but a decided game goes quiet. Inside this window the under wins about half the time whatever the market charges, so the rule buys the cheapest one and holds to the whistle."]}),(0,b.jsxs)("div",{className:"wc-under-sizing-summary",children:["From ",(0,b.jsxs)("b",{children:[Number(k.late_tail_min_minute??70),"′"]})," to ",(0,b.jsxs)("b",{children:[Number(k.late_tail_max_minute??88),"′"]})," · at least ",(0,b.jsx)("b",{children:Number(k.late_tail_min_goals??2)})," goals scored · frontier under priced ",(0,b.jsxs)("b",{children:[(100*Number(k.late_tail_price_lo??.2)).toFixed(0),"¢–",(100*Number(k.late_tail_price_hi??.35)).toFixed(0),"¢"]})," · score confirmed by the book · ",(0,b.jsxs)("b",{children:["$",Number(k.late_tail_stake_usd??100).toFixed(0)]})," per match, one position each, held to the whistle. Entries are rare by design — the healthy books usually quote this line far above the band."]}),(0,b.jsx)(rL,{title:"Late-Tail Pilot configuration",config:k,fields:rk,dirty:!!r[t.id],saving:v===`adv:${t.id}`,onChange:(e,a)=>n(s=>({...s,[t.id]:{...k,[e]:a}})),onReset:()=>n(e=>{let a={...e};return delete a[t.id],a}),onSave:()=>F(t)})]}),"key_sub_over"===t.config.strategy&&(0,b.jsxs)("div",{className:"wc-bot-adv wc-under-controls",children:[(0,b.jsxs)("div",{className:"wc-under-rails-intro",children:[(0,b.jsx)("b",{children:"Forward-research rails."})," Defaults reproduce the focused historical cohort; changing them creates a new forward policy rather than proving a larger historical edge."]}),(0,b.jsxs)("div",{className:"wc-under-sizing-summary",children:["0-0 market favorite only · substitution ",(0,b.jsxs)("b",{children:[Number(k.key_sub_min_minute??55),"′–",Number(k.key_sub_max_minute??64),"′"]})," · O0.5 ≤",(0,b.jsxs)("b",{children:[(100*Number(k.key_sub_max_price??.7)).toFixed(0),"¢"]})," · ",(0,b.jsxs)("b",{children:["$",Number(k.key_sub_stake_usd??100).toFixed(0)]})," maximum paper cost · one entry per match · holds to resolution."]}),(0,b.jsx)(rL,{title:"KeySub paper configuration",config:k,fields:rS,dirty:!!r[t.id],saving:v===`adv:${t.id}
8`,onChange:(e,a)=>n(s=>({...s,[t.id]:{...k,[e]:a}})),onReset:()=>n(e=>{let a={...e};return delete a[t.id],a}),onSave:()=>F(t)})]}),"favorite_no_fade"===t.config.strategy&&(0,b.jsxs)("div",{className:"wc-bot-adv wc-under-controls",children:[(0,b.jsxs)("div",{className:"wc-under-rails-intro",children:[(0,b.jsx)("b",{children:"Validated paper rails."})," Changing any boundary starts a new cohort and must not be mixed with the audited default."]}),(0,b.jsxs)("div",{className:"wc-under-sizing-summary",children:[(0,b.jsxs)("b",{children:["$",Number(k.ml_no_stake_usd??50).toFixed(0)]})," direct-NO stake · favorite ",(0,b.jsxs)("b",{children:[(100*Number(k.ml_no_min_favorite??.55)).toFixed(0),"–",(100*Number(k.ml_no_max_favorite??.7)).toFixed(0),"%"]})," · NO ",(0,b.jsxs)("b",{children:[(100*Number(k.ml_no_min_price??.5)).toFixed(0),"–",(100*Number(k.ml_no_max_price??.7)).toFixed(0),"¢"]})," · spread ≤",(0,b.jsxs)("b",{children:[(100*Number(k.ml_no_max_spread??.02)).toFixed(1),"¢"]})," · hold to settlement."]}),(0,b.jsx)(rL,{title:"Favorite-NO fade paper configuration",config:k,fields:r$,dirty:!!r[t.id],saving:v===`adv:${t.id}`,onChange:(e,a)=>n(s=>({...s,[t.id]:{...k,[e]:a}})),onReset:()=>n(e=>{let a={...e};return delete a[t.id],a}),onSave:()=>F(t)})]}),["first_goal_no_fomo","first_goal_no_risk"].includes(t.config.strategy||"")&&(0,b.jsxs)("div",{className:"wc-bot-adv wc-under-controls",children:[(0,b.jsx)("div",{className:"wc-under-rails-intro",children:Z?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)("b",{children:"Live canary controls."})," Every risk and timing rail below is editable. Execution remains a fee-aware bounded taker order so the short post-goal window cannot leave a stale passive bid behind."]}):(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)("b",{children:"Forward paper rails."})," Defaults preserve the leakage-safe historical cohort. Any boundary change creates a separate forward experiment and does not inherit the displayed backtest."]})}),(0,b.jsxs)("div",{className:"wc-under-sizing-summary",children:[(0,b.jsxs)("b",{children:["$",Number(k.fomo_no_stake_usd??(Z?100:400)).toFixed(0)]})," direct-NO stake · first goal ",(0,b.jsxs)("b",{children:[Number(k.fomo_no_min_minute??10),"′–",Number(k.fomo_no_max_minute??29),"′"]})," · wait ",(0,b.jsxs)("b",{children:[Number(k.fomo_no_min_goal_age_seconds??120),"–",Number(k.fomo_no_max_goal_age_seconds??240),"s"]})," · NO ",(0,b.jsxs)("b",{children:[(100*Number(k.fomo_no_min_price??.1)).toFixed(0),"–",(100*Number(k.fomo_no_max_price??.25)).toFixed(0),"¢"]})," · compression ",(0,b.jsxs)("b",{children:[(100*Number(k.fomo_no_min_compression??.3)).toFixed(0),"–",(100*Number(k.fomo_no_max_compression??.7)).toFixed(0),"%"]})," · ",X?(0,b.jsxs)(b.Fragment,{children:["full target / ",(100*Number(k.fomo_no_stop_multiple??.5)).toFixed(0),"% stop inside ",(0,b.jsxs)("b",{children:[Number(k.fomo_no_recovery_window_seconds??300)/60,"m"]}),", then settlement hold."]}):(0,b.jsxs)(b.Fragment,{children:["recover principal inside ",(0,b.jsxs)("b",{children:[Number(k.fomo_no_recovery_window_seconds??300)/60,"m"]}),", then hold the free runner."]})," ",Z&&(0,b.jsxs)(b.Fragment,{children:["· ",(0,b.jsx)("b",{children:"bounded taker"})," · daily stop ",(0,b.jsx)("b",{children:Number(k.daily_max_loss_usd??150)>0?`−$${Number(k.daily_max_loss_usd??150).toFixed(0)}`:"off"})]})]}),(0,b.jsx)(rL,{title:Z?"Live FOMO risk-router configuration":X?"First-goal FOMO risk-router configuration":"First-goal FOMO fade configuration",config:k,fields:Z?rE:X?rM:rC,dirty:!!r[t.id],saving:v===`adv:${t.id}`,onChange:(e,a)=>n(s=>({...s,[t.id]:{...k,[e]:a}})),onReset:()=>n(e=>{let a={...e};return delete a[t.id],a}),onSave:()=>F(t)})]}),"us391_under_copy"===t.config.strategy&&(0,b.jsxs)("div",{className:"wc-bot-adv wc-under-controls",children:[(0,b.jsxs)("div",{className:"wc-under-rails-intro",children:[(0,b.jsx)("b",{children:"Live execution rails."})," US391 chooses the exact market, side, and timing. You control sizing, portfolio exposure, price tolerance, liquidity, retries, hedge vetoes, and exit mirroring below."]}),(0,b.jsxs)("div",{className:"wc-under-sizing-summary",children:["No source-size or order-size floor · target ",(0,b.jsxs)("b",{children:[(100*Number(k.copy_size_ratio??.1)).toFixed(1),"%"]})," of cumulative source fills · per-market cap ",(0,b.jsxs)("b",{children:["$",Number(k.copy_max_stake_usd??500).toFixed(0)]})," · total-open cap ",(0,b.jsxs)("b",{children:["$",Number(k.copy_max_open_exp
8osure_usd??1e3).toLocaleString()]})," · equity cap ",(0,b.jsxs)("b",{children:[(100*Number(k.copy_bankroll_fraction??.02)).toFixed(1),"%"]})," · daily/session stop ",(0,b.jsxs)("b",{children:["−$",Number(k.daily_max_loss_usd??500).toFixed(0)]}),"."]}),(0,b.jsx)(rL,{title:"Live US391 copier configuration",config:k,fields:rA,dirty:!!r[t.id],saving:v===`adv:${t.id}`,onChange:(e,a)=>n(s=>({...s,[t.id]:{...k,[e]:a}})),onMirrorChange:e=>n(a=>({...a,[t.id]:{...k,copy_mirror_exits:e}})),onReset:()=>n(e=>{let a={...e};return delete a[t.id],a}),onSave:()=>F(t)})]}),"rollobravado_moneyline_copy"===t.config.strategy&&(0,b.jsxs)("div",{className:"wc-bot-adv wc-under-controls",children:[(0,b.jsxs)("div",{className:"wc-under-rails-intro",children:[(0,b.jsx)("b",{children:"True proportional mode."})," Rollo chooses the named team and NO side. The copier continuously matches the configured percentage of every prematch-origin position; only execution-quality settings remain adjustable."]}),(0,b.jsxs)("div",{className:"wc-under-sizing-summary",children:["Exact target ",(0,b.jsxs)("b",{children:[(100*Number(k.copy_size_ratio??.02)).toFixed(1),"%"]})," of source open cost · later live additions included · all source reductions mirrored · no application sizing caps or entry floors · limited only by wallet cash and executable exchange liquidity."]}),(0,b.jsx)(rL,{title:"Live Rollo copier configuration",config:k,fields:rT,dirty:!!r[t.id],saving:v===`adv:${t.id}`,onChange:(e,a)=>n(s=>({...s,[t.id]:{...k,[e]:a}})),continuousSizing:!0,onReset:()=>n(e=>{let a={...e};return delete a[t.id],a}),onSave:()=>F(t)})]}),t.open_positions.length>0&&(0,b.jsxs)("div",{className:"wc-bot-led",children:[(0,b.jsxs)("div",{className:"wc-bot-pos-label",children:["open ",t.mode," positions"]}),(0,b.jsxs)("table",{className:"wc-bot-pos",children:[(0,b.jsx)("thead",{children:(0,b.jsxs)("tr",{children:[(0,b.jsx)("th",{children:"match"}),(0,b.jsx)("th",{children:"position"}),(0,b.jsx)("th",{children:"adds"}),(0,b.jsx)("th",{children:"shares"}),(0,b.jsx)("th",{children:"avg→live"}),(0,b.jsx)("th",{children:"P&L"})]})}),(0,b.jsx)("tbody",{children:t.open_positions.map((e,a)=>(0,b.jsxs)("tr",{children:[(0,b.jsx)("td",{className:"wc-power-sub",title:eg(e.event_id),children:eg(e.event_id)}),(0,b.jsx)("td",{children:rv(e,t.config.strategy)}),(0,b.jsx)("td",{children:e.legs}),(0,b.jsx)("td",{children:null!=e.shares?e.shares.toFixed(0):"—"}),(0,b.jsxs)("td",{children:[e.avg_entry?.toFixed(2),"→",e.live_price?.toFixed(2)]}),(0,b.jsxs)("td",{className:e.pnl>=0?"radar-up":"radar-down",children:[e.pnl>=0?"+":"","$",e.pnl.toFixed(0)]})]},a))})]})]}),o===t.id&&(()=>{let e=d[t.id];if(m[t.id])return(0,b.jsxs)("div",{className:"wc-ledger-error",children:["Couldn't load the execution ledger. ",(0,b.jsx)("button",{className:"wc-bot-log",onClick:()=>void C(t.id,!0,h[t.id]||0),children:"Retry now"})]});if(!e)return(0,b.jsxs)("div",{className:"wc-ledger-loading",children:[(0,b.jsx)("span",{className:"wc-bot-spin"})," Loading positions and fills…"]});let a=e.summary,s=t=>t&&e.match_names?.[t]||eg(t),r=Number(e.position_offset||0),n=Number(e.position_limit||500),l=Number(e.position_total||e.positions.length),i=Math.floor(r/n);return(0,b.jsxs)("div",{className:"wc-paper-ledger",children:[(0,b.jsxs)("div",{className:"wc-paper-ledger-head",children:[(0,b.jsxs)("div",{children:[(0,b.jsxs)("span",{className:"wc-under-agent-kicker",children:["live"===t.mode?"LIVE BOOK":"PAPER BOOK"," // FULL LEDGER"]}),(0,b.jsx)("b",{children:"Position history & execution log"})]}),(0,b.jsx)("button",{className:"wc-bot-log-close",onClick:()=>c(null),children:"hide ×"})]}),e.backtest_seed&&(0,b.jsx)("div",{className:"wc-under-foot",children:"pm15m_updown"===t.config.strategy?(0,b.jsxs)(b.Fragment,{children:["Real Polymarket windows: ",(0,b.jsxs)("b",{children:[e.backtest_seed.trades||0," windows"]})," from ",e.backtest_seed.start_date," to ",e.backtest_seed.end_date," at ",(0,b.jsxs)("b",{children:["$",Number(e.backtest_seed.stake_usd||300)]})," each, ",(0,b.jsxs)("b",{children:[e.backtest_seed.wins??"—","W · ",e.backtest_seed.losses??"—","L"]}),", ",(0,b.jsx)("b",{children:rj(e.backtest_seed.pnl_usd)})," after the 7% taker fee, max drawdown ",(0,b.jsxs)("b",{children:["$",Math.round(e.backtest_seed.max_drawdown_usd||0)]}),". ",e.backtest_seed.caveat]}):"key_sub_over"===t.config.strategy?(0,b.jsxs)(b.Fragment,{children:["Full-year outcome validation: ",(0,b.jsxs)("b",{children:[e.backtest_seed.validation?.outcome_only_trades||e.backtest_seed.trades||0," signals across ",e.backtest_seed.validation?.archive_matches_scanned||0," Polymarket-linked 2025 matches"]})," from ",e.backtest_seed.start_date," to ",e.backtest_seed.end_date,". The visible curve prices every signal at the worst allowed ",(0,b.jsxs)("b",{children:[(100*Number(e.backtest_seed.stress_entry||.7)).toFixed(0),"¢"]}),", including fees: ",(0,b.jsxs)("b",{children:[(100*Number(e.backtest_seed.validation?.outcome_only_win_rate||0)).toFixed(1),"% hit rate"]}),", ",(0,b.jsxs)("b",{children:[(100*Number(e.backtest_seed.roi||0)).toFixed(2),"% cap-stress ROI"]}),", ",(0,b.jsxs)("b",{children:["$",Number(e.backtest_seed.max_drawdown_usd||0).toFixed(0)," max drawdown"]}),". Chronological halves held at ",(0,b.jsxs)("b",{children:[(100*Number(e.backtest_seed.validation?.chronological_first_half_win_rate||0)).toFixed(1),"%"]})," and ",(0,b.jsxs)("b",{children:[(100*Number(e.backtest_seed.validation?.chronological_second_half_win_rate||0)).toFixed(1),"%"]}),". ",e.backtest_seed.validation?.recheck_trades?(0,b.jsxs)(b.Fragment,{children:["Fresh archive rerun with reduced provider coverage still found ",(0,b.jsxs)("b",{children:[e.backtest_seed.validation.recheck_wins,"/",e.backtest_seed.validation.recheck_trades," · ",(100*Number(e.backtest_seed.validation.recheck_win_rate||0)).toFixed(1),"%"]}),". "]}):null,"Separate exact-CLOB holdout: ",(0,b.jsxs)("b",{children:[e.backtest_seed.validation?.exact_clob_trades||0," trades, ",e.backtest_seed.validation?.exact_clob_wins||0," wins, ",(100*Number(e.backtest_seed.validation?.exact_clob_roi||0)).toFixed(2),"% ROI"]}),". ",e.backtest_seed.caveat]}):(0,b.jsxs)(b.Fragment,{children:["Historical seed: ",(0,b.jsxs)("b",{children:[e.backtest_seed.trades||0," positions across ",e.backtest_seed.matches||0," matches"]})," from ",e.backtest_seed.start_date," to ",e.backtest_seed.end_date,", normalized to ",(0,b.jsxs)("b",{children:["$",Number(e.backtest_seed.stake_usd||0).toFixed(0)," per ",e.backtest_seed.stake_basis||"match"]}),". These are backtest rows, not forward paper fills. ",e.backtest_seed.validation?.exact_timeline_matches?(0,b.jsxs)(b.Fragment,{children:[" Independent exact-clock check: ",(0,b.jsxs)("b",{children:[e.backtest_seed.validation.exact_timeline_matches," matches at ",(100*Number(e.backtest_seed.validation.exact_timeline_roi||0)).toFixed(2),"% ROI"]}),"; same-event reconstructed clocks produced ",(0,b.jsxs)("b",{children:[(100*Number(e.backtest_seed.validation.same_event_reconstructed_roi||0)).toFixed(2),"%"]}),". "]}):null,e.backtest_seed.caveat]})}),(0,b.jsxs)("div",{className:"wc-paper-ledger-stats",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{children:"realized P&L"}),(0,b.jsxs)("b",{className:a.realized_pnl>=0?"radar-up":"radar-down",children:[a.realized_pnl>=0?"+":"−","$",Math.abs(a.realized_pnl).toFixed(2)]})]}),(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{children:"record"}),(0,b.jsxs)("b",{children:[a.wins,"W · ",a.losses,"L"]})]}),(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{children:"closed positions"}),(0,b.jsx)("b",{children:a.closed})]}),(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{children:"capital recorded"}
8),(0,b.jsxs)("b",{children:["$",a.deployed_usd.toLocaleString(void 0,{maximumFractionDigits:0})]})]})]}),(0,b.jsxs)("details",{className:"wc-paper-ledger-section",open:!0,children:[(0,b.jsxs)("summary",{children:["All positions ",(0,b.jsx)("span",{children:l?`${r+1}–${Math.min(r+e.positions.length,l)} of ${l}`:"0 rows"})]}),l>n&&(0,b.jsxs)("div",{style:{display:"flex",alignItems:"center",justifyContent:"flex-end",gap:6,padding:"6px 8px 0"},children:[(0,b.jsx)("button",{className:"wc-bot-log",disabled:i<=0||v===`ledger:${t.id}`,onClick:()=>{let e=Math.max(0,i-1);p(a=>({...a,[t.id]:e})),C(t.id,!0,e)},children:"← newer 500"}),(0,b.jsxs)("span",{className:"wc-power-sub",children:["page ",i+1," / ",Math.ceil(l/n)]}),(0,b.jsx)("button",{className:"wc-bot-log",disabled:!e.has_more_positions||v===`ledger:${t.id}`,onClick:()=>{let e=i+1;p(a=>({...a,[t.id]:e})),C(t.id,!0,e)},children:"older 500 →"})]}),(0,b.jsx)("div",{className:"wc-paper-ledger-scroll",children:(0,b.jsxs)("table",{className:"wc-bot-pos wc-paper-ledger-table",children:[(0,b.jsx)("thead",{children:(0,b.jsxs)("tr",{children:[(0,b.jsx)("th",{children:"opened"}),(0,b.jsx)("th",{children:"match"}),(0,b.jsx)("th",{children:"position"}),(0,b.jsx)("th",{children:"status"}),(0,b.jsx)("th",{children:"stake"}),(0,b.jsx)("th",{children:"avg"}),(0,b.jsx)("th",{children:"P&L"})]})}),(0,b.jsx)("tbody",{children:e.positions.map((e,a)=>{let r=e.realized_pnl;return(0,b.jsxs)("tr",{children:[(0,b.jsx)("td",{className:"wc-power-sub",children:H(e.opened_ms)}),(0,b.jsx)("td",{title:s(e.event_id),children:s(e.event_id)}),(0,b.jsxs)("td",{children:[rv(e,t.config.strategy)," ",(0,b.jsxs)("span",{className:"wc-power-sub",children:["×",e.legs]})]}),(0,b.jsx)("td",{children:(0,b.jsx)("span",{className:`wc-ledger-status ${e.status||"open"}`,children:e.status||"open"})}),(0,b.jsxs)("td",{children:["$",Number(e.total_usd||0).toFixed(2)]}),(0,b.jsx)("td",{children:Number(e.avg_entry||0).toFixed(3)}),(0,b.jsx)("td",{className:null==r?"wc-power-sub":r>=0?"radar-up":"radar-down",children:null==r?"pending":`${r>=0?"+":"−"}$${Math.abs(r).toFixed(2)}`})]},`${e.event_id}:${e.condition_id||e.period}:${a}`)})})]})})]}),(0,b.jsxs)("details",{className:"wc-paper-ledger-section",children:[(0,b.jsxs)("summary",{children:["Complete execution log ",(0,b.jsxs)("span",{children:[e.orders.length," rows"]})]}),(0,b.jsx)("div",{className:"wc-paper-ledger-orders",children:e.orders.map((e,a)=>(0,b.jsxs)("div",{className:`wc-bot-logrow ${e.status}`,children:[(0,b.jsx)("span",{className:"wc-bot-feed-time",children:H(e.ts_ms)}),(0,b.jsx)("span",{className:"wc-bot-feed-match",title:s(e.event_id),children:s(e.event_id)}),(0,b.jsxs)("span",{className:"wc-bot-min",children:[e.minute,"'"]}),(0,b.jsx)("span",{children:rv(e,t.config.strategy)}),(0,b.jsx)("span",{className:"wc-power-sub",children:e.status}),"filled"===e.status?(0,b.jsxs)("span",{className:"radar-up",children:["BUY $",Number(e.fill_usd||0).toFixed(2)," @ ",Number(e.fill_price||0).toFixed(3)]}):"exit"===e.status?(0,b.jsxs)("span",{className:"wc-bot-exit",children:["SOLD $",Number(e.fill_usd||0).toFixed(2)," @ ",Number(e.fill_price||0).toFixed(3)]}):(0,b.jsx)("span",{className:"wc-power-sub",children:e.reason||"—"}),e.signal_reason&&(0,b.jsxs)("span",{className:"wc-bot-aiwhy",children:["🧠 ",e.signal_reason]})]},`${e.ts_ms}:${a}`))})]})]})})()]})]},t.id)})}),(0,b.jsxs)("div",{className:"wc-bot-feed",children:[(0,b.jsxs)("div",{className:"wc-bot-feed-head",children:["📋 live decisions ",em?(0,b.jsxs)("span",{className:"wc-power-sub",children:["— ",em.label,", newest first ",(0,b.jsx)("button",{className:"wc-bot-log-close",onClick:()=>i(null),children:"hide ×"})]}):(0,b.jsxs)("span",{className:"wc-power-sub",children:["— tap ",(0,b.jsx)("b",{children:"📋 log"})," on an account above to see its calls"]})]}),em?0===ex.length?(0,b.jsx)("div",{className:"wc-power-sub wc-bot-feed-empty",children:em.enabled?"watching live matches… no calls yet this session.":"this account is OFF — turn it ON to see the bot work."}):ex.map((e,t)=>(0,b.jsxs)("div",{className:`wc-bot-logrow ${e.status}`,children:[(0,b.jsx)("span",{className:"wc-bot-feed-time",children:U(e.ts_ms)}),(0,b.jsx)("span",{className:"wc-bot-feed-acct",title:e.acct,children:e.acct}),(0,b.jsx)("span",{className:"wc-bot-feed-match",title:eg(e.event_id),children:eg(e.event_id)}),(0,b.jsxs)("span",{className:"wc-bot-min",children:[e.minute,"'"]}),(0,b.jsx)("span",{children:rv(e,em.config.strategy)}),"under_ai"===em.config.strategy?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)("span",{className:"wc-power-sub",children:["true ",Math.round(100*e.true_prob),"% ",e.true_prob>=e.ask?"≥":"<"," ask ",Math.round(100*e.ask),"%"]}),(0,b.jsxs)("span",{className:e.edge>=0?"radar-up":"radar-down",children:["edge ",e.edge>=0?"+":"",Math.round(100*e.edge),"%"]})]}):"us391_under_copy"===em.config.strategy?(0,b.jsxs)("span",{className:"wc-power-sub",children:["copy ask ",Math.round(100*e.ask),"% · exact US391 source token"]}):"rollobravado_moneyline_copy"===em.config.strategy?(0,b.jsxs)("span",{className:"wc-power-sub",children:["copy ask ",Math.round(100*e.ask),"% · verified named-team NO token"]}):"late_tail_paper"===em.config.strategy?(0,b.jsxs)("span",{className:"wc-power-sub",children:["ask ",Math.round(100*e.ask),"% · market says ",Math.round(100*e.ask),"%, the tape says about half"]}):"pm15m_updown"===em.config.strategy?(0,b.jsxs)("span",{className:"wc-power-sub",children:["ask ",Math.round(100*e.ask),"¢ · ","live"===e.confidence?"vad1 FAK taker, held to settlement":"year seed · real-venue fill"]}):"key_sub_over"===em.config.strategy?(0,b.jsxs)("span",{className:"wc-power-sub",children:["O0.5 ask ",Math.round(100*e.ask),"% · fresh favorite-side key attacker substitution"]}):"style_inventory_rust"===em.config.strategy?(0,b.jsx)("span",{className:"wc-power-sub",children:"native Rust spread inventory · durable seed, complement lock, or settlement"}):"favorite_no_fade"===em.config.strategy?(0,b.jsxs)("span",{className:"wc-power-sub",children:["NO ask ",Math.round(100*e.ask),"% · validated first-goal favorite fade · settlement hold"]}):["first_goal_no_fomo","first_goal_no_risk"].includes(em.config.strategy||"")?(0,b.jsxs)("span",{className:"wc-power-sub",children:["NO ask ",Math.round(100*e.ask),"% · early first-goal compression fade · ","first_goal_no_risk"===em.config.strategy?"full-exit risk router":"principal-runner lifecycle"]}):(0,b.jsxs)("span",{className:"wc-power-sub",children:["ask ",Math.round(100*e.ask),"% · ","over05_ai_continuous"===em.config.strategy?"continuous book watch":"forward price checkpoint"]}),"filled"===e.status?(0,b.jsxs)("span",{className:"radar-up",children:["BUY $",e.fill_usd?.toFixed(0)," ✓"]}):"exit"===e.status?(0,b.jsxs)("span",{className:"wc-bot-exit",children:["⏏ SOLD $",e.fill_usd?.toFixed(0)," — ",e.reason]}):"settled"===e.status?(0,b.jsxs)("span",{className:"wc-power-sub",children:["SETTLED — ",e.reason]}):"failed"===e.status?(0,b.jsxs)("span",{className:"radar-down",children:["FAILED — ",e.reason]}):"waiting"===e.status?(0,b.jsxs)("span",{className:"wc-power-sub",children:["WAIT — ",e.reason]}):["submitting","delayed","unknown","resting"].includes(e.status)?(0,b.jsxs)("span",{className:"wc-power-sub",children:["SUBMITTED — ",e.reason]}):(0,b.jsxs)("span",{className:"wc-power-sub",children:["skip — ",e.reason]}),null!=e.clv&&(0,b.jsxs)("span",{className:e.clv>=0?"radar-up":"radar-down",children:[" · CLV ",e.clv>=0?"+":"",Math.round(100*e.clv),"%"]}),e.signal_reason&&(0,b.jsxs)("span",{className:"wc-bot-aiwhy",title:"what the AI signal saw in the run of play",children:["🧠 ",e.signal_reason]})]},t)):null]}),j&&(0,b.jsx)("div",{className:`wc-bot-flash${j.ok?"":" err"}`,children:j.msg})]})}let rq={"ml:home":"HOME","ml:away":"AWAY","ml:draw":"DRAW"},rV=["pre-KO","0-15'","15-30'","30-HT","HT-60'","60-75'","75'-FT"],rG=e=>Math.abs(e)>=1e6?`$${(e/1e6).toFixed(1)}
8M`:`$${Math.round(e/1e3).toLocaleString()}k`,rJ=e=>`${e<0?"−":"+"}$${Math.abs(e).toLocaleString()}`;function rY(){let[e,t]=(0,_.useState)(null),[a,s]=(0,_.useState)(!1);if((0,_.useEffect)(()=>{let e=!1,a=()=>(0,er.authGetJson)("/api/worldcup/tape-analytics").then(a=>{e||t(a.data||null)}).catch(()=>!e&&s(!0));a();let r=setInterval(a,12e4);return()=>{e=!0,clearInterval(r)}},[]),a)return(0,b.jsx)("div",{className:"empty-state",children:"Tape analytics unavailable — backend may still be on the previous build."});if(!e)return(0,b.jsx)("div",{className:"empty-state",children:"Folding the tapes…"});if(!e.n_matches)return(0,b.jsx)("div",{className:"empty-state",children:"No audited tapes yet — the tape starts rolling at the next live match."});let r=e.matches.filter(e=>e.pre?.lean),n=r.filter(e=>e.pre?.hit).length,l=e.matches.filter(e=>e.early?.lean),i=l.filter(e=>e.early?.hit).length,o=Object.values(e.timing.win||{}).reduce((e,t)=>e+t,0)||1,c=Object.values(e.timing.lose||{}).reduce((e,t)=>e+t,0)||1,d=Object.entries(e.styles).sort((e,t)=>t[1].roi-e[1].roi),u=Math.max(...d.map(([,e])=>e.pnl),1),h=Object.entries(e.market_pnl).sort((e,t)=>t[1].pnl-e[1].pnl),p=e.walk_forward.filter(e=>e.hit).length,m=(e,t,a)=>(0,b.jsx)("span",{style:{display:"inline-block",height:8,borderRadius:2,background:a,width:`${Math.max(2,Math.abs(e)/t*100)}%`}});return(0,b.jsxs)("div",{className:"wc-tape",children:[(0,b.jsxs)("div",{className:"radar-section",children:[(0,b.jsxs)("div",{className:"radar-section-title",children:["🎬 Tape Analysis ",(0,b.jsx)("span",{className:"wc-power-sub",children:"— every on-chain fill in our taped matches, settled against the final score"})]}),(0,b.jsxs)("div",{style:{display:"flex",gap:26,flexWrap:"wrap",margin:"10px 0 4px",fontVariantNumeric:"tabular-nums"},children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("b",{style:{fontSize:22},children:rG(e.total_vol)}),(0,b.jsx)("div",{className:"wc-power-sub",children:"flow captured"})]}),(0,b.jsxs)("div",{children:[(0,b.jsx)("b",{style:{fontSize:22},children:e.total_wallets.toLocaleString()}),(0,b.jsx)("div",{className:"wc-power-sub",children:"wallets audited"})]}),(0,b.jsxs)("div",{children:[(0,b.jsx)("b",{style:{fontSize:22},children:e.n_matches}),(0,b.jsx)("div",{className:"wc-power-sub",children:"matches taped"})]}),(0,b.jsxs)("div",{children:[(0,b.jsxs)("b",{style:{fontSize:22},children:[n,"/",r.length]}),(0,b.jsx)("div",{className:"wc-power-sub",children:"pre-kickoff money named the winner"})]}),(0,b.jsxs)("div",{children:[(0,b.jsxs)("b",{style:{fontSize:22},children:[i,"/",l.length]}),(0,b.jsx)("div",{className:"wc-power-sub",children:"named it by the 30th minute"})]})]})]}),(0,b.jsxs)("div",{className:"radar-section",children:[(0,b.jsxs)("div",{className:"radar-section-title",children:["The call board ",(0,b.jsx)("span",{className:"wc-power-sub",children:"— where the money leaned, and what actually happened"})]}),(0,b.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit,minmax(310px,1fr))",gap:10},children:e.matches.map(e=>{let t,a=Math.max(...Object.values(e.full?.flows||{x:1}).map(Math.abs),1);return(0,b.jsxs)("div",{style:{border:"1px solid rgba(255,255,255,0.08)",borderRadius:6,padding:"10px 12px"},children:[(0,b.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",gap:8},children:[(0,b.jsx)("b",{children:e.match}),(0,b.jsxs)("span",{className:"wc-power-sub",children:[rG(e.vol)," · ",e.wallets.toLocaleString()," wallets"]})]}),(0,b.jsx)("div",{style:{display:"flex",gap:6,flexWrap:"wrap",margin:"8px 0"},children:(t={display:"inline-block",padding:"3px 9px",borderRadius:4,fontSize:11,whiteSpace:"nowrap",border:"1px solid rgba(255,255,255,0.14)",fontVariantNumeric:"tabular-nums"},(0,b.jsxs)(b.Fragment,{children:[e.pre?.lean?(0,b.jsxs)("span",{style:{...t,color:e.pre.hit?"#58C08A":"#E0685C",borderColor:e.pre.hit?"rgba(88,192,138,0.5)":"rgba(224,104,92,0.5)"},children:["before kickoff → ",rq[e.pre.lean]," ",rG(e.pre.usd)," ",e.pre.hit?"✓":"✗"]}):(0,b.jsx)("span",{style:{...t,opacity:.55},children:"before kickoff → no conviction"}),e.early?.lean&&(0,b.jsxs)("span",{style:{...t,color:e.early.hit?"#58C08A":"#E0685C",borderColor:e.early.hit?"rgba(88,192,138,0.5)":"rgba(224,104,92,0.5)"},children:["by 30′ → ",rq[e.early.lean]," ",e.early.hit?"✓":"✗"]})]}))}),["ml:home","ml:draw","ml:away"].map(t=>{let s=e.full?.flows?.[t]??0;return(0,b.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"46px 1fr 74px",gap:8,alignItems:"center",fontSize:11,fontVariantNumeric:"tabular-nums",opacity:t===e.result?1:.65},children:[(0,b.jsxs)("span",{children:[rq[t],t===e.result?" ●":""]}),(0,b.jsx)("span",{children:m(s,a,s>=0?"#58C08A":"#E0685C")}),(0,b.jsxs)("span",{style:{textAlign:"right"},children:[rJ(Math.round(s/1e3)),"k"]})]},t)})]},e.eid)})})]}),(0,b.jsxs)("div",{className:"radar-section",children:[(0,b.jsxs)("div",{className:"radar-section-title",children:["The money river ",(0,b.jsx)("span",{className:"wc-power-sub",children:"— who collects and who donates, by trading style"})]}),(0,b.jsxs)("table",{className:"wc-table",style:{fontVariantNumeric:"tabular-nums"},children:[(0,b.jsx)("thead",{children:(0,b.jsxs)("tr",{children:[(0,b.jsx)("th",{children:"style"}),(0,b.jsx)("th",{children:"wallet-matches"}),(0,b.jsx)("th",{children:"win %"}),(0,b.jsx)("th",{children:"P&L per $ bought"}),(0,b.jsx)("th",{children:"settled P&L"})]})}),(0,b.jsx)("tbody",{children:d.map(([e,t])=>(0,b.jsxs)("tr",{children:[(0,b.jsx)("td",{children:(0,b.jsx)("b",{children:e})}
8),(0,b.jsx)("td",{children:t.n.toLocaleString()}),(0,b.jsxs)("td",{children:[t.win_pct,"%"]}),(0,b.jsxs)("td",{style:{color:t.roi>=.3?"#58C08A":void 0},children:[t.roi>=0?"+":"",t.roi.toFixed(2)]}),(0,b.jsxs)("td",{style:{minWidth:180},children:[m(t.pnl,u,"#58C08A")," ",(0,b.jsx)("span",{style:{marginLeft:6},children:rJ(t.pnl)})]})]},e))})]}),(0,b.jsxs)("div",{className:"wc-power-sub",style:{marginTop:6},children:["The best style is ",(0,b.jsx)("b",{children:"pre-match money with in-play exits"})," — buy before kickoff, sell into the match. Your CLV audit said the same about your own trading."]})]}),(0,b.jsxs)("div",{className:"radar-section",children:[(0,b.jsxs)("div",{className:"radar-section-title",children:["When the winning dollar arrives ",(0,b.jsx)("span",{className:"wc-power-sub",children:"— share of each side's buying, by match phase"})]}),(0,b.jsx)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:22},children:["win","lose"].map(t=>{let a="win"===t?o:c;return(0,b.jsxs)("div",{children:[(0,b.jsx)("b",{style:{color:"win"===t?"#58C08A":"#E0685C"},children:"win"===t?"Winners' buys":"Losers' buys"}),rV.map(s=>{let r=(e.timing[t]?.[s]||0)/a*100;return(0,b.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"58px 1fr 46px",gap:8,alignItems:"center",fontSize:11,margin:"4px 0",fontVariantNumeric:"tabular-nums"},children:[(0,b.jsx)("span",{children:s}),(0,b.jsx)("span",{children:m(r,55,"win"===t?"#58C08A":"#E0685C")}),(0,b.jsxs)("span",{style:{textAlign:"right"},children:[r.toFixed(1),"%"]})]},s)})]},t)})}),(0,b.jsxs)("div",{className:"wc-power-sub",style:{marginTop:6},children:["Half of all winning money is placed ",(0,b.jsx)("b",{children:"before kickoff"}),". Losing money crowds the last 15 minutes — the desperation window our 72′ cutoff refuses."]})]}),(0,b.jsxs)("div",{className:"radar-section",children:[(0,b.jsxs)("div",{className:"radar-section-title",children:["What burned ",(0,b.jsx)("span",{className:"wc-power-sub",children:"— the crowd's profit or loss, per market"})]}),(0,b.jsxs)("table",{className:"wc-table",style:{fontVariantNumeric:"tabular-nums"},children:[(0,b.jsx)("thead",{children:(0,b.jsxs)("tr",{children:[(0,b.jsx)("th",{children:"market"}),(0,b.jsx)("th",{children:"$ bought"}),(0,b.jsx)("th",{children:"crowd net P&L"}),(0,b.jsx)("th",{children:"per $"})]})}),(0,b.jsx)("tbody",{children:h.map(([e,t])=>(0,b.jsxs)("tr",{children:[(0,b.jsx)("td",{children:e}),(0,b.jsx)("td",{children:rG(t.buy)}),(0,b.jsx)("td",{style:{color:t.pnl>=0?"#58C08A":"#E0685C"},children:rJ(t.pnl)}),(0,b.jsx)("td",{style:{color:t.pnl>=0?"#58C08A":"#E0685C"},children:(t.pnl/Math.max(1,t.buy)>=0?"+":"")+(t.pnl/Math.max(1,t.buy)).toFixed(3)})]},e))})]}),(0,b.jsxs)("div",{className:"wc-power-sub",style:{marginTop:6},children:["Chalk-heavy stretch — favorites and goals both landed, so moneyline takers collected. The reliable torch pile: ",(0,b.jsx)("b",{children:"0-0 lottery tickets"})," (betting NO on Over 0.5) went 0-for-",e.n_matches,"."]})]}),(0,b.jsxs)("div",{className:"radar-section",children:[(0,b.jsxs)("div",{className:"radar-section-title",children:["The size ladder ",(0,b.jsx)("span",{className:"wc-power-sub",children:"— win rate climbs with stake size"})]}),(0,b.jsx)("div",{style:{display:"flex",gap:10,alignItems:"flex-end"},children:["<$100","$100-1k","$1k-10k","$10k-100k",">$100k"].filter(t=>e.tiers[t]).map(t=>{let a=e.tiers[t];return(0,b.jsxs)("div",{style:{flex:1,textAlign:"center",fontSize:11,fontVariantNumeric:"tabular-nums"},children:[(0,b.jsxs)("b",{style:{fontSize:15},children:[a.win_pct,"%"]}),(0,b.jsx)("div",{style:{background:"linear-gradient(180deg,#3FA96C,#2A6E48)",borderRadius:"3px 3px 0 0",margin:"5px auto 6px",width:"68%",height:Math.max(6,(a.win_pct-45)*6)}}),(0,b.jsx)("div",{children:t}),(0,b.jsx)("div",{className:"wc-power-sub",children:"<$100"===t||"$100-1k"===t?`n=${a.n.toLocaleString()}`:`+${a.roi.toFixed(3)}/$ \xb7 n=${a.n.toLocaleString()}`})]},t)})}),(0,b.jsxs)("div",{className:"wc-power-sub",style:{marginTop:6},children:["The dead zone is ",(0,b.jsx)("b",{children:"$1k–10k"}),": serious enough to lose, not serious enough to work."]})]}),(0,b.jsxs)("div",{className:"radar-section",children:[(0,b.jsxs)("div",{className:"radar-section-title",children:["The proven cohort ",(0,b.jsx)("span",{className:"wc-power-sub",children:"— wallets that beat the market in 2+ taped matches"})]}),(0,b.jsxs)("table",{className:"wc-table",style:{fontVariantNumeric:"tabular-nums"},children:[(0,b.jsx)("thead",{children:(0,b.jsxs)("tr",{children:[(0,b.jsx)("th",{children:"wallet"}),(0,b.jsx)("th",{children:"style"}),(0,b.jsx)("th",{children:"matches"}),(0,b.jsx)("th",{children:"settled P&L"})]})}),(0,b.jsx)("tbody",{children:e.proven.map(e=>(0,b.jsxs)("tr",{children:[(0,b.jsx)("td",{children:(0,b.jsx)("b",{children:e.name||e.w})}),(0,b.jsx)("td",{children:e.style}),(0,b.jsx)("td",{children:e.matches}),(0,b.jsx)("td",{style:{color:"#58C08A"},children:rJ(e.pnl)})]},e.w))})]}),(0,b.jsxs)("div",{style:{marginTop:10,fontSize:12.5},children:[(0,b.jsx)("b",{children:"Walk-forward test"})," ",(0,b.jsxs)("span",{className:"wc-power-sub",children:["— using only wallets proven BEFORE each match, did their early lean call it? ",p," of ",e.walk_forward.length,":"]}),e.walk_forward.map(e=>(0,b.jsxs)("div",{className:"wc-power-sub",style:{marginTop:3}
8,children:["› ",e.match,": cohort leaned ",rq[e.lean]," (",rG(e.usd),") ",e.hit?(0,b.jsx)("span",{style:{color:"#58C08A"},children:"✓ called it"}):(0,b.jsx)("span",{style:{color:"#E0685C"},children:"✗ missed (the draw)"})]},e.match))]})]}),(0,b.jsxs)("div",{className:"radar-section",children:[(0,b.jsxs)("div",{className:"radar-section-title",children:["The alpha ",(0,b.jsx)("span",{className:"wc-power-sub",children:"— what these tapes tell us to do, ranked by evidence"})]}),[["Respect the early tape over the models",`Pre-kickoff conviction leans: ${n}/${r.length}. By 30′: ${i}/${l.length}. Backtested on our own 25 ML entries: fighting a ≥$100k crowd lean picked the losing side 16/16; aligned entries 9/9.`,"✅ LIVE — tape brake vetoes crowd-opposed ML buys (PM + pair + fade cells)"],["Be pre-match money with in-play exits",`Best style in the river at +$0.51 per dollar. Enter before kickoff, sell the match's emotion — never the reverse.`,"✅ live — the PM's Canada trade was exactly this shape"],["Never be the late dollar",`75′-to-FT buying: ${((e.timing.lose?.["75'-FT"]||0)/c*100).toFixed(0)}% of losing volume vs ${((e.timing.win?.["75'-FT"]||0)/o*100).toFixed(0)}% of winning. Half the winning money arrives pre-kickoff.`,"✅ live — 72′ cutoff + ET gate"],[`The draw is the sharps' blind spot — and the crowd's strength`,`The only walk-forward miss was the draw; the broad pre-kickoff tape DID lean draw on that match (✓). When the whole crowd leans DRAW pre-match, listen.`,"👁 watch — n=1, logging every pre-KO draw lean"],["Trade the complement like a first-class market",`NO-side dollars are ${Math.round(e.buys_yes_no[1]/Math.max(1,e.buys_yes_no[0]+e.buys_yes_no[1])*100)}% of all buying. Complement exits have full liquidity.`,"✅ live — complement-exit route"],["Never buy the 0-0 lottery without a collapse signal","Over 0.5 NO: zero hits, every settled dollar burned.","✅ live — cold-lotto guard"],["Shadow the proven cohort",`${e.proven[0]?.name||e.proven[0]?.w||"top wallet"}: ${rJ(e.proven[0]?.pnl||0)} across ${e.proven[0]?.matches||0} straight matches. Walk-forward ${p}-of-${e.walk_forward.length} — but as a veto it would have blocked our draw wins (sharps are draw-blind), so it informs, never vetoes.`,"✅ LIVE — proven-cohort lean feeds the PM's payload as information only"]].map(([e,t,a],s)=>(0,b.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"30px 1fr",gap:10,padding:"9px 10px",border:"1px solid rgba(255,255,255,0.07)",borderLeft:"3px solid #3FA96C",borderRadius:4,marginTop:8},children:[(0,b.jsx)("b",{style:{fontSize:18,color:"#3FA96C"},children:s+1}),(0,b.jsxs)("div",{children:[(0,b.jsx)("b",{children:e}),(0,b.jsx)("div",{className:"wc-power-sub",children:t}),(0,b.jsx)("div",{style:{fontSize:11,marginTop:3,opacity:.85},children:a})]})]},s)),(0,b.jsxs)("div",{className:"wc-power-sub",style:{marginTop:12},children:["Read honestly: ",e.n_matches," matches is a regime, not a law — this stretch was chalk-heavy, which flatters taker P&L as a class. The tape sees taker fills ≥$2; maker income is invisible. P&L settles at the 90′ score. Rebuilds automatically as new tapes land."]})]})]})}let rK={16:"Round of 32",8:"Round of 16",4:"Quarter-finals",2:"Semi-finals",1:"Final"};function rX({matches:e,onOpen:t}){let[a,s]=(0,_.useState)(!1),r=(0,_.useMemo)(()=>{let t=[...e].sort((e,t)=>(e.kickoff_ts||0)-(t.kickoff_ts||0)),a=e=>[e.home_team,e.away_team],s=(e,s)=>t.filter(t=>(t.kickoff_ts||0)<s&&"finished"===t.status&&a(t).includes(e)),r=e=>{let s;if("finished"!==e.status)return null;let r=e.score_home??0,n=e.score_away??0;if(r>n)return e.home_team;if(n>r)return e.away_team;let l=(s=e.kickoff_ts||0,new Set(t.filter(e=>(e.kickoff_ts||0)>s).flatMap(a)));return l.has(e.home_team)?e.home_team:l.has(e.away_team)?e.away_team:null},n=t.filter(e=>{let n=e.kickoff_ts||0;if("finished"===e.status){let l=r(e);if(!l)return!1;let i=a(e).find(e=>e!==l);return!(!i||t.some(e=>(e.kickoff_ts||0)>n&&a(e).includes(i)))&&s(e.home_team,n).length>=3}return a(e).every(e=>{let t=s(e,n);return t.length>=3&&r(t[t.length-1])===e})});if(n.length<2)return null;let l=(e,t)=>
8{let a=n.filter(a=>(a.kickoff_ts||0)<t&&r(a)===e);return a.length?a[a.length-1]:null},i=new Map,o=e=>{let t=String(e.event_id);if(i.has(t))return i.get(t);i.set(t,0);let s=a(e).map(t=>l(t,e.kickoff_ts||0)).filter(Boolean),r=s.length?1+Math.max(...s.map(o)):0;return i.set(t,r),r};n.forEach(o);let c=new Map;n.forEach(e=>{let t=i.get(String(e.event_id));(c.get(t)||c.set(t,[]).get(t)).push(e)});let d=[...c.keys()].sort((e,t)=>e-t),u=e=>e.m?r(e.m):null,h=[],p=null;for(let e of d){let t=(c.get(e)||[]).sort((e,t)=>(e.kickoff_ts||0)-(t.kickoff_ts||0)),s=t.map(e=>({key:String(e.event_id),m:e}));p&&s.sort((e,t)=>{let s=e=>{if(!e.m)return 999;let t=a(e.m).map(t=>l(t,e.m.kickoff_ts||0)).filter(Boolean),s=t.length?p.findIndex(e=>e.m&&e.m.event_id===t[0].event_id):999;return s<0?999:s};return s(e)-s(t)}),h.push({key:`g${e}`,label:rK[t.length]||`Round of ${2*t.length}`,nodes:s}),p=s}let m=h[h.length-1];if(m&&m.nodes.length>=2){let e=[];for(let t=0;t<Math.floor(m.nodes.length/2);t++)e.push({key:`proj-${t}`,feeds:[m.nodes[2*t],m.nodes[2*t+1]]});e.length&&h.push({key:"proj",label:rK[e.length]||`Round of ${2*e.length}`,nodes:e})}let x=h.findIndex(e=>e.nodes.some(e=>!e.m||"finished"!==e.m.status));return{cols:h,currentIdx:-1===x?h.length-1:x,sideLabel:e=>{let t=u(e);return t||(e.m?`${e.m.home_team} / ${e.m.away_team} winner`:"TBD")},nodeWinner:u}},[e]);if(!r)return null;let{cols:n,currentIdx:l,sideLabel:i,nodeWinner:o}=r,c=e=>{if(!e.m){let[t,a]=e.feeds||[];return(0,b.jsxs)("div",{className:"wcbk-card wcbk-tbd",children:[(0,b.jsx)("div",{className:"wcbk-side",children:(0,b.jsx)("span",{className:"wcbk-name dim",children:t?i(t):"TBD"})}),(0,b.jsx)("div",{className:"wcbk-side",children:(0,b.jsx)("span",{className:"wcbk-name dim",children:a?i(a):"TBD"})}),(0,b.jsx)("div",{className:"wcbk-meta",children:"projected pairing"})]},e.key)}let a=e.m,s=o(e),r="finished"===a.status&&(a.score_home??0)===(a.score_away??0),n=(e,t,r)=>(0,b.jsxs)("div",{className:"wcbk-side",children:[(0,b.jsxs)("span",{className:`wcbk-name${s&&s!==e?" dim":""}${s===e?" won":""}`,children:[t," ",e]}),(0,b.jsx)("span",{className:`wcbk-score${s===e?" won":""}`,children:"scheduled"===a.status?"":r??""})]});return(0,b.jsxs)("div",{className:`wcbk-card${"live"===a.status?" live":""}`,onClick:()=>t(a),title:"open the match page",children:[n(a.home_team,a.home_flag,a.score_home),n(a.away_team,a.away_flag,a.score_away),(0,b.jsx)("div",{className:"wcbk-meta",children:"live"===a.status?(0,b.jsxs)("span",{className:"wcbk-live",children:["● ",null!=a.minute?`${a.minute}'`:"LIVE"]}):"finished"===a.status?(0,b.jsxs)(b.Fragment,{children:["FT",r?" · pens":"",s?` \xb7 ${s} advance${s.endsWith("s")?"":"s"}`:""]}):rm(a.kickoff_ts)})]},e.key)};return(0,b.jsxs)("div",{className:"wcbk-wrap",children:[(0,b.jsxs)("div",{className:"wcbk-head",onClick:()=>s(e=>!e),children:["🏆 Knockout bracket",(0,b.jsxs)("span",{className:"wcbk-stage",children:["— ",n[l]?.label," in progress"]}),(0,b.jsx)("span",{className:"wcbk-collapse",children:a?"▸ show":"▾ hide"})]}),!a&&(0,b.jsx)("div",{className:"wcbk-scroll",children:(0,b.jsx)("div",{className:"wcbk",children:n.map((e,t)=>(0,b.jsxs)("div",{className:`wcbk-round${t===l?" here":""}`,children:[(0,b.jsxs)("div",{className:"wcbk-round-label",children:[e.label,t===l?" · now":""]}),(0,b.jsx)("div",{className:"wcbk-col",children:e.nodes.length>1?(e=>{let t=[];for(let a=0;a<e.length;a+=2)t.push(e.slice(a,a+2));return t})(e.nodes).map((e,t)=>(0,b.jsx)("div",{className:"wcbk-pair",children:e.map(c)},t)):e.nodes.map(c)})]},e.key))})})]})}function rZ({l:e,active:t,onPick:a}){let s=0===(e.open||0)&&0===(e.live||0);return(0,b.jsxs)("button",{className:`wc-league-chip${t?" active":""}${s?" empty":""}${1===e.tier?" t1":""}`,onClick:()=>a(e.key),title:`${e.name}${e.goals_avg?` \xb7 ${e.goals_avg.toFixed(2)} goals/match`:""}${null!=e.fav_win?` \xb7 ⭐ our Elo favorite wins ${(100*e.fav_win).toFixed(0)}% (${e.fav_n} matches)`:""}${null!=e.mkt_fav_win?` \xb7 📈 the POLYMARKET pre-kickoff favorite wins ${(100*e.mkt_fav_win).toFixed(0)}% (${e.mkt_fav_n} matches)`:""}${s?" · no open fixtures listed yet":""}`,children:[e.short,e.goals_avg>0&&(0,b.jsx)("span",{className:"wc-chip-goals",children:e.goals_avg.toFixed(2)}),null!=e.fav_win&&(0,b.jsxs)("span",{className:"wc-chip-fav",children:["⭐",(100*e.fav_win).toFixed(0),"%"]}),null!=e.mkt_fav_win&&(0,b.jsxs)("span",{className:"wc-chip-fav",children:["ðŸ“
8ˆ",(100*e.mkt_fav_win).toFixed(0),"%"]}),(e.live||0)>0?(0,b.jsxs)("span",{className:"wc-chip-live",children:[" ●",e.live]}):(e.open||0)>0?(0,b.jsxs)("span",{className:"wc-chip-n",children:[" ",e.open]}):null]})}function rQ(){let[e,t]=(0,_.useState)([]),[a,s]=(0,_.useState)(!0),[r,n]=(0,_.useState)("upcoming"),[l,i]=(0,_.useState)("all"),[o,c]=(0,_.useState)([]);(0,_.useEffect)(()=>{let e=()=>(0,er.authGetJson)("/api/worldcup/leagues").then(e=>{e.ok&&c(e.data.leagues||[])}).catch(()=>{});e();let t=setInterval(e,6e4);return()=>clearInterval(t)},[]);let d=(0,_.useMemo)(()=>Object.fromEntries(o.map(e=>[e.key,e.short])),[o]),[u,h]=(0,_.useState)(!1),[p,m]=(0,_.useState)(!1),[x,g]=(0,_.useState)(!1),[f,v]=(0,_.useState)(null);(0,_.useEffect)(()=>{let e=()=>(0,er.authGetJson)("/api/worldcup/autotrade/status").then(e=>{if(e.ok){let t=e.data.accounts.filter(e=>e.enabled);v(t.length?{n:t.length,pnl:t.reduce((e,t)=>e+t.today_pnl,0)}:null)}}).catch(()=>{});e();let t=setInterval(e,8e3);return()=>clearInterval(t)},[]);let{openTab:y}=(0,ez.useMarketTabs)(),j=e=>y({kind:"wc",marketId:e.event_id,title:`${e.home_flag||""} ${e.home_team} vs ${e.away_team} ${e.away_flag||""}`.trim()});(0,_.useEffect)(()=>{let e=!1,a=null,r=()=>{let n=3e4;(0,er.authGetJson)("/api/worldcup/matches").then(a=>{if(!e){let e=a.data?.matches||[];t(e),s(!1);let r=Date.now();n=e.some(e=>"live"===e.status||"finished"!==e.status&&null!=e.kickoff_ts&&e.kickoff_ts>=r-144e5&&e.kickoff_ts<=r+9e5)?5e3:3e4}}).catch(()=>!e&&s(!1)).finally(()=>{e||(a=window.setTimeout(r,n))})};return r(),()=>{e=!0,null!=a&&window.clearTimeout(a)}},[]);let w=(0,_.useMemo)(()=>"all"===l?e:e.filter(e=>(e.league||"fifwc")===l),[e,l]),N=(0,_.useMemo)(()=>{let e=Date.now(),t=new Date().setHours(0,0,0,0),a=t+864e5,s=w;return"live"===r?s=w.filter(e=>"live"===e.status):"today"===r?s=w.filter(e=>(e.kickoff_ts||0)>=t&&(e.kickoff_ts||0)<a):"finished"===r?s=w.filter(e=>"finished"===e.status).slice().reverse():"upcoming"===r&&(s=w.filter(t=>"finished"!==t.status&&(t.kickoff_ts||0)>e-108e5)),s},[w,r]),k=(0,_.useMemo)(()=>{let e=new Map;for(let a of N){var t;let s=(t=a.kickoff_ts)?new Date(t).toLocaleDateString(void 0,{weekday:"long",month:"long",day:"numeric"}):"Date TBD";e.has(s)||e.set(s,[]),e.get(s).push(a)}return Array.from(e.entries())},[N]),S=w.filter(e=>"live"===e.status).length,$=(0,_.useMemo)(()=>{let t=e.filter(e=>"fifwc"===(e.league||"fifwc")),a=new Date().setHours(0,0,0,0),s=a+864e5,r=t.filter(e=>"finished"===e.status).length,n=t.filter(e=>"live"===e.status).length,l=t.filter(e=>(e.kickoff_ts||0)>=a&&(e.kickoff_ts||0)<s&&"finished"!==e.status).length,i=Math.max(104,t.length),o=Math.max(0,i-r),c=i?Math.round(r/i*100):0;return{total:i,finished:r,live:n,today:l,left:o,pct:c}},[e]);return(0,b.jsxs)("div",{className:"wc-view",children:[(0,b.jsxs)("div",{className:"wc-toolbar",children:[(0,b.jsx)("span",{className:"wc-title",children:"⚽ Soccer"}),["upcoming","live","today","finished","all"].map(e=>(0,b.jsxs)("button",{className:`wc-filter${r===e&&!u&&!p&&!x?" active":""}`,onClick:()=>{h(!1),m(!1),g(!1),n(e)},children:[e,"live"===e&&S>0?` (${S})`:""]},e)),(0,b.jsx)("button",{className:`wc-filter${u?" active":""}`,onClick:()=>{h(e=>!e),m(!1),g(!1)},children:"🧪 signal lab"}),(0,b.jsxs)("button",{className:`wc-filter${p?" active":""}`,onClick:()=>{m(e=>!e),h(!1),g(!1)},children:["🤖 paper agents",f?" ●":""]}),(0,b.jsx)("button",{className:`wc-filter${x?" active":""}`,onClick:()=>{g(e=>!e),m(!1),h(!1)},children:"🎬 tape analysis"}),f&&(0,b.jsxs)("span",{className:`wc-bot-toolpill${f.pnl<0?" neg":""}`,onClick:()=>{m(!0),h(!1)},title:"auto-trader running — click to open",children:["🤖 ",f.n," paper agent",1===f.n?"":"s"," running · ",f.pnl>=0?"+":"","$",f.pnl.toFixed(0)," today"]}),(0,b.jsx)("span",{className:"wc-note",children:"prices = Polymarket · fair = our Elo-history model · edge = fair − market"})]}),!p&&!u&&!x&&o.length>0&&(0,b.jsxs)("div",{className:"wc-league-chips",children:[(0,b.jsx)("button",{className:`wc-league-chip${"all"===l?" active":""}`,onClick:()=>i("all"),children:"All leagues"}),o.filter(e=>0===e.tier).map(e=>(0,b.jsx)(rZ,{l:e,active:l===e.key,onPick:i},e.key)),(0,b.jsx)("span",{className:"wc-tier-label t1",title:"3.00+ goals per match (2022–2026 study, global average 2.71)",children:"🔥 TIER 1 
8· GOAL FEST"}),o.filter(e=>1===e.tier).map(e=>(0,b.jsx)(rZ,{l:e,active:l===e.key,onPick:i},e.key)),(0,b.jsx)("span",{className:"wc-tier-label",title:"above the 2.71 global average goals per match",children:"TIER 2 · ABOVE AVG"}),o.filter(e=>2===e.tier).map(e=>(0,b.jsx)(rZ,{l:e,active:l===e.key,onPick:i},e.key)),o.some(e=>3===e.tier)&&(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)("span",{className:"wc-tier-label",title:"below the 2.71 global average — defensive leagues where the Under is the play (full ESPN narration only)",children:"🧊 TIER 3 · CAGEY"}),o.filter(e=>3===e.tier).map(e=>(0,b.jsx)(rZ,{l:e,active:l===e.key,onPick:i},e.key))]}),o.some(e=>4===e.tier)&&(0,b.jsxs)("select",{className:`wc-league-select${o.some(e=>4===e.tier&&e.key===l)?" active":""}`,value:o.some(e=>4===e.tier&&e.key===l)?l:"",onChange:e=>e.target.value&&i(e.target.value),title:"Every other Polymarket soccer competition with an open fixture; discovered automatically",children:[(0,b.jsxs)("option",{value:"",children:["🌐 Other leagues (",o.filter(e=>4===e.tier).length,")"]}),o.filter(e=>4===e.tier).map(e=>(0,b.jsxs)("option",{value:e.key,children:[e.name," · ",e.live?`${e.live} live`:`${e.open||0} open`]},e.key))]})]}),!p&&!u&&!x&&"fifwc"===l&&e.length>0&&(0,b.jsxs)("div",{className:"wc-tracker",title:"Full WC 2026 = 104 matches (72 group-stage + 32 knockout). Later knockout fixtures appear on the board once the bracket is drawn.",children:[(0,b.jsxs)("span",{className:"wc-tracker-head",children:["🏆 ",(0,b.jsx)("b",{children:$.left})," ",1===$.left?"match":"matches"," left"]}),(0,b.jsx)("span",{className:"wc-tracker-bar",children:(0,b.jsx)("span",{className:"wc-tracker-fill",style:{width:`${$.pct}%`}})}),(0,b.jsxs)("span",{className:"wc-tracker-sub",children:[$.finished," of ",$.total," played · ",$.pct,"%"]}),$.live>0&&(0,b.jsxs)("span",{className:"wc-tracker-live",children:["● ",$.live," live"]}),$.today>0&&(0,b.jsxs)("span",{className:"wc-tracker-today",children:[$.today," today"]})]}),p?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(rH,{}),(0,b.jsx)(rU,{})]}):x?(0,b.jsx)(rY,{}):u?(0,b.jsx)(rb,{}):a?(0,b.jsx)("div",{className:"empty-state",children:"Loading fixtures…"}):0===k.length?(0,b.jsxs)("div",{className:"empty-state",children:["No matches for this filter",0===e.length?" — fixture sync runs every 10 minutes":"","."]}):(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(rX,{matches:e,onOpen:j}),k.map(([e,t])=>(0,b.jsxs)("div",{className:"wc-day",children:[(0,b.jsx)("div",{className:"wc-day-head",children:e}),(0,b.jsx)("table",{className:"wc-table",children:(0,b.jsx)("tbody",{children:t.map(e=>{let t,a,s,r=(t=0,["home","draw","away"].forEach(a=>{let s=rx(e.model?.[a],e.prices?.[a]);null!=s&&Math.abs(s)>Math.abs(t)&&(t=s)}),t);return(0,b.jsxs)("tr",{className:"wc-row",onClick:()=>j(e),children:[(0,b.jsx)("td",{className:"wc-cell-status",children:"live"===e.status?(0,b.jsxs)("span",{className:"wc-live-badge",children:["● ",null!=e.minute?`${e.minute}'`:"LIVE"]}):"finished"===e.status?(0,b.jsx)("span",{className:"wc-ft",children:"FT"}):(0,b.jsx)("span",{className:"wc-ko",children:rm(e.kickoff_ts).split(", ").pop()})}),(0,b.jsxs)("td",{className:"wc-cell-teams",children:["all"===l&&e.league&&(0,b.jsx)("span",{className:"wc-league-tag",title:d[e.league]?void 0:e.league,children:d[e.league]||e.league}),(0,b.jsxs)("span",{className:"scheduled"!==e.status&&(e.score_home??0)>(e.score_away??0)?"wc-winner":"",children:[e.home_flag," ",e.home_team]}),(0,b.jsx)("span",{className:"wc-score",children:"scheduled"===e.status?"vs":`${e.score_home??"?"}–${e.score_away??"?"}`}),(0,b.jsxs)("span",{className:"scheduled"!==e.status&&(e.score_away??0)>(e.score_home??0)?"wc-winner":"",children:[e.away_team," ",e.away_flag]})]}),(0,b.jsxs)("td",{className:"wc-cell-prices",children:[(0,b.jsx)("span",{className:"wc-price",children:ru(e.prices?.home)}),(0,b.jsx)("span",{className:"wc-price draw",children:ru(e.prices?.draw)}),(0,b.jsx)("span",{className:"wc-price",children:ru(e.prices?.away)})]}),(0,b.jsx)("td",{className:"wc-cell-bar",children:(0,b.jsx)(rg,{m:e})}),(0,b.jsx)("td",{className:"wc-cell-edge",children:Math.abs(r)>=4&&"finished"!==e.status?(0,b.jsxs)("span",{className:`wc-edge ${r>0?"pos":"neg"}`,title:"largest |fair − market| across the three outcomes",children:[r>0?"+":"",r.toFixed(1),"pp"]}):null}),(0,b.jsx)("td",{className:"wc-cell-vol",children:(0,b.jsx)("span",{className:`wc-vol ${(a=Number(e.volume||0))>=25e4?"deep":a>=5e4?"ok":a>=1e4?"thin":"dead"}`,title:`Polymarket volume traded on this match so far: ${rh(e.volume)}`+(e.volume_24h?` \xb7 ${rh(e.volume_24h)} in the last 24h`:"")+"\nCombined across the moneyline and every prop market.",children:(s=Number(e.volume||0))?s>=1e6?`$${(s/1e6).toFixed(s>=1e7?0:1)}M`:s>=1e3?`$${(s/1e3).toFixed(s>=1e5?0:1)}k`:`$${s.toFixed(0)}`:"—"})})]},e.event_id)})})})]},e))]})]})}function r0({data:e}){let t=e.swing,a=e.match;
8if(!t||"finished"===a.status)return null;let s=t.p_multi_swing>=.5?"high":t.p_multi_swing>=.35?"medium":"low",r=e=>null!=e?`${Math.round(100*e)}%`:"—",n=e=>e?`${a.home_team} ${Math.round(100*(e.home||0))}c \xb7 draw ${Math.round(100*(e.draw||0))}c \xb7 ${a.away_team} ${Math.round(100*(e.away||0))}c`:"—";return(0,b.jsxs)("div",{className:"radar-section",children:[(0,b.jsxs)("div",{className:"radar-section-title",children:["Swing plan — how tradeable is this match live?"," ",(0,b.jsxs)("span",{className:`wc-swing-grade ${s}`,children:[s.toUpperCase()," swing potential"]})]}),(0,b.jsx)("div",{className:"radar-section-note",children:"For the “buy the legs cheap, sell the spikes” style: profits come from goals forcing violent repricing — this scores how likely those moments are (10,000-sim Poisson on this matchup’s goal rates)."}),(0,b.jsxs)("div",{className:"wc-swing-grid",children:[(0,b.jsxs)("div",{className:"wc-swing-stat",children:[(0,b.jsx)("b",{children:t.exp_goals}),(0,b.jsx)("span",{children:"expected goals"})]}),(0,b.jsxs)("div",{className:"wc-swing-stat",children:[(0,b.jsx)("b",{children:r(1-t.p_0_0)}),(0,b.jsx)("span",{children:"at least one goal"})]}),(0,b.jsxs)("div",{className:"wc-swing-stat",children:[(0,b.jsx)("b",{children:r(t.p_any_equalizer)}),(0,b.jsx)("span",{children:"an equalizer happens"})]}),(0,b.jsxs)("div",{className:"wc-swing-stat",children:[(0,b.jsx)("b",{children:r(t.p_lead_change)}),(0,b.jsx)("span",{children:"lead changes hands"})]}),(0,b.jsxs)("div",{className:"wc-swing-stat",children:[(0,b.jsx)("b",{children:r(t.p_multi_swing)}),(0,b.jsx)("span",{children:"2+ big swings"})]}),null!=t.basket_cost_c&&(0,b.jsxs)("div",{className:"wc-swing-stat",children:[(0,b.jsxs)("b",{children:[t.basket_cost_c,"c"]}),(0,b.jsxs)("span",{children:["all-3-legs basket cost ",t.basket_cost_c>100?"(over $1 — pure volatility play, never hold to the end)":"(under $1!)"]})]})]}),(0,b.jsxs)("div",{className:"wc-swing-playbook",children:[(0,b.jsx)("div",{className:"radar-section-note",children:"Pre-written repricings from the model — your sell/buy reference points when an event hits:"}),(0,b.jsxs)("div",{children:["⚽ If ",a.home_team," scores first (~30'): fair becomes ",n(t.if_home_scores_30)," — sell the ",a.home_team," leg above its fair, buy the crushed legs below theirs."]}),(0,b.jsxs)("div",{children:["⚽ If ",a.away_team," scores first (~30'): fair becomes ",n(t.if_away_scores_30),"."]}),(0,b.jsxs)("div",{children:["⚽ If it’s 1–1 around 60': fair becomes ",n(t.if_equalizer_60),"."]}),(0,b.jsx)("div",{className:"wc-power-sub",children:"The live fair values above keep updating with score and time. Risks this plan can’t remove: a 0-0 grind decays every leg, a single late goal gives one swing not three, and thin in-play books cost slippage."})]})]})}let r1={back_over:{label:"BACK OVER",cls:"wc-ai-over"},probe_under:{label:"PROBE UNDER",cls:"wc-ai-under"},back_under:{label:"BACK UNDER",cls:"wc-ai-under"},add_under:{label:"ADD UNDER",cls:"wc-ai-under"},hold_under:{label:"HOLD UNDER",cls:"wc-ai-under"},trim_under:{label:"TRIM UNDER",cls:"wc-ai-under-trim"},exit_under:{label:"EXIT UNDER",cls:"wc-ai-under-exit"},fade_favorite:{label:"SHADOW · FAVOURITE NO",cls:"wc-ai-fav"},back_favorite:{label:"BACK FAVOURITE",cls:"wc-ai-fav"},no_play:{label:"no play",cls:"wc-ai-none"}},r2={espn:{label:"ESPN",cls:"wc-src-espn"},isports:{label:"iSport",cls:"wc-src-isport"},apifootball:{label:"API-F",cls:"wc-src-apif"},livescore:{label:"Live",cls:"wc-src-live"},synthetic:{label:"AI",cls:"wc-src-synth"}},r5=["espn","isports","livescore","apifootball","synthetic"],r4={attacking:{icon:"⚔️",label:"Attacking",cls:"wc-mr-att"},balanced:{icon:"⚖️",label:"Balanced",cls:"wc-mr-bal"},defending:{icon:"🛡️",label:"Defending",cls:"wc-mr-def"},"parking-the-bus":{icon:"🚧",label:"Parking the bus",cls:"wc-mr-bus"}};function r3({eventId:e,live:t,home:a,away:s,active:r=!0}){let[n,l]=(0,_.useState)(null),[i,o]=(0,_.useState)(!1),[c,d]=(0,_.useState)(!1),[u,h]=(0,_.useState)(!0),p=(0,_.useRef)(!0),m=(t="")=>{o(!0),d(!0),(0,er.authGetJson)(`/api/worldcup/matches/${e}/match-read${"force"===t?"?force=1":""}`).then(e=>{p.current&&l(e.data||null)}
8).catch(()=>{}).finally(()=>{p.current&&o(!1)})};(0,_.useEffect)(()=>{if(r)return p.current=!0,h(!0),(0,er.authGetJson)(`/api/worldcup/matches/${e}/match-read?peek=1`).then(e=>{p.current&&(e.data?.phases?.length?(l(e.data),d(!0)):t&&m(""))}).catch(()=>{}).finally(()=>{p.current&&h(!1)}),()=>{p.current=!1}},[r,e,t]);let x=n?.home||a,g=n?.away||s,f=n?.phases||[],v=Math.max(1,...f.flatMap(e=>[e.home.danger,e.away.danger])),y=n?.read||{},j=y.home_posture?r4[y.home_posture]:null,w=y.away_posture?r4[y.away_posture]:null;return(0,b.jsxs)("div",{className:"radar-section wc-mr",children:[(0,b.jsxs)("div",{className:"radar-section-title",children:["🧠 Match Read — who's attacking, who's defending",t&&(0,b.jsx)("span",{className:"wc-ai-livedot",children:" 🔴 live"})]}),(0,b.jsx)("div",{className:"radar-section-note",children:"How each team's approach has shifted from kickoff to now — read from the run of play, not the scoreline."}),!c&&!u&&0===f.length&&(0,b.jsx)("button",{className:"wc-scout-run",onClick:()=>m(""),children:"▶ Read the match"}),i&&(0,b.jsxs)("div",{className:"wc-scout-loading",children:[(0,b.jsx)("span",{className:"chat-streaming-dot"})," Reading the tactics… (~5s)"]}),!i&&c&&0===f.length&&(0,b.jsx)("div",{className:"radar-section-note",children:n?.note||"No commentary to read yet."}),(j||w)&&(0,b.jsxs)("div",{className:"wc-mr-postures",children:[(0,b.jsxs)("div",{className:`wc-mr-team ${j?.cls||""}`,children:[(0,b.jsx)("div",{className:"wc-mr-team-name",children:x}),(0,b.jsxs)("div",{className:"wc-mr-badge",children:[j?.icon," ",j?.label||"—"]}),y.home_arc&&(0,b.jsx)("div",{className:"wc-mr-arc",children:y.home_arc})]}),(0,b.jsxs)("div",{className:"wc-mr-mom",children:[(0,b.jsx)("div",{className:"wc-power-sub",children:"momentum now"}),(0,b.jsx)("div",{className:"wc-mr-mom-arrow",children:"home"===y.momentum?`◄ ${x}`:"away"===y.momentum?`${g} ►`:"⚖ even"})]}),(0,b.jsxs)("div",{className:`wc-mr-team ${w?.cls||""}`,children:[(0,b.jsx)("div",{className:"wc-mr-team-name",children:g}),(0,b.jsxs)("div",{className:"wc-mr-badge",children:[w?.icon," ",w?.label||"—"]}),y.away_arc&&(0,b.jsx)("div",{className:"wc-mr-arc",children:y.away_arc})]})]}),f.length>0&&(0,b.jsxs)("div",{className:"wc-mr-grid",children:[(0,b.jsxs)("div",{className:"wc-mr-grid-head",children:[(0,b.jsxs)("span",{children:["◄ ",x]}),(0,b.jsx)("span",{children:"attacking pressure by phase"}),(0,b.jsxs)("span",{children:[g," ►"]})]}),f.map(e=>(0,b.jsxs)("div",{className:"wc-mr-row",children:[(0,b.jsxs)("div",{className:"wc-mr-bar wc-mr-bar-h",children:[e.home.goals>0&&(0,b.jsx)("span",{className:"wc-mr-goal",children:"⚽".repeat(e.home.goals)}),(0,b.jsx)("i",{style:{width:`${e.home.danger/v*100}%`},title:`${x}: ${e.home.danger} dangerous moments`})]}),(0,b.jsx)("div",{className:"wc-mr-phase",children:e.phase}),(0,b.jsxs)("div",{className:"wc-mr-bar wc-mr-bar-a",children:[(0,b.jsx)("i",{style:{width:`${e.away.danger/v*100}%`},title:`${g}: ${e.away.danger} dangerous moments`}),e.away.goals>0&&(0,b.jsx)("span",{className:"wc-mr-goal",children:"⚽".repeat(e.away.goals)})]})]},e.lo))]}),y.read&&(0,b.jsxs)("div",{className:"wc-mr-read",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("b",{children:"Read:"})," ",y.read]}),y.psychology&&(0,b.jsx)("div",{className:"wc-mr-psy",children:y.psychology})]}),f.length>0&&(0,b.jsxs)("div",{className:"wc-mr-foot",children:[(0,b.jsxs)("span",{className:"wc-power-sub",children:["saved snapshot",n?.last_minute!=null?` \xb7 as of ${n.last_minute}'`:"",t?" — press re-read for the latest":""]}),(0,b.jsx)("button",{className:"wc-scout-refresh",onClick:()=>m("force"),disabled:i,children:"↻ re-read (replace)"})]})]})}function r6({eventId:e,live:t,clock:a,active:s=!0}){let r,[n,l]=(0,_.useState)(null),[i,o]=(0,_.useState)(!1),[c,d]=(0,_.useState)(!1),[u,h]=(0,_.useState)(!1),[p,m]=(0,_.useState)({}),[x,g]=(0,_.useState)(null);(0,_.useEffect)(()=>{if(!s)return;let a=!0,r=()=>(0,er.authGetJson)(`/api/worldcup/matches/${e}/safety`).then(e=>{a&&g(e.data||null)}).catch(()=>{});if(r(),t){let e=window.setInterval(r,1e4);return()=>{a=!1,window.clearInterval(e)}}return()=>{a=!1}},[s,e,t]);let f=(0,_.useRef)(null),v=(0,_.useRef)(null),y=(0,_.useRef)(!0),j=(0,_.useRef)(!1),w=(0,_.useRef)(!1),N=(t=!1)=>{j.current||(j.current=!0,t&&o(!0),(0,er.authGetJson)(`/api/worldcup/matches/${e}/ai-replay?compute=0`).then(e=>{if(!y.current)return;let t=e.data||null;l(e=>!t||(!t.commentary||0===t.commentary.length)&&null==t.last_minute&&e&&((e.commentary?.length??0)>0||(e.signals?.length??0)>0)?e:t)}).catch(()=>{}).finally(()=>{j.current=!1,t&&o(!1)}))},k=()=>{s&&y.current&&!w.current&&(w.current=!0,d(!0),(0,er.authGetJson)(`/api/worldcup/matches/${e}/ai-replay?compute=8`).then(e=>{if(w.current=!1,!y.current)return;N(!1);let a=e.data?.next_decision!=null,s=(e.data?.computed??0)>0;a&&s?f.current=window.setTimeout(k,800):t?f.current=window.setTimeout(k,3e3):d(!1)}).catch(()=>{w.current=!1,y.current&&t?f.current=window.setTimeout(k,3e3):d(!1)}))},S=()=>{s&&(h(!0),N(!0),k(),t&&(v.current&&window.clearInterval(v.current),v.current=window.setInterval(()=>N(!1),3e3)))};(0,_.useEffect)(()=>(y.current=s,s)?(t?S():(h(!0),N(!0)),()=>{y.current=!1,f.current&&window.clearTimeout(f.current),v.current&&window.clearInterval(v.current)}):(o(!1),d(!1),()=>{y.current=!1,f.current&&window.clearTimeout(f.current),v.current&&window.clearInterval(v.current)}),[s,e,t]);let $=(t,a)=>{let s=`${t.minute}:${t.lane||t.signal}:${t.line??""}`,r=p[s]||{note:""};m(e=>({...e,[s]:{...r,verdict:a}})),(0,er.authPostJson)("/api/worldcup/ai-signal-feedback",{event_id:e,minute:t.minute,signal:t.signal,verdict:a,note:r.note||""}).catch(()=>{})},C=n?.signals||[],M=n?.under_checks||[],E=n?.corridors||[],A=n?.last_minute??null,T=a??A,F=null!=T&&null!=A&&T-A>=2;return(0,b.jsxs)("div",{className:"radar-section wc-ai",children:[(0,b.jsxs)("div",{className:"radar-section-title",children:["🤖 AI Live Read — signals as the match unfolds",t&&(0,b.jsx)("span",{className:"wc-ai-livedot",children:" 🔴 live · auto-updating"})]}),(0,b.jsxs)("div",{className:"radar-section-note",children:["Three independent lanes track the match: commentary can back an Over, the risk reader manages the Under ladder, and the moneyline lab records a shadow favorite-NO quote five minutes after a longshot scores first. The moneyline lab never submits an order. A lower Over and higher Under can both be valid as a range — no lane blocks another. Each call sees only the public state so far and shows when it ",(0,b.jsx)("b",{children:"first fired"})," and how long it ",(0,b.jsx)("b",{children:"held"})," (e.g. 34'→75') — one signal per conviction, not one per minute. Under calls hold unless invali
8dated."," ",t?"New signals appear as the read changes.":"Rate each call 👍/👎 (note the bad ones) so I can see what it got wrong and fix it."]}),(t||i||c)&&(0,b.jsx)("div",{className:"wc-ai-status",children:i||c?(0,b.jsxs)("span",{className:"wc-ai-reading",children:[(0,b.jsx)("span",{className:"chat-streaming-dot"})," AI reading the match…",null!=T?` (match at ${T}'${F?`, narration ${A}'`:""})`:""]}):t?(0,b.jsxs)("span",{className:"wc-power-sub",children:["⟳ watching live · checking every 3s",null!=T?` \xb7 match at ${T}'${F?` \xb7 narration ${A}'`:""}`:""]}):null}),!t&&n?.next_decision!=null&&!c&&(0,b.jsx)("button",{className:"wc-scout-run",onClick:S,children:"▶ read the rest of the match"}),i&&(0,b.jsxs)("div",{className:"wc-scout-loading",children:[(0,b.jsx)("span",{className:"chat-streaming-dot"})," Reading the match minute by minute… (~30s)"]}),!i&&u&&0===C.length&&(!n?.commentary||0===n.commentary.length)&&(0,b.jsx)("div",{className:"radar-section-note",children:n?.note||"No commentary to read for this match yet."}),u&&0===C.length&&(n?.commentary?.length??0)>0&&(0,b.jsx)("div",{className:"radar-section-note",children:"🤖 AI is watching the match — no bet worth making yet. It sits out quiet play and only calls a real edge (you'll see signals appear here when it does)."}),x&&x.rows.length>0&&(0,b.jsxs)("div",{className:"wc-safety",children:[(0,b.jsxs)("div",{className:"wc-safety-head",children:["🎯 Safety Meter ",(0,b.jsx)("span",{className:"wc-power-sub",children:"· history vs the price"})]}),x.regime&&(0,b.jsx)("div",{className:"wc-safety-regime",children:x.regime}),["full","2h","1h"].map(e=>{let t=x.rows.filter(t=>t.scope===e);if(!t.length)return null;let a=[];t.forEach(e=>{let t=e.edge_under,s=e.edge_over;null!=e.market_under&&(null!=s&&s>=.03?a.push({line:e.line,side:"OVER",edge:s,hist:e.p_over,cost:e.market_over??0}):null!=t&&t>=.03&&a.push({line:e.line,side:"UNDER",edge:t,hist:e.p_under,cost:e.market_under??0}))});let s=new Set(a.map(e=>e.line)),r=t.filter(e=>!s.has(e.line)).map(e=>e.line);return(0,b.jsxs)("div",{className:"wc-safety-scope",children:[(0,b.jsx)("div",{className:"wc-safety-scope-h",children:"full"===e?"Full match":"1h"===e?"1st half":"2nd half"}),a.map(e=>(0,b.jsxs)("div",{className:"wc-safety-pick",children:[(0,b.jsxs)("div",{className:"wc-safety-pick-top",children:[(0,b.jsxs)("span",{className:"wc-safety-line",children:["Over ",e.line]}),(0,b.jsxs)("span",{className:"wc-safety-edge up",children:["✅ ",e.side," looks cheap +",Math.round(100*e.edge),"¢"]})]}),(0,b.jsxs)("div",{className:"wc-safety-why",children:["history ",Math.round(100*e.hist),"% · costs ~",Math.round(100*e.cost),"¢"]})]},e.line)),r.length>0&&(0,b.jsxs)("div",{className:"wc-safety-fair",children:["Over ",r.join(" · "),(0,b.jsx)("span",{className:"wc-safety-fair-tag",children:"fair"})]})]},e)}),(0,b.jsx)("div",{className:"wc-power-sub wc-safety-foot",children:"From 314 past matches. The market already prices most of this in — a nudge, size small."})]}),n?.match_stakes&&(0,b.jsxs)("div",{className:"wc-stakes",children:[(0,b.jsxs)("div",{className:"wc-stakes-head",children:["🎯 What's at stake",(0,b.jsxs)("span",{className:"wc-power-sub",children:[" — ","group"===n.match_stakes.stage?`${n.match_stakes.group}${n.match_stakes.decisive?" · final round — decides who goes through":` \xb7 matchday ${n.match_stakes.matchday}`}`:`${n.match_stakes.round} \xb7 single-leg knockout — loser is out`]})]}),n.match_stakes.teams&&(0,b.jsx)("div",{className:"wc-stakes-teams",children:Object.entries(n.match_stakes.teams).map(([e,t])=>{let a=function(e){switch(e.needed){case"through":return{t:"✅ THROUGH",c:"wc-stakes-b-thru"};case"draw_secures":return{t:"🤝 a draw is enough",c:"wc-stakes-b-draw"};case"must_win":return{t:"⚔️ must win",c:"wc-stakes-b-win"};case"needs_help":return{t:"🎲 win + other results",c:"wc-stakes-b-help"};case"eliminated":return{t:"❌ can't qualify",c:"wc-stakes-b-out"};default:return null}}(t);return(0,b.jsxs)("div",{className:`wc-stakes-team${t.content?" wc-stakes-content":""}`,children:[(0,b.jsx)("b",{children:e}),a&&(0,b.jsx)("span",{className:`wc-stakes-need ${a.c}`,children:a.t}),t.text&&(0,b.jsxs)("span",{className:"wc-power-sub",children:[" — ",t.text]})]},e)})}),n.match_stakes.table&&n.match_stakes.table.length>0&&(0,b.jsxs)("div",{className:"wc-stakes-table",children:[n.match_stakes.table.map(e=>(0,b.jsxs)("div",{className:`wc-stakes-row${(e.rank??9)<=2?" wc-stakes-qual":""}${n.match_stakes.teams&&n.match_stakes.teams[e.team]?" wc-stakes-inmatch":""}`,children:[(0,b.jsx)("span",{className:"wc-stakes-rank",children:e.rank}),(0,b.jsxs)("span",{className:"wc-stakes-tn",children:[e.team,e.advanced?" ✅":""]}),(0,b.jsxs)("span",{className:"wc-stakes-pts",children:[e.points??0," pts"]}),(0,b.jsxs)("span",{className:"wc-power-sub",children:[(e.gd??0)>=0?`+${e.gd??0}`:e.gd," GD"]})]},e.team)),(0,b.jsx)("div",{className:"wc-power-sub wc-stakes-legend",children:"green = currently qualifying (top 2) · ✅ = already through"})]}),(0,b.jsxs)("div",{className:"wc-stakes-tilt",children:["📋 ",n.match_stakes.summary]}),n.match_stakes.note&&(0,b.jsx)("div",{className:"wc-power-sub wc-stakes-note",children:n.match_stakes.note})]}),n?.coach?.moves&&Object.keys(n.coach.moves).length>0&&(0,b.jsxs)("div",{className:"wc-coach",children:[(0,b.jsxs)("div",{className:"wc-coach-head",children:["🧠 Coach's Hand ",(0,b.jsx)("span",{className:"wc-power-sub",children:"— what the managers are doing with subs (reads into over/under)"})]}),n.coach.read&&(0,b.jsx)("div",{className:"wc-coach-read",children:n.coach.read}),(0,b.jsx)("div",{className:"wc-coach-teams",children:Object.entries(n.coach.moves).map(([e,t])=>(0,b.jsxs)("div",{className:"wc-coach-team",children:[(0,b.jsxs)("div",{className:"wc-coach-team-head",children:[(0,b.jsx)("b",{children:e}),(0,b.jsx)("span",{className:`wc-coach-sl wc-coach-sl-${t.scoreline}`,children:t.scoreline})]}),t.subs.map((e,t)=>{let a="attack"===e.removed_role?{t:"▼ attacker off",c:"wc-coach-off-att"}:"defense"===e.removed_role?{t:"▲ defender off",c:"wc-coach-off-def"}:{t:"• mid off",c:"wc-coach-off-mid"};return(0,b.jsxs)("div",{className:"wc-coach-sub",children:[(0,b.jsxs)("span",{className:"wc-coach-min",children:[e.minute,"'"]}),(0,b.jsx)("span",{className:`wc-coach-tag ${a.c}`,children:a.t}),(0,b.jsxs)("span",{className:"wc-coach-players",children:[(0,b.jsx)("b",{children:e.on})," ← ",e.off,e.off_position?(0,b.jsxs)("span",{className:"wc-power-sub",children:[" (",e.off_position,")"]}):null]})]},t)})]},e))})]}),(t||M.length>0||E.length>0)&&(0,b.jsxs)("div",{className:"wc-range-desk",children:[(0,b.jsxs)("div",{className:"wc-range-head",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{className:"wc-range-kicker",children:"RANGE DESK // UNDER CHECKPOINTS"}),(0,b.jsx)("div",{className:"wc-range-title",children:"The Under lane never suppresses the main read."})]}),(0,b.jsx)("span",{className:"wc-range-next",children:n?.next_under_checkpoint!=null?`next review ${n.next_under_checkpoint}'`:M.some(e=>["probe","entry","add","hold"].includes(e.status))?"UNDER MANAGED":"reviews complete"})]}),(0,b.jsx)("div",{className:"wc-range-checks",children:(n?.under_review_minutes||[20,25,30,35,40,42,45,50,55,58,60,65,70,75,80,85]).map(e=>{let t=M.find(t=>t.minute===e),a=t?.status||(null!=T&&e<T-2?"missed":"pending"),s="entry"===a?"BUY":"probe"===a?"PROBE":"add"===a?"ADD":"hold"===a?"HOLD":"trim"===a?"TRIM":"exit"===a?"EXIT":"rejected"===a?"NO PLAY":a.toUpperCase();return(0,b.jsxs)("div",{className:`wc-range-check ${a}`,title:t?.reason||void 0,children:[(0,b.jsxs)("span",{children:[e,"'"]}),(0,b.jsx)("b",{children:s})]},e)})}),M.length>0&&(r=M[M.length-1],(0,b.jsxs)("div",{className:`wc-range-audit ${r.status}`,children:[(0,b.jsx)("span",{className:"wc-range-audit-mark",children:"rejected"===r.status?"×":"exit"===r.status?"↘":"✓"}),(0,b.jsxs)("div",{children:[(0,b.jsxs)("b",{children:[r.minute,"' Under review — ",r.status]}),(0,b.jsx)("span",{children:r.reason||"No reason recorded."})]})]})),E.map(e=>(0,b.jsxs)("div",{className:"wc-corridor-card",children:[(0,b.jsxs)("div",{className:"wc-corridor-window",children:[(0,b.jsx)("span",{children:"PROFIT WINDOW"}),(0,b.jsxs)("strong",{children:[e.landing_label," GOALS"]}),(0,b.jsx)("small",{children:"both legs win inside this range"})]}),(0,b.jsxs)("div",{className:"wc-corridor-rails",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{children:"FLOOR"}),(0,b.jsxs)("b",{children:["OVER ",e.floor_line]}),(0,b.jsxs)("em",{children:[Math.round(100*e.over_price),"¢"]})]}),(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{children:"CEILING"}),(0,b.jsxs)("b",{children:["UNDER ",e.ceiling_line]}),(0,b.jsxs)("em",{children:[Math.round(100*e.under_price),"¢"]})]})]}),(0,b.jsxs)("div",{className:"wc-corridor-payoff",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{children:"PAIR COST"}),(0,b.jsxs)("b",{children:[Math.round(100*e.package_cost),"¢"]})]}),(0,b.jsxs)("div",{className:"inside",children:[(0,b.jsxs)("span",{children:["LANDS ",e.landing_label]}),(0,b.jsxs)("b",{children:[e.inside_pnl>=0?"+":"",Math.round(100*e.inside_pnl),"¢"]})]}),(0,b.jsxs)("div",{className:"outside",children:[(0,b.jsx)("span",{children:"OUT
8SIDE RANGE"}),(0,b.jsxs)("b",{children:[e.outside_pnl>=0?"+":"",Math.round(100*e.outside_pnl),"¢"]})]})]}),(0,b.jsx)("div",{className:"wc-corridor-warning",children:"Per one paired share · not a guaranteed hedge: outside the corridor only one leg pays."})]},`${e.minute}:${e.floor_line}:${e.ceiling_line}`))]}),C.length>0&&(0,b.jsxs)("div",{className:"wc-ai-timeline",children:[n?.final_score&&(0,b.jsxs)("div",{className:"wc-power-sub",children:["Final score ",n.final_score," · favourite: ",n.favorite," — judge each call against how it actually played out."]}),C.map(e=>{let t=r1[e.signal]||r1.no_play,a=`${e.minute}:${e.lane||e.signal}:${e.line??""}`,s=p[a],r=e.trade_plan,n=["sell_now","exit"].includes(String(r?.action||""));return(0,b.jsxs)("div",{className:`wc-ai-row${"no_play"===e.signal?" wc-ai-row-idle":""}${n?" wc-ai-row-exit":""}`,children:[(0,b.jsxs)("div",{className:"wc-ai-min",children:[e.held_from??e.minute,"'",null!=e.held_to&&e.held_to!==(e.held_from??e.minute)&&(0,b.jsxs)("span",{className:"wc-ai-held-to",children:["→",e.held_to,"'"]}),(0,b.jsx)("div",{className:"wc-power-sub",children:e.score}),"no_play"!==e.signal&&(e.held_count??1)>1&&(0,b.jsx)("div",{className:"wc-power-sub wc-ai-held-note",children:e.active?"● still holding":`held ${e.held_count}m`})]}),(0,b.jsxs)("div",{className:"wc-ai-body",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{className:`wc-ai-badge ${t.cls}`,children:t.label})," ",e.bet&&"no_play"!==e.signal?(0,b.jsx)("b",{children:e.bet}):null," ",(0,b.jsxs)("span",{className:"wc-power-sub",children:["(",e.confidence,")"]}
8),"under"===e.lane&&"no_play"!==e.signal&&(0,b.jsxs)("span",{className:"wc-power-sub",children:[" · recurring review",null!=e.entry_price?` \xb7 ${Math.round(100*e.entry_price)}\xa2`:""]}),"moneyline"===e.lane&&(0,b.jsxs)("span",{className:"wc-power-sub",children:[" · direct NO ask",null!=e.entry_price?` \xb7 ${Math.round(100*e.entry_price)}\xa2`:""]})]}),(0,b.jsx)("div",{className:"wc-ai-reason",children:e.reason}),r?.strategy==="favorite_comeback"&&(0,b.jsxs)("div",{className:`wc-ai-plan wc-ai-plan-fav${n?" exit":""}`,children:[(0,b.jsx)("div",{className:"wc-ai-plan-head",children:n?"⚡ EXIT NOW — SELL THE COMEBACK":"↗ EQUALIZER SCALP PLAN"}),(0,b.jsxs)("div",{children:[null!=r.target_price?(0,b.jsxs)(b.Fragment,{children:["AI target ",(0,b.jsxs)("b",{children:[Math.round(100*r.target_price),"¢"]})," · "]}):null,(0,b.jsx)("b",{children:"Exit trigger: equalizer"}),null!=r.sell_fraction_at_target?(0,b.jsxs)(b.Fragment,{children:[" · sell ",(0,b.jsxs)("b",{children:[Math.round(100*r.sell_fraction_at_target),"%"]})]}):null,null!=r.residual_fraction_at_target?(0,b.jsxs)(b.Fragment,{children:[" · retain ",(0,b.jsxs)("b",{children:[Math.round(100*r.residual_fraction_at_target),"%"]})," house money"]}):null]}),(0,b.jsx)("div",{children:n?"The target or equalizer arrived. Do not hold the full moneyline for the final result.":"Exit immediately on the equalizer. The thesis is the bounce, not that the favourite wins."})]}),r?.strategy==="favorite_fade"&&(0,b.jsxs)("div",{className:"wc-ai-plan wc-ai-plan-fav",children:[(0,b.jsx)("div",{className:"wc-ai-plan-head",children:"◌ RESEARCH SHADOW — NO ORDER"}),(0,b.jsxs)("div",{children:[(0,b.jsx)("b",{children:"Observe the favourite-NO token to settlement."})," This records a forward exact-tape sample and never submits a trade."]}),null!=r.archive_sample_size&&null!=r.archive_roi&&(0,b.jsxs)("div",{className:"wc-ai-plan-muted",children:["reconstructed archive: ",r.archive_sample_size," · ",Math.round(100*Number(r.archive_hit_rate||0)),"% hit · ",(100*r.archive_roi).toFixed(1),"% ROI",null!=r.exact_sample_size&&null!=r.exact_roi?` \xb7 exact tape: ${r.exact_sample_size} \xb7 ${Math.round(100*Number(r.exact_hit_rate||0))}% hit \xb7 ${(100*r.exact_roi).toFixed(1)}% ROI`:""]})]}),r?.strategy==="disciplined_under"&&(0,b.jsxs)("div",{className:"wc-ai-plan wc-ai-plan-under",children:[(0,b.jsx)("div",{className:"wc-ai-plan-head",children:"small_starter"===r.action?"◎ SMALL PROBE":"add"===r.action?"+ ADD TO UNDER":"trim"===r.action?"↘ TAKE PARTIAL PROFIT":"exit"===r.action?"⚡ EXIT UNDER":"⌛ MANAGE TIME DECAY"}),(0,b.jsx)("div",{children:"small_starter"===r.action?"Starter size only while the tape and live thesis confirm.":r.hold_policy||"Hold unless fresh evidence invalidates the thesis."}),r.invalidation&&(0,b.jsxs)("div",{className:"wc-ai-plan-muted",children:["Invalidate only for: ",r.invalidation,"."]})]}),e.polymarket_url&&"no_play"!==e.signal&&(0,b.jsxs)("a",{className:"wc-ai-link",href:e.polymarket_url,target:"_blank",rel:"noreferrer",children:["↗ ","fade_favorite"===e.signal?"inspect on Polymarket":"trade on Polymarket"]})]}),"no_play"!==e.signal&&(0,b.jsxs)("div",{className:"wc-ai-fb",children:[(0,b.jsx)("button",{className:`wc-ai-fb-btn${s?.verdict==="good"?" on":""}`,title:"good call",onClick:()=>$(e,"good"),children:"👍"}),(0,b.jsx)("button",{className:`wc-ai-fb-btn${s?.verdict==="bad"?" on":""}`,title:"bad call",onClick:()=>$(e,"bad"),children:"👎"}),(0,b.jsx)("input",{className:"wc-ai-note",placeholder:"what went wrong?",value:s?.note||"",onChange:e=>m(t=>({...t,[a]:{...t[a]||{},note:e.target.value}}))})]})]},a)}),(0,b.jsx)("button",{className:"wc-scout-refresh",onClick:S,children:"↻ re-read"})]}),n?.commentary&&n.commentary.length>0&&(0,b.jsxs)("div",{className:"wc-ai-term",children:[(0,b.jsxs)("div",{className:"wc-ai-term-bar",children:[(0,b.jsxs)("span",{className:"wc-ai-term-dots",children:[(0,b.jsx)("i",{}),(0,b.jsx)("i",{}),(0,b.jsx)("i",{})]}),(0,b.jsxs)("span",{className:"wc-ai-term-title",children:["narration.log",t?" — live":""]}),n?.feeds&&Object.keys(n.feeds).length>0&&(0,b.jsx)("span",{className:"wc-ai-term-feeds",title:"each feed's latest minute — proof every source is live (the freshest fills ESPN's lag)",children:r5.filter(e=>null!=n.feeds[e]).map(e=>{let t=r2[e];return(0,b.jsxs)("span",{className:`wc-ai-feed ${t?.cls||""}`,children:[t?.label||e," ",n.feeds[e],"'"]},e)})})]}),(0,b.jsxs)("div",{className:"wc-ai-term-body",children:[t&&(0,b.jsxs)("div",{className:"wc-ai-term-line wc-ai-term-wait",children:["▌ streaming — match at ",T??0,"'",F?` \xb7 narration at ${A}'`:"",c?" · AI reading…":""]}),[...n.commentary].reverse().map((e,t)=>{let a=r2[e.source||""]||(e.source?{label:e.source,cls:""}:null);return(0,b.jsxs)("div",{className:"wc-ai-term-line",children:[(0,b.jsx)("span",{className:"wc-ai-term-min",children:e.disp||(null!=e.minute?`${e.minute}'`:"·")}),a&&(0,b.jsx)("span",{className:`wc-ai-term-src ${a.cls}`,children:a.label}),(0,b.jsx)("span",{className:"wc-ai-term-txt",children:e.text})]},t)})]})]})]})}function r8({eventId:e}
8){let[t,a]=(0,_.useState)(null),[s,r]=(0,_.useState)(!1),[n,l]=(0,_.useState)(!1),i=(t=!1)=>{r(!0),l(!0),a(null),(0,er.authGetJson)(`/api/worldcup/matches/${e}/scout${t?"?force=1":""}`).then(e=>a(e.data||null)).catch(()=>a(null)).finally(()=>r(!1))},o=t&&!t.error&&(t.headline||t.blind_spots&&t.blind_spots.length>0)?t:null;return(0,b.jsxs)("div",{className:"radar-section wc-scout",children:[(0,b.jsx)("div",{className:"radar-section-title",children:"🔮 AI Scout — what the model can’t see"}),(0,b.jsxs)("div",{className:"radar-section-note",children:["The model is pure Elo + goal math, so it’s blind to ",(0,b.jsx)("b",{children:"team news"}),". The scout reads live injuries, suspensions, lineups & motivation, then flags where reality diverges from the model — grounded in real sources."]}),!n&&(0,b.jsx)("button",{className:"wc-scout-run",onClick:()=>i(),children:"⚡ Run scout — scan live team news"}),s&&(0,b.jsxs)("div",{className:"wc-scout-loading",children:[(0,b.jsx)("span",{className:"chat-streaming-dot"})," Scanning current team news, injuries & lineups… (~20s)"]}),!s&&n&&!o&&(0,b.jsxs)("div",{className:"radar-section-note",children:["No usable team news found right now — the model read stands on its own."," ",(0,b.jsx)("button",{className:"wc-scout-refresh",onClick:()=>i(),children:"Try again"})]}),o&&(0,b.jsxs)("div",{className:"wc-scout-body",children:[(0,b.jsxs)("div",{className:"wc-scout-top",children:[(0,b.jsx)("div",{className:"wc-scout-headline",children:o.headline}),o.confidence&&(0,b.jsxs)("span",{className:`wc-scout-conf wc-scout-conf-${o.confidence}`,children:[o.confidence," confidence",o.news_count?` \xb7 ${o.news_count} sources`:""]})]}),o.net_read&&(0,b.jsxs)("div",{className:"wc-scout-net",children:[(0,b.jsx)("b",{children:"Bottom line:"})," ",o.net_read]}),o.blind_spots&&o.blind_spots.length>0&&(0,b.jsxs)("div",{className:"wc-scout-blocks",children:[(0,b.jsx)("div",{className:"wc-scout-subhead",children:"Edges the model is blind to"}),o.blind_spots.map((e,t)=>(0,b.jsxs)("div",{className:"wc-scout-blind",children:[(0,b.jsxs)("div",{className:"wc-scout-blind-head",children:[(0,b.jsx)("span",{className:"wc-scout-affects",children:e.affects}),(0,b.jsx)("span",{className:"wc-scout-lean",children:e.lean})]}),(0,b.jsx)("div",{className:"wc-scout-insight",children:e.insight}),(0,b.jsxs)("div",{className:"wc-scout-why",children:["why the model misses it: ",e.why_model_misses]})]},t))]}),o.teams&&o.teams.length>0&&(0,b.jsx)("div",{className:"wc-scout-teams",children:o.teams.map((e,t)=>(0,b.jsxs)("div",{className:"wc-scout-team",children:[(0,b.jsxs)("div",{className:"wc-scout-team-head",children:[e.team," ",(0,b.jsxs)("span",{className:"wc-power-sub",children:["(",e.side,")"]})]}),(0,b.jsx)("div",{className:"wc-scout-verdict",children:e.availability_verdict}),e.key_absences&&e.key_absences.length>0?(0,b.jsx)("ul",{className:"wc-scout-absences",children:e.key_absences.map((e,t)=>(0,b.jsxs)("li",{children:[(0,b.jsx)("b",{children:e.name})," ",(0,b.jsx)("span",{className:"wc-scout-issue",children:e.issue})," — ",e.impact]},t))}):(0,b.jsx)("div",{className:"wc-power-sub",children:"No absences reported."}),e.motivation&&(0,b.jsxs)("div",{className:"wc-scout-motiv",children:["🎯 ",e.motivation]})]},t))}),o.what_to_watch&&o.what_to_watch.length>0&&(0,b.jsxs)("div",{className:"wc-scout-watch",children:[(0,b.jsx)("b",{children:"Watch before kickoff:"}),(0,b.jsx)("ul",{children:o.what_to_watch.map((e,t)=>(0,b.jsx)("li",{children:e},t))})]}),(0,b.jsxs)("div",{className:"wc-scout-foot",children:[o.sources&&o.sources.length>0&&(0,b.jsxs)("span",{className:"wc-scout-sources",children:[(0,b.jsx)("span",{className:"wc-power-sub",children:"Sources:"})," ",o.sources.map((e,t)=>(0,b.jsxs)("a",{href:e.url,target:"_blank",rel:"noopener noreferrer",title:e.title,children:["[",t+1,"]"]},t))]}),(0,b.jsx)("button",{className:"wc-scout-refresh",onClick:()=>i(!0),disabled:s,title:"This report is a snapshot. Re-read to pick up the current lineup, score, subs and cards.",children:"↻ re-read (replace)"})]})]})]})}function r9(){let[e,t]=(0,_.useState)(null);if((0,_.useEffect)(()=>{let e=!0;return(0,er.authGetJson)("/api/worldcup/signal-stats").then(a=>{e&&t(a.data||null)}
8).catch(()=>{}),()=>{e=!1}},[]),!e||!e.types)return null;let a=(t,a)=>a&&null!=a.pct?(0,b.jsxs)("span",{className:"wc-chip",title:`${a.n} graded calls since ${e.since}`,children:[t," ",(0,b.jsxs)("b",{children:[a.pct,"%"]}),null!=a.roi_per_dollar?(0,b.jsxs)("span",{className:a.roi_per_dollar>=0?"radar-up":"radar-down",children:[" ",a.roi_per_dollar>=0?"+":"",a.roi_per_dollar,"/$"]}):null]}):null,s=e.goal_latency?Object.entries(e.goal_latency).sort((e,t)=>e[1].median_behind_s-t[1].median_behind_s)[0]:null;return(0,b.jsxs)("div",{className:"wc-trust",children:[(0,b.jsxs)("span",{className:"wc-power-sub",children:["graded live since ",e.since,":"]}),a("overs",e.types.back_over),a("favorites",e.types.back_favorite),s?(0,b.jsxs)("span",{className:"wc-power-sub",children:["· fastest goal feed: ",s[0]]}):null]})}function r7({eventId:e,home:t,away:a}){let[s,r]=(0,_.useState)(null),[n,l]=(0,_.useState)("SportMonks");if((0,_.useEffect)(()=>{let t=!0;return(0,er.authGetJson)(`/api/worldcup/matches/${e}/lineups`).then(e=>{t&&(r(e.data||null),e.source&&l(e.source))}).catch(()=>{}),()=>{t=!1}},[e]),!s||!s.home?.xi?.length&&!s.away?.xi?.length)return null;let i=(e,t)=>(0,b.jsxs)("div",{className:"wc-lu-col",children:[(0,b.jsxs)("div",{className:"wc-lu-team",children:[t,e.formation?(0,b.jsxs)("span",{className:"wc-power-sub",children:[" · ",e.formation]}):null]}),(e.xi||[]).map((e,t)=>(0,b.jsxs)("div",{className:"wc-lu-p",children:[(0,b.jsx)("span",{className:"wc-lu-num",children:e.number})," ",e.name]},t)),(e.bench||[]).length>0?(0,b.jsxs)("div",{className:"wc-lu-bench",children:["Bench: ",e.bench.map(e=>e.name).join(", ")]}):null]});return(0,b.jsxs)("div",{className:"radar-section wc-lu",children:[(0,b.jsxs)("div",{className:"radar-section-title",children:["📋 Lineups ",(0,b.jsxs)("span",{className:"wc-power-sub",children:["· ",n]})]}),(0,b.jsxs)("div",{className:"wc-lu-grid",children:[i(s.home,t||"Home"),i(s.away,a||"Away")]})]})}let ne={goals:"Goals",ml:"Result",btts:"Both teams to score",corners:"Corners"},nt=["ml","goals","btts","corners"];function na({eventId:e,active:t=!0}){let[a,s]=(0,_.useState)(null);(0,_.useEffect)(()=>{if(!t)return;let e=!0,a=null,r=()=>(0,er.authGetJson)("/api/worldcup/odds-edge/status").then(t=>{e&&s(t.data||null)}).catch(()=>{}).finally(()=>{e&&(a=window.setTimeout(r,1e4))});return r(),()=>{e=!1,null!=a&&window.clearTimeout(a)}},[t,e]);let r=(a?.live||[]).filter(t=>t.series.startsWith(e+":"));if(0===r.length)return null;let n={};for(let e of r)(n[e.market]||=[]).push(e);return(0,b.jsxs)("div",{className:"radar-section wc-oe",children:[(0,b.jsxs)("div",{className:"radar-section-title",children:["📊 Sharp odds vs Polymarket ",(0,b.jsx)("span",{className:"wc-power-sub",children:"· SportMonks in-play (observe-only)"})]}),a?.analysis?.verdict?(0,b.jsx)("div",{className:"wc-oe-verdict",children:a.analysis.verdict}):null,nt.filter(e=>n[e]).map(e=>(0,b.jsxs)("div",{className:"wc-oe-mkt",children:[(0,b.jsx)("div",{className:"wc-oe-mkt-h",children:ne[e]||e}),n[e].map(e=>{let t=Math.round(100*e.gap),a=t<=-3?{t:`PM cheap +${-t}\xa2`,c:"up"}:t>=3?{t:`PM rich −${t}\xa2`,c:"down"}:{t:"aligned",c:"flat"};return(0,b.jsxs)("div",{className:"wc-oe-row",children:[(0,b.jsx)("span",{className:"wc-oe-line",children:e.label}),(0,b.jsxs)("span",{className:"wc-oe-nums",children:["sharp ",(0,b.jsxs)("b",{children:[Math.round(100*e.sm_fair),"%"]})," · PM ",(0,b.jsxs)("b",{children:[Math.round(100*e.pm_mid),"¢"]})]}),(0,b.jsx)("span",{className:`wc-oe-read ${a.c}`,children:a.t})]},e.series)})]},e)),(0,b.jsx)("div",{className:"wc-power-sub wc-oe-foot",children:"Sharp bookmaker consensus (120+ books, ~5s) vs Polymarket across result, goals & BTTS. If the odds lead, PM-cheap = buy / PM-rich = sell — still proving the lead, no trades yet."})]})}function ns({eventId:e,home:t,away:a,active:s=!0,live:r=!1}){let[n,l]=(0,_.useState)(null),[i,o]=(0,_.useState)(!0),[c,d]=(0,_.useState)(""),[u,h]=(0,_.useState)(0),[p,m]=(0,_.useState)({}),[x,g]=(0,_.useState)(!1),[f,v]=(0,_.useState)({});(0,_.useEffect)(()=>{if(!s)return;let t=!1,a=null;o(!0),d("");let n=()=>(0,er.authGetJson)(`/api/worldcup/matches/${e}/smart-money`).then(e=>{t||(l(e.data||null),d(""))}).catch(()=>{t||d("Smart-money scan failed; the last good result is preserved.")}).finally(()=>{!t&&(o(!1),r&&(a=window.setTimeout(n,6e4)))});return n(),()=>{t=!0,null!=a&&window.clearTimeout(a)}},[s,e,r,u]);let y=n?.traders||[];if(i)return(0,b.jsxs)("div",{className:"radar-section",children:[(0,b.jsx)("div",{className:"radar-section-title",children:"Smart money in this match"}),(0,b.jsx)("div",{className:"radar-section-note",children:"Reading credible traders across every market…"})]});let j=n?.consensus||null,w=j?.landscape||null;return(0,b.jsxs)("div",{className:"radar-section",children:[(0,b.jsxs)("div",{className:"radar-section-title",children:["🧠 Smart Money",j?(0,b.jsxs)("span",{className:"wc-power-sub",children:[" · ",j.n_directional," directional sharps · ",rp(j.total_capital),j.n_market_makers?` \xb7 ${j.n_market_makers} two-sided book${1===j.n_market_makers?"":"s"} analyzed`:""]}):null]}),c&&(0,b.jsxs)("div",{className:"radar-section-note",children:[c," ",(0,b.jsx)("button",{className:"wc-scout-refresh",onClick:()=>h(e=>e+1),children:"retry"})]}),!c&&0===y.length&&(0,b.jsxs)("div",{className:"radar-section-note",children:["No watched or qualified smart-money wallet currently holds a visible position in this match",n?.scanned!=null?` \xb7 ${n.scanned} holder wallets scanned`:"",". Live matches rescan automatically."]}),j&&(0,b.jsxs)("div",{className:"wc-sm-consensus",children:[w?(0,b.jsxs)("div",{className:`wc-sm-landscape ${w.winner_lean}`,children:[(0,b.jsxs)("div",{className:"wc-sm-landscape-kicker",children:[(0,b.jsx)("span",{children:"ai"===w.mode?"AI MONEY LANDSCAPE":"MONEY LANDSCAPE · AI RETRYING"}),(0,b.jsxs)("span",{className:`wc-sm-landscape-confidence ${w.confidence}`,children:[w.confidence," confidence"]}),(0,b.jsxs)("span",{className:"wc-sm-landscape-winner",children:["WINNER READ · ",w.winner_label]})]}),(0,b.jsx)("div",{className:"wc-sm-landscape-headline",children:w.headline}),(0,b.jsx)("div",{className:"wc-sm-landscape-summary",children:w.summary}),w.key_traders.length>0&&(0,b.jsx)("div",{className:"wc-sm-landscape-traders",children:w.key_traders.map(e=>(0,b.jsxs)("div",{className:`wc-sm-landscape-trader${e.priority?" priority":""}`,children:[(0,b.jsxs)("div",{className:"wc-sm-landscape-trader-head",children:[(0,b.jsx)("a",{className:"radar-link",href:`https://polymarket.com/profile/${e.wallet}`,target:"_blank",rel:"noreferrer",children:e.name}),e.priority&&(0,b.jsx)("span",{className:"wc-sm-priority",children:"FOCUS"}),(0,b.jsx)("span",{className:"wc-sm-landscape-stance",children:e.stance})]}),(0,b.jsx)("div",{className:"wc-sm-landscape-thesis",children:e.thesis}),(0,b.jsxs)("div",{className:"wc-sm-landscape-exposure",children:[(0,b.jsxs)("span",{className:"main",children:[(0,b.jsx)("b",{children:"BIGGEST"})," ",(0,b.jsx)("span",{className:`wc-sm-sig-lean ${e.main_side}`,children:e.main_side.toUpperCase()})," ",e.main_bag," · ",(0,b.jsx)("strong",{children:rp(e.main_usd)})]}),(0,b.jsxs)("span",{className:e.hedged?"hedged":"unhedged",children:[(0,b.jsx)("b",{children:e.hedged?"HEDGE":"NO HEDGE"}),e.hedged?` ${rp(e.hedge_usd)} \xb7 ${Math.round(100*e.hedge_ratio)}% of biggest bag`:" against biggest bag"]})]}),(0,b.jsx)("div",{className:"wc-sm-landscape-hedge-read",children:e.hedge_read})]},e.wallet))})]}):(0,b.jsx)("div",{className:"wc-sm-landscape-loading",children:"AI is mapping the whole-match positions…"}),(0,b.jsx)("div",{className:"wc-sm-cons-cat-h wc-sm-map-title",children:"Position-weighted market map"}),j.categories.map(e=>(0,b.jsxs)("div",{className:"wc-sm-cons-cat",children:[(0,b.jsx)("div",{className:"wc-sm-cons-cat-h",children:e.category}),e.signals.map((e,t)=>(0,b.jsxs)("div",{className:"wc-sm-sig",children:[(0,b.jsx)("span",{className:"wc-sm-sig-name",children:e.outcome}),(0,b.jsx)("span",{className:`wc-sm-sig-lean ${e.side}`,children:e.side.toUpperCase()}),(0,b.jsx)("span",{className:"wc-sm-bar",children:(0,b.jsx)("span",{className:`wc-sm-bar-fill ${e.side}`,style:{width:`${Math.round(100*e.strength)}%`}})}),(0,b.jsxs)("span",{className:"wc-sm-sig-net",children:[rp(e.net),(0,b.jsxs)("span",{className:"wc-power-sub",children:[" · ",e.n_yes," yes / ",e.n_no," no",null!=e.avg_winrate?` \xb7 ${Math.round(100*e.avg_winrate)}% wr`:""]})]})]},t))]},e.category)),(0,b.jsx)("div",{className:"wc-power-sub wc-sm-cons-foot",children:"AI reads every current position, including two-sided books. Biggest-bag and hedge dollars are recomputed from exact open legs; the compact bars isolate directional exposure."})]}),n?.tape&&("live"===n.tape.mode||"audit"===n.tape.mode)&&(0,b.jsxs)("div",{className:"wc-sm-consensus wc-sm-tape",children:["live"===n.tape.mode&&(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)("div",{className:"wc-sm-cons-cat-h",children:"🎬 Match tape — live flow (last 12 min)"}),n.tape.flow&&n.tape.flow.length>0?n.tape.flow.map((e,s)=>(0,b.jsxs)("div",{className:"wc-sm-sig",children:[(0,b.jsxs)("a",{className:"radar-link wc-sm-sig-name",href:`https://polymarket.com/profile/${e.wallet}`,target:"_blank",rel:"noreferrer",children:[e.name||`${e.wallet.slice(0,6)}…`,n.tape.proven_wallets?.includes(e.wallet)?" 🎬":""]}),(0,b.jsx)("span",{className:`wc-sm-sig-lean ${e.net_usd>=0?"yes":"no"}`,children:e.net_usd>=0?"BUYING":"DUMPING"}),(0,b.jsxs)("span",{className:"wc-sm-sig-net",children:[function(e,t,a){let s=e.endsWith(" NO"),r=s?e.slice(0,-3):e;if(r.startsWith("over:"))return s?`Under ${r.slice(5)}`:`Over ${r.slice(5)}`;if("ml:draw"===r)return s?"No draw":"Draw";let n="ml:home"===r?t||"Home":"ml:away"===r?a||"Away":r;return s?`against ${n}`:`${n} win`}(e.market,t,a)," · ",(0,b.jsx)("b",{children:rp(Math.abs(e.net_usd))})]})]},s)):(0,b.jsx)("div",{className:"wc-power-sub",children:n.tape.capturing?"No wallet moving ≥$200 in the last 12 min.":"Tape recorder warming up — first fills land within a minute of 
8kickoff."})]}),"audit"===n.tape.mode&&n.tape.audit&&(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)("div",{className:"wc-sm-cons-cat-h",children:["🎬 Match tape — who actually banked (",n.tape.audit.wallets," wallets audited)"]}),(n.tape.audit.winners||[]).slice(0,8).map((e,t)=>(0,b.jsxs)("div",{className:"wc-sm-sig",children:[(0,b.jsxs)("a",{className:"radar-link wc-sm-sig-name",href:`https://polymarket.com/profile/${e.w}`,target:"_blank",rel:"noreferrer",children:[e.name||`${e.w.slice(0,6)}…`,n.tape.proven_wallets?.includes(e.w)?" 🎬":""]}),(0,b.jsx)("span",{className:"wc-sm-sig-lean yes",children:e.style}),(0,b.jsxs)("span",{className:"wc-sm-sig-net",children:[(0,b.jsxs)("b",{className:"radar-up",children:["+",rp(e.pnl)]}),(0,b.jsxs)("span",{className:"wc-power-sub",children:[" · ",e.fills," fill",1===e.fills?"":"s",e.inplay?` (${e.inplay} in-play)`:""]})]})]},t)),(n.tape.audit.losers||[]).slice(0,3).map((e,t)=>(0,b.jsxs)("div",{className:"wc-sm-sig",children:[(0,b.jsx)("a",{className:"radar-link wc-sm-sig-name",href:`https://polymarket.com/profile/${e.w}`,target:"_blank",rel:"noreferrer",children:e.name||`${e.w.slice(0,6)}…`}),(0,b.jsx)("span",{className:"wc-sm-sig-lean no",children:e.style}),(0,b.jsxs)("span",{className:"wc-sm-sig-net",children:[(0,b.jsx)("b",{className:"radar-down",children:rp(e.pnl)}),(0,b.jsxs)("span",{className:"wc-power-sub",children:[" · ",e.fills," fill",1===e.fills?"":"s"]})]})]},t))]}),n.tape.proven&&n.tape.proven.length>0&&(0,b.jsxs)("div",{className:"wc-power-sub wc-sm-cons-foot",children:["🎬 tape-proven repeat winners:"," ",n.tape.proven.slice(0,5).map((e,t)=>(0,b.jsxs)("span",{children:[t>0?", ":"",(0,b.jsx)("a",{className:"radar-link",href:`https://polymarket.com/profile/${e.wallet}`,target:"_blank",rel:"noreferrer",children:e.name||`${e.wallet.slice(0,6)}…`})," ","(+",rp(e.pnl)," / ",e.matches,")"]},e.wallet))]}),(0,b.jsx)("div",{className:"wc-power-sub wc-sm-cons-foot",children:'Every wallet-attributed fill in this match\'s main markets, captured live — leaderboards miss these (0/20 Spain-Austria winners were "famous"). 🎬 = banked in 2+ audited matches.'})]}),j&&j.trader_cards&&j.trader_cards.length>0&&(0,b.jsxs)("div",{className:"wc-sm-cards",children:[(0,b.jsx)("div",{className:"wc-sm-cons-cat-h",children:"Who's betting what — biggest bags"}),j.trader_cards.map(e=>(0,b.jsxs)("div",{className:"wc-sm-card-wrap",children:[(0,b.jsxs)("div",{className:"wc-sm-card",children:[(0,b.jsxs)("a",{className:"radar-link wc-sm-card-name",href:`https://polymarket.com/profile/${e.wallet}`,target:"_blank",rel:"noreferrer",children:[e.name,n?.tape?.proven_wallets?.includes(e.wallet)?" 🎬":""]}),(0,b.jsxs)("span",{className:"wc-sm-card-bag",children:[(0,b.jsx)("span",{className:`wc-sm-sig-lean ${e.bag_side||"yes"}`,children:(e.bag_side||"yes").toUpperCase()})," ",e.bag," ",(0,b.jsx)("b",{children:rp(e.bag_usd||0)}),e.n_hedges?(0,b.jsxs)("button",{className:"wc-sm-hedge-btn",onClick:()=>v(t=>({...t,[e.wallet]:!t[e.wallet]})),children:["+",e.n_hedges," hedge",1===e.n_hedges?"":"s"," ",f[e.wallet]?"▾":"▸"]}):null]}),(0,b.jsx)("span",{className:"wc-sm-card-rec",children:e.soccer_n?(0,b.jsxs)("span",{className:null!=e.soccer_wr&&e.soccer_wr>=.5?"radar-up":"radar-down",children:[Math.round(100*(e.soccer_wr||0)),"%",(0,b.jsxs)("span",{className:"wc-power-sub",children:[" · ",e.soccer_n," soccer",e.soccer_days?` / ${e.soccer_days}d`:""]})]}):(0,b.jsx)("span",{className:"wc-power-sub",children:"no soccer record"})})]}),f[e.wallet]&&e.hedges&&e.hedges.length>0&&(0,b.jsxs)("div",{className:"wc-sm-hedges",children:[(0,b.jsxs)("div",{className:"wc-sm-hedges-h",children:[e.name,"'s other positions (",e.hedges.length,")"]}),e.hedges.map((e,t)=>(0,b.jsxs)("div",{className:"wc-sm-hedge",children:[(0,b.jsx)("span",{className:`wc-sm-sig-lean ${e.side}`,children:e.side.toUpperCase()}),(0,b.jsx)("span",{className:"wc-sm-hedge-name",children:e.outcome}),(0,b.jsxs)("span",{className:"wc-sm-hedge-usd",children:[rp(e.usd),e.pnl?(0,b.jsxs)("span",{className:e.pnl>=0?"radar-up":"radar-down",children:[" (",e.pnl>=0?"+":"",rp(e.pnl),")"]}):null]})]},t))]})]},e.wallet))]}),y.length>0&&(0,b.jsx)("button",{className:"radar-addr-btn wc-sm-more",onClick:()=>g(e=>!e),children:x?"▾ hide raw positions":`▸ all ${y.length} traders' full positions`}),x&&(0,b.jsxs)(b.Fragment,{children:[y.map(e=>{let t=!!p[e.wallet],a=t?e.positions:e.positions.slice(0,5),s=[];for(let e of a){let t=s[s.length-1];t&&t[0]===e.category?t[1].push(e):s.push([e.category,[e]])}return(0,b.jsxs)("div",{className:"wc-sm-trader",children:[(0,b.jsxs)("div",{className:"wc-sm-head",children:[(0,b.jsx)("a",{className:"radar-link",href:`https://polymarket.com/profile/${e.wallet}`,target:"_blank",rel:"noreferrer",children:e.name}),(0,b.jsxs)("span",{className:"wc-power-sub",children:["lifetime ",rp(e.pnl)]}),(0,b.jsxs)("span",{className:"wc-sm-inmatch",children:["in match ",rp(e.match_value)," ·"," ",(0,b.jsxs)("span",{className:e.match_pnl>=0?"radar-up":"radar-down",children:["P&L ",e.match_pnl>=0?"+":"",rp(e.match_pnl)]}
8)," ","· ",e.n_positions," position",1===e.n_positions?"":"s"," across ",e.categories.length," categor",1===e.categories.length?"y":"ies"]})]}),s.map(([e,t],a)=>(0,b.jsxs)("div",{className:"wc-sm-cat",children:[(0,b.jsx)("span",{className:"wc-sm-cat-name",children:e}),(0,b.jsx)("div",{className:"wc-sm-poslist",children:t.map((e,t)=>(0,b.jsxs)("span",{className:"wc-sm-pos",title:`${Math.round(e.size).toLocaleString()} shares`,children:[(0,b.jsx)("span",{className:`radar-badge ${"YES"===e.side?"radar-badge-up":"radar-badge-down"}`,children:e.outcome})," ",e.label,(0,b.jsxs)("span",{className:"wc-power-sub",children:[" ","· ",rp(e.value),null!=e.avg&&(0,b.jsxs)("span",{title:"their average fill price → the market now",children:[" ","· in ",(100*e.avg).toFixed(1),"¢",null!=e.cur_price?`→${(100*e.cur_price).toFixed(1)}\xa2`:""]}),e.pnl?(0,b.jsxs)("span",{className:e.pnl>=0?"radar-up":"radar-down",children:[" ","(",e.pnl>=0?"+":"",rp(e.pnl),")"]}):null]})]},t))})]},a)),e.positions.length>5&&(0,b.jsx)("button",{className:"radar-addr-btn wc-sm-more",onClick:()=>m(a=>({...a,[e.wallet]:!t})),children:t?"show less":`+${e.positions.length-5} more positions`})]},e.wallet)}),(0,b.jsx)("div",{className:"radar-section-note",children:"Positions sorted by size · updates every few minutes."})]})]})}function nr({data:e}){let t,a=e.prematch,s=e.match;if(!a||!a.lines?.length||"finished"===s.status)return null;let r=a.lean,n="over"===r?{t:"▲ LEAN OVER",c:"up"}:"under"===r?{t:"▼ LEAN UNDER",c:"down"}:{t:"— no clear edge",c:"flat"},l="strong"===a.confidence?"strong":"lean"===a.confidence?"moderate":"slight"===a.confidence?"slight":"",i=(a.factors||[]).filter(e=>"info"!==e.scope),o=(a.factors||[]).filter(e=>"info"===e.scope);return(0,b.jsxs)("div",{className:"radar-section",children:[(0,b.jsxs)("div",{className:"radar-section-title",children:["Model Over/Under signal"," ",a.live?(0,b.jsxs)("span",{className:"wc-live-badge",children:["● LIVE ",a.minute,"'",a.score?` \xb7 ${a.score[0]}-${a.score[1]}`:""]}):(0,b.jsx)("span",{className:"wc-power-sub",children:"— before kickoff"})]}),(0,b.jsxs)("div",{className:`wc-pm-call ${n.c}`,children:[(0,b.jsx)("span",{className:`wc-pm-lean ${n.c}`,children:n.t}),"none"!==r&&null!=a.line&&(0,b.jsxs)("span",{className:"wc-pm-head",children:["O/U ",a.line," · ",(0,b.jsx)("b",{children:l})," · model ",Math.round(100*(a.model_over||0)),"% vs market ",null==(t=a.market_over)?"—":`${Math.round(100*t)}c`," ",(0,b.jsxs)("span",{className:null!=a.edge_pp&&a.edge_pp>0?"radar-up":"radar-down",children:["(",null!=a.edge_pp&&a.edge_pp>0?"+":"",a.edge_pp,"pp)"]})]})]}),(0,b.jsxs)("div",{className:"radar-section-note",children:["over"===r?`The model makes the over more likely than the price implies — the over looks cheap at O/U ${a.line}.`:"under"===r?`The model makes the under more likely than the price implies — the under looks cheap at O/U ${a.line}.`:"Model and market agree at the main line — no edge worth taking."," ",a.live?"Projected final total":"Expected total goals"," ≈ ",(0,b.jsx)("b",{children:a.lam_total}),null!=a.gap?`, Elo gap ~${a.gap}`:"",a.live?" (current score + remaining-time model)":"","."]}),(i.length>0||o.length>0)&&(0,b.jsxs)("div",{className:"wc-pm-factors",children:[i.map((e,t)=>(0,b.jsxs)("span",{className:`wc-pm-factor ${"over"===e.dir?"up":"under"===e.dir?"down":""}`,children:["over"===e.dir?"▲":"under"===e.dir?"▼":"•"," ",e.text]},t)),o.map((e,t)=>(0,b.jsxs)("span",{className:"wc-pm-factor info",children:["⚠ ",e.text]},`i${t}`))]})]})}function nn({data:e}){let[t,a]=(0,_.useState)("league"),s=e.league_stats,r=e.fav_stats;if(!s&&!r)return null;let n=(e,t)=>t>0?`${Math.round(e/t*100)}%`:"—",l=s?.fav_first&&s?.underdog_first&&s.fav_first.n+s.underdog_first.n>0?Math.round(s.fav_first.n/(s.fav_first.n+s.underdog_first.n)*100):null,i=e=>{if(!r)return null;let a=r[e],s="market"===t?a.market:a.elo,l=("market"===t?r.cur.market_fav:r.cur.elo_fav)===e,i="market"===t?"📈 market":"⭐ Elo";return(0,b.jsxs)("div",{style:{padding:"6px 8px",borderRadius:6,background:"rgba(255,255,255,0.04)",border:l?"1px solid rgba(224,180,90,0.45)":"1px solid transparent"},children:[(0,b.jsx)("b",{children:a.team}),l&&(0,b.jsxs)("span",{className:"wc-live-badge",style:{marginLeft:8},children:["today's ",i," fav"]}),s&&s.n>0?(0,b.jsxs)("div",{className:"radar-section-note",style:{margin:"3px 0 0"},children:["as the ",i," favorite: ",(0,b.jsx)("b",{children:s.n})," matches — wins ",(0,b.jsx)("b",{className:"radar-up",children:n(s.w,s.n)}),", draws ",n(s.d,s.n)," · scores first ",(0,b.jsx)("b",{children:n(s.sf,s.sf_n)}),s.sf_n>0?` (of ${s.sf_n}
8 with a goal)`:"",s.sf>0?(0,b.jsxs)(b.Fragment,{children:[" · when it scored first it won ",(0,b.jsx)("b",{className:"radar-up",children:n(s.sf_w,s.sf)})]}):null]}):(0,b.jsxs)("div",{className:"radar-section-note wc-power-sub",style:{margin:"3px 0 0"},children:["no graded matches as the ",i," favorite in this league yet"]})]},e)};return(0,b.jsxs)("div",{className:"radar-section",children:[(0,b.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"},children:[(0,b.jsx)("div",{className:"radar-section-title",style:{margin:0},children:"💎 Favorites record"}),(0,b.jsxs)("div",{className:"wc-bot-tabs",children:[(0,b.jsx)("button",{className:"league"===t?"on":"",onClick:()=>a("league"),children:"League"}),(0,b.jsx)("button",{className:"market"===t?"on":"",onClick:()=>a("market"),children:"📈 Polymarket fav"}),(0,b.jsx)("button",{className:"elo"===t?"on":"",onClick:()=>a("elo"),children:"⭐ Elo fav"})]})]}),"league"===t&&s&&(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)("div",{className:"radar-section-note",style:{marginTop:6},children:[s.market_fav&&(0,b.jsxs)(b.Fragment,{children:["📈 The ",(0,b.jsx)("b",{children:"Polymarket favorite"})," (pricier side before kickoff) wins"," ",(0,b.jsxs)("b",{className:"radar-up",children:[Math.round(100*s.market_fav.fav_win),"%"]})," and draws"," ",Math.round(100*s.market_fav.fav_draw),"% here (",s.market_fav.n," matches). "]}),s.elo_fav&&(0,b.jsxs)(b.Fragment,{children:["⭐ Our ",(0,b.jsx)("b",{children:"Elo favorite"})," wins ",(0,b.jsxs)("b",{className:"radar-up",children:[Math.round(100*s.elo_fav.fav_win),"%"]})," and draws ",Math.round(100*s.elo_fav.fav_draw),"% (",s.elo_fav.n,")."]})]}),s.fav_first&&(0,b.jsxs)("div",{className:"radar-section-note",children:["The favorite scores first in ",(0,b.jsx)("b",{children:null!=l?`${l}%`:"—"})," of scored games — and when it does, it wins ",(0,b.jsxs)("b",{className:"radar-up",children:[Math.round(100*s.fav_first.fav_win),"%"]})," ","(",s.fav_first.n," matches)."]}),s.underdog_first&&(0,b.jsxs)("div",{className:"radar-section-note",children:["When the ",(0,b.jsx)("b",{children:"underdog scores first"}),", the favorite still comes back to win"," ",(0,b.jsxs)("b",{className:"radar-up",children:[Math.round(100*s.underdog_first.fav_win),"%"]})," and draws"," ",(0,b.jsxs)("b",{children:[Math.round(100*s.underdog_first.fav_draw),"%"]})," — it avoids losing"," ",(0,b.jsxs)("b",{children:[Math.round((s.underdog_first.fav_win+s.underdog_first.fav_draw)*100),"%"]})," of the time (",s.underdog_first.n," matches). That panic dip is the cheap-favorite window."]}),(0,b.jsx)("div",{className:"radar-section-note wc-power-sub",children:"First-scorer splits use the Polymarket favorite. Switch the tabs to see each of today's teams through its own as-favorite history."})]}),"league"!==t&&(0,b.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:6,marginTop:8},children:r?(0,b.jsxs)(b.Fragment,{children:[i("home"),i("away"),(0,b.jsx)("div",{className:"radar-section-note wc-power-sub",style:{margin:0},children:"market"===t?"“Favorite” = the pricier Polymarket side before kickoff, graded over every finished match we priced.":"“Favorite” = the higher raw-Elo side at that point in time (no home bonus — it picks winners slightly better, and it&apos;s what the ratings above show), no hindsight."})]}):(0,b.jsx)("div",{className:"radar-section-note wc-power-sub",children:"per-team favorite records not built yet for this league"})})]})}function nl({r:e}){return(0,b.jsx)("span",{className:`wc-chip ${"W"===e?"w":"D"===e?"d":"l"}`,children:e})}function ni({label:e,flag:t,price:a,fair:s}){let r=rx(s,a);return(0,b.jsxs)("div",{className:"wc-outcome-card",children:[(0,b.jsxs)("div",{className:"wc-outcome-label",children:[t," ",e]}),(0,b.jsx)("div",{className:"wc-outcome-price",children:ru(a)}),(0,b.jsxs)("div",{className:"wc-outcome-fair",children:["fair ",null==s?"—":`${(100*s).toFixed(0)}%`,null!=r&&Math.abs(r)>=1?(0,b.jsxs)("span",{className:`wc-edge ${r>0?"pos":"neg"}`,children:[" ",r>0?"+":"",r.toFixed(1),"pp"]}):null]})]})}function no({label:e,home:t,away:a,pct:s}){if(null==t&&null==a)return null;let r=t??0,n=a??0,l=r+n||1;return(0,b.jsxs)("div",{className:"wc-statbar",children:[(0,b.jsx)("span",{className:"wc-statbar-val",children:s?`${r}%`:r}),(0,b.jsxs)("div",{className:"wc-statbar-track",children:[(0,b.jsx)("div",{className:"wc-statbar-h",style:{width:`${r/l*100}%`}}),(0,b.jsx)("div",{className:"wc-statbar-a",style:{width:`${n/l*100}%`}})]}),(0,b.jsx)("span",{className:"wc-statbar-val",children:s?`${n}%`:n}),(0,b.jsx)("span",{className:"wc-statbar-label",children:e})]})}function nc({m:e}){let t=e.live_stats?.home||{},a=e.live_stats?.away||{},s=e.live_stats?.sources||{},r=e.live_stats?.price_jump,n=r&&Date.now()-(r.ts_ms||0)<9e4;return(0,b.jsxs)("div",{className:"wc-livestrip",children:[(0,b.jsxs)("div",{className:"wc-livestrip-head",children:[(0,b.jsx)("span",{className:"wc-live-badge",children:"● LIVE"})," minute ",e.minute??"?"," · ",e.score_home,"–",e.score_away,n?(0,b.jsx)("span",{className:"wc-jump-badge",title:"the draw price just moved hard — often a goal the score feeds haven't printed yet",children:"⚡ price action suggests score change"}):null]}),Object.keys(s).length>0&&(0,b.jsxs)("div",{className:`wc-sources${e.live_stats?.score_disagreement?" disagree":""}`,children:["score consensus:"," ",Object.entries(s).map(([e,t])=>`${"polymarket"===e?"Polymarket":"bet365"===e?"bet365":"espn"===e?"ESPN":e} ${t.score??"?"}${null!=t.minute?` @${t.minute}'`:""}`).join(" · "),e.live_stats?.score_disagreement?" — sources disagree, using the most progressed score":""]}),(0,b.jsx)(no,{label:"possession",home:t.possession,away:a.possession,pct:!0}),(0,b.jsx)(no,{label:"shots",home:t.shots,away:a.shots}),(0,b.jsx)(no,{label:"on target",home:t.sot,away:a.sot}),(0,b.jsx)(no,{label:"attacks",home:t.attacks,away:a.attacks}),(0,b.jsx)(no,{label:"danger attacks",home:t.dangerous_attacks,away:a.dangerous_attacks}),(0,b.jsx)(no,{label:"corners",home:t.corners,away:a.corners}),(0,b.jsx)(no,{label:"fouls",home:t.fouls,away:a.fouls})]})}
8function nd({match:e,onClose:t}){let[a,s]=(0,_.useState)(null),[r,n]=(0,_.useState)(null);return(0,_.useEffect)(()=>{let t=!1;return(0,er.authGetJson)(`/api/worldcup/goals?date=${encodeURIComponent(e.date)}&home=${encodeURIComponent(e.home)}&away=${encodeURIComponent(e.away)}`).then(e=>{t||(s(e.data?.goals||[]),n(e.data?.source||null))}).catch(()=>!t&&s([])),()=>{t=!0}},[e.date,e.home,e.away]),(0,b.jsx)("div",{className:"wc-goals-pop-backdrop",onClick:t,children:(0,b.jsxs)("div",{className:"wc-goals-pop",onClick:e=>e.stopPropagation(),children:[(0,b.jsxs)("div",{className:"wc-goals-pop-head",children:[(0,b.jsxs)("b",{children:[e.home," ",e.score," ",e.away]}),(0,b.jsx)("span",{className:"wc-power-sub",children:e.date}),(0,b.jsx)("button",{className:"radar-overlay-close",onClick:t,children:"×"})]}),null===a?(0,b.jsx)("div",{className:"radar-section-note",children:"Fetching scorers…"}):0===a.length?(0,b.jsx)("div",{className:"radar-section-note",children:"No goal details available for this match (older games often lack minute data)."}):(0,b.jsxs)("div",{className:"wc-goals-list",children:[a.map((e,t)=>(0,b.jsxs)("div",{className:"wc-goal-row",children:[(0,b.jsxs)("span",{className:"wc-goal-min",children:[e.minute,"'"]}),(0,b.jsxs)("span",{children:["⚽ ",e.player,"penalty"===e.type?" (pen)":""]}),(0,b.jsx)("span",{className:"wc-power-sub",children:e.team})]},t)),(0,b.jsxs)("div",{className:"wc-power-sub",style:{marginTop:4},children:["source: ","statsbomb"===r?"StatsBomb event data":"ESPN match report"]})]})]})})}function nu({clock:e,team:t,isLive:a,liveDiff:s,liveScore:r}){let n,l,i,[o,c]=(0,_.useState)(15),[d,u]=(0,_.useState)(!1);if(!e||0===e.n_matches)return(0,b.jsxs)("div",{className:"radar-section-note",children:["No minute-level goal data for ",t," yet — they haven’t appeared in the tournaments our timeline dataset covers; the qualifier/friendly backfill is filling this in."]});let h=e.scored_by_state,p=e.conceded_by_state,m=!!(a&&h&&p&&(e.state_matches??e.sb_matches??0)>0),x=(s??0)>0?"lead":(s??0)<0?"trail":"level",g=m&&d,f=g?h[x]:e.scored_by_min,v=g?p[x]:e.conceded_by_min,y=g?(f?.reduce((e,t)=>e+t,0)||0)+(v?.reduce((e,t)=>e+t,0)||0):0,j="lead"===x?"LEADING":"trail"===x?"TRAILING":"LEVEL";if(f&&v&&f.length>=91){let e=Math.floor(89/o)+1;l=Array(e).fill(0),i=Array(e).fill(0);for(let e=0;e<=90;e++){let t=0===e?0:Math.floor((e-1)/o);l[t]+=f[e]||0,i[t]+=v[e]||0}n=Array.from({length:e},(e,t)=>{let a=t*o+1,s=Math.min(90,(t+1)*o);return`${a}-${s}${45===s||90===s?"+":""}`})}else n=e.buckets,l=e.scored,i=e.conceded;let w=Math.max(1,...l,...i),N=n.length>9;return(0,b.jsxs)("div",{className:"wc-clock",children:[(0,b.jsxs)("div",{className:"wc-clock-head",children:[(0,b.jsx)("span",{className:"wc-clock-title",children:g?(0,b.jsxs)(b.Fragment,{children:["🔴 live · conditioned on ",(0,b.jsx)("b",{children:j}),r?` (${r})`:""," · n=",y," goals",y<20?(0,b.jsx)("span",{className:"wc-power-sub",children:" · small sample ⚠️"}):null]}):(0,b.jsxs)(b.Fragment,{children:["Scoring clock — ",e.n_matches," matches with goal times",null!=e.first_goal_avg?(0,b.jsxs)("span",{className:"wc-power-sub",children:[" · first goal typically ~",Math.round(e.first_goal_avg),"'"]}):null]})}),m&&(0,b.jsx)("button",{type:"button",className:`wc-clock-live${d?" on":""}`,onClick:()=>u(e=>!e),title:d?`showing only goals from when they were ${j.toLowerCase()} — click for all situations`:`refine to the live situation (currently ${j.toLowerCase()})`,children:d?"🔴 live":"○ live"})]}),f&&v&&f.length>=91&&(0,b.jsxs)("div",{className:"wc-clock-control",children:[(0,b.jsxs)("span",{className:"wc-power-sub",children:["window: ",o," min (",n.length," bins)"]}),(0,b.jsx)("input",{type:"range",min:5,max:45,step:5,value:o,onChange:e=>c(Number(e.target.value)),className:"wc-clock-slider",title:"drag to change the time-window size"})]}),g&&0===y?(0,b.jsxs)("div",{className:"radar-section-note",children:["No goals recorded while ",j.toLowerCase()," in our timeline sample yet — turn live off for the all-situations clock."]}):(0,b.jsx)("div",{className:"wc-clock-scroll",children:(0,b.jsx)("div",{className:`wc-clock-grid${N?" dense":""}`,children:n.map((e,t)=>(0,b.jsxs)("div",{className:"wc-clock-col",title:`${e}': scored ${l[t]}, conceded ${i[t]}`,children:[(0,b.jsxs)("div",{className:"wc-clock-bars",children:[(0,b.jsx)("div",{className:"wc-clock-bar scored",style:{height:`${l[t]/w*46+2}px`}}),(0,b.jsx)("div",{className:"wc-clock-bar conceded",style:{height:`${i[t]/w*46+2}px`}})]}),(0,b.jsx)("div",{className:"wc-clock-label",children:e}),!N&&(0,b.jsxs)("div",{className:"wc-clock-nums",children:[(0,b.jsx)("span",{className:"radar-up",children:l[t]}),"/",(0,b.jsx)("span",{className:"radar-down",children:i[t]})]})]},e+t))})}),(0,b.jsx)("div",{className:"wc-power-sub",children:"green = goals THEY scored in that window · red = goals they LET IN (opponent scored)"})]})}function nh({p:e,flag:t,onMatchClick:a,opponentElo:s,opponentName:r,isLive:n,liveDiff:l,liveScore:i}){let o=e.scoring,c=t=>{a({date:t.date,home:e.team,away:t.opponent,score:t.score})},d=e=>{if(null==e||null==s)return null;let t=Math.abs(e-s);
8return t<=30?"close":t<=70?"near":null};return(0,b.jsxs)("div",{className:"wc-dossier",children:[(0,b.jsxs)("div",{className:"wc-form-head",children:[t," ",e.team]}),(0,b.jsxs)("div",{className:"wc-dossier-chips",children:[(0,b.jsxs)("span",{title:"average goals scored per match since mid-2023",children:["⚽ ",o.gf_avg,"/game"]}),(0,b.jsxs)("span",{title:"average goals let in per match",children:["🥅 ",o.ga_avg," let in"]}),(0,b.jsxs)("span",{title:"share of matches without letting a goal in",children:[Math.round(100*o.clean_sheet_pct),"% clean sheets"]}),(0,b.jsxs)("span",{title:"both teams scored",children:[Math.round(100*o.btts_pct),"% BTTS"]}),(0,b.jsxs)("span",{title:"matches with 3+ total goals",children:[Math.round(100*o.over25_pct),"% over 2.5"]}),(0,b.jsxs)("span",{className:"wc-power-sub",children:["(",o.n," matches since Jun 2023)"]})]}),(0,b.jsx)(nu,{clock:e.clock,team:e.team,isLive:n,liveDiff:l,liveScore:i}),(0,b.jsx)("div",{className:"radar-section-note",children:"click any match for scorers + minutes"}),null!=s&&(0,b.jsxs)("div",{className:"radar-section-note",children:[(0,b.jsx)("span",{className:"wc-elo-badge wc-elo-close",children:"🎯"})," faced a team about as strong as"," ",(0,b.jsx)("b",{children:r})," (Elo ",Math.round(s),"), their upcoming opponent ·"," ",(0,b.jsx)("span",{className:"wc-elo-badge wc-elo-near",children:"≈"})," quite close"]}),(0,b.jsx)("table",{className:"radar-moves-table",children:(0,b.jsx)("tbody",{children:e.recent.slice(0,10).map((e,t)=>{let a=d(e.opponent_elo);return(0,b.jsxs)("tr",{className:`wc-match-clickable${a?` wc-elo-row-${a}`:""}`,onClick:()=>c(e),children:[(0,b.jsx)("td",{children:e.date}),(0,b.jsxs)("td",{children:[(0,b.jsx)(nl,{r:e.result})," ",(0,b.jsx)("b",{children:e.score})," vs ",e.opponent,null!=e.opponent_elo&&(0,b.jsxs)("span",{className:"wc-power-sub",title:"opponent's Elo rating going into that match",children:[" · Elo ",e.opponent_elo]}),a&&(0,b.jsxs)("span",{className:`wc-elo-badge wc-elo-${a}`,title:`about as strong as ${r} (Elo ${Math.round(s)}) — your upcoming opponent`,children:["close"===a?"🎯":"≈"," ",r]})]}),(0,b.jsx)("td",{className:"wc-power-sub",children:e.tournament||""})]},t)})})}),e.wc.length>0&&(0,b.jsxs)("div",{className:"wc-dossier-wc",children:[(0,b.jsx)("div",{className:"wc-power-sub",children:"World Cup history:"}),e.wc.map((e,t)=>{let a=d(e.opponent_elo);return(0,b.jsxs)("span",{className:`wc-wc-item wc-match-clickable${a?` wc-elo-chip-${a}`:""}`,onClick:()=>c(e),title:a?`about as strong as ${r} — your upcoming opponent`:void 0,children:[(0,b.jsx)(nl,{r:e.result})," ",e.score," vs ",e.opponent,null!=e.opponent_elo&&(0,b.jsxs)("span",{className:"wc-power-sub",children:[" (Elo ",e.opponent_elo,")"]}),"close"===a?" 🎯":"near"===a?" ≈":""," ",(0,b.jsxs)("i",{children:["’",e.date.slice(2,4)]})]},t)})]})]})}function np({eventId:e,onClose:t,inline:a=!1,active:s=!0,onTitle:r}){let n,l,[i,o]=(0,_.useState)(null),[c,d]=(0,_.useState)(Date.now()),[u,h]=(0,_.useState)(null),[p,m]=(0,_.useState)(null),[x,g]=(0,_.useState)(!1),[f,v]=(0,_.useState)(""),j=i?.match?.status==="live",w=async()=>{g(!0),v("");try{let t=await (0,er.authPostJson)(`/api/worldcup/matches/${e}/refresh-live`),a=t.data?.match;a&&o(e=>e?{...e,match:{...e.match,...a}}:e);let s=t.data?.sources||[];v(s.length?`checked ${s.join(" + ")}`:"no live source found")}catch{v("refresh failed")}finally{g(!1)}},N=i?.match,k=j||!!(N&&"finished"!==N.status&&null!=N.kickoff_ts&&N.kickoff_ts<=Date.now()+9e5);if((0,_.useEffect)(()=>{if(!s||!j)return void h(null);let t=null,a=!1;return(async()=>{let s=await (0,er.getAccessToken)();!a&&s&&((t=new EventSource(`${y.API_BASE}/api/worldcup/matches/${e}/stream?access_token=${encodeURIComponent(s)}`)).onmessage=e=>{try{let t=JSON.parse(e.data);t&&(t.prices||t.fair)&&(h(t),d(Date.now()))}catch{}},t.onerror=()=>{})})(),()=>{a=!0,t?.close()}},[s,e,j]),(0,_.useEffect)(()=>{let t=!1,a=null,n=()=>{t||(0,er.authGetJson)(`/api/worldcup/matches/${e}`).then(e=>{if(!t){o(e.data||null),d(Date.now());let t=e.data?.match;if(t){let e="live"===t.status?` \xb7 ${t.score_home??0}–${t.score_away??0} ${null!=t.minute?t.minute+"'":"LIVE"}`:"";r?.(`${t.home_flag||""} ${t.home_team} vs ${t.away_team}${e}`.trim())}}}).catch(()=>{}).finally(()=>{!t&&s&&(a=window.setTimeout(n,k?3e3:3e4))})};return n(),()=>{t=!0,null!=a&&window.clearTimeout(a)}},[s,e,j,k]),!i)return(0,b.jsx)(s7.OverlayWrap,{inline:a,onClose:t,children:(0,b.jsx)("div",{className:"radar-overlay-panel wc-overlay",onClick:e=>e.stopPropagation(),children:(0,b.jsx)("div",{className:"empty-state",children:"Loading match…"})})});let S=(()=>{let e=i.match;if(!u)return e;let t={...e};u.prices&&Object.keys(u.prices).length&&(t.prices={...e.prices,...u.prices});let a={...e.live_stats||{},...u.live_stats||{}};if(u.fair&&(a.model_live=u.fair),u.jump&&(a.price_jump=u.jump),t.live_stats=a,null!=u.minute&&(t.minute=Math.max(Number(e.minute||0),Number(u.minute||0))),"string"==typeof u.score&&/^\d+-\d+$/.test(u.score)){let[a,s]=u.score.split("-").map(Number);a+s>=Number(e.score_home||0)+Number(e.score_away||0)&&(t.score_home=a,t.score_away=s)}return"live"===u.status&&"scheduled"===e.status&&(t.status="live"),t})(),$=i.elo[S.home_team],C=i.elo[S.away_team],M=i.bucket,E=(S.model?.elo_home??0)>=(S.model?.elo_away??0)?S.home_team:S.away_team,A=i.league_meta,T=A?0===A.tier?"Tier 0 · tournament":1===A.tier?"Tier 1 · goal-fest":2===A.tier?"Tier 2 · above average":"Tier 3 · cagey":null;return(0,b.jsxs)(s7.OverlayWrap,{inline:a,onClose:t,children:[(0,b.jsx)(tC.TradeWidgetSource,{eventId:e,marketSlug:S.slug}),(0,b.jsxs)("div",{className:"radar-overlay-panel wc-overlay",onClick:e=>e.stopPropagation(),children:[(0,b.jsxs)("div",{className:"radar-overlay-head",children:[(0,b.jsxs)("div",{className:"wc-match-head",children:[(0,b.jsxs)("div",{className:"wc-match-title",children:[(0,b.jsxs)("span",{className:"wc-team-big",children:[S.home_flag," ",S.home_team]}),(0,b.jsx)("span",{className:"wc-score-big",children:"scheduled"===S.status?"vs":`${S.score_home??0}–${S.score_away??0}`}),(0,b.jsxs)("span",{className:"wc-team-big",children:[S.away_team," ",S.away_flag]})]}),(0,b.jsxs)("div",{className:"wc-match-context",children:[(0,b.jsx)("span",{className:"wc-match-league",children:A?.name||S.league||"FIFA World Cup"}),A&&T&&(0,b.jsx)("span",{className:`wc-match-tier tier-${A.tier}`,title:A.goals_avg>0?`${A.goals_avg.toFixed(2)} goals per match`:"Competition tier; not ranked by league scoring average",children:T}),A&&A.goals_avg>0&&(0,b.jsxs)("span",{className:"wc-match-goals",children:[A.goals_avg.toFixed(2)," goals/match"]})]}),(0,b.jsxs)("div",{className:"wc-match-sub",children:[S.stage?`${S.stage} \xb7 `:"","live"===S.status?(0,b.jsxs)("span",{className:"wc-live-badge",children:["● LIVE ",null!=S.minute?`${S.minute}'`:""," ",S.period||""]}):"finished"===S.status?"full time":rm(S.kickoff_ts),"finished"!==S.status&&(0,b.jsxs)(b.Fragment,{children:[" · ",(0,b.jsx)("button",{className:"wc-scout-refresh",onClick:w,disabled:x,children:x?"checking…":"↻ refresh status"}),f&&(0,b.jsxs)("span",{className:"wc-power-sub",children:[" ",f]})]})," · ",(0,b.jsx)("a",{className:"radar-link",href:`https://polymarket.com/event/${S.slug}`,target:"_blank",rel:"noreferrer",children:"trade on Polymarket ↗"})]})]}),!a&&(0,b.jsx)("button",{className:"radar-overlay-close",onClick:t,children:"×"})]}),"live"===S.status&&(0,b.jsx)(nc,{m:S}),(0,b.jsxs)("div",{className:"wc-outcomes",children:[(0,b.jsx)(ni,{label:`${S.home_team} win`,flag:S.home_flag,price:S.prices?.home,fair:(S.live_stats?.model_live||S.model)?.home}),(0,b.jsx)(ni,{label:"Draw",price:S.prices?.draw,fair:(S.live_stats?.model_live||S.model)?.draw}),(0,b.jsx)(ni,{label:`${S.away_team} win`,flag:S.away_flag,price:S.prices?.away,fair:(S.live_stats?.model_live||S.model)?.away})]}),"live"===S.status&&S.live_stats?.model_live?(0,b.jsxs)("div",{className:"radar-section-note",children:["fair odds above are LIVE — recomputed from the current score (",S.score_home,"–",S.score_away,") and time left, not the pre-match line."]}):null,(0,b.jsxs)("div",{className:"radar-section",children:[(0,b.jsx)("div",{className:"radar-section-title",children:"Odds history"}),(0,b.jsx)(rt,{eventId:e,homeTeam:S.home_team,awayTeam:S.away_team,active:s})]}),(0,b.jsx)(r0,{data:i}),(0,b.jsx)(nr,{data:i}),(0,b.jsx)(nn,{data:i}),"finished"!==S.status&&(0,b.jsx)(r8,{eventId:e}),"scheduled"!==S.status&&(0,b.jsx)(r3,{eventId:e,live:"live"===S.status,home:S.home_team,away:S.away_team,active:s}),"scheduled"!==S.status&&(0,b.jsx)(r9,{}),"scheduled"!==S.status&&(0,b.jsx)(r6,{eventId:e,live:"live"===S.status,clock:S.minute,active:s}),(0,b.jsx)(ns,{eventId:e,home:S.home_team,away:S.away_team,active:s,live:"live"===S.status}),(0,b.jsx)(na,{eventId:e,active:s}),(0,b.jsx)(r7,{eventId:e,home:S.home_team,away:S.away_team}),(0,b.jsx)(rd,{eventId:e,home:S.home_team,away:S.away_team,kickoffMs:S.kickoff_ts??null,active:s}),(0,b.jsx)(rn,{eventId:e,label:`${S.home_team} v ${S.away_team}`}),(0,b.jsxs)("div",{className:"radar-section",children:[(0,b.jsx)("div",{className:"radar-section-title",children:"Power ratings & what history says"}),(n=!!($?.cross_pool&&C?.cross_pool&&$.pool&&C.pool&&$.pool!==C.pool),l=e=>["Elo",`${e?.matches??0} matches`,e?.cross_pool?`${e.pool_label||e.pool||"domestic"}
8 pool`:null].filter(Boolean).join(" · "),(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)("div",{className:"wc-power",children:[(0,b.jsxs)("div",{className:"wc-power-team",children:[(0,b.jsxs)("div",{className:"wc-power-name",children:[S.home_flag," ",S.home_team]}),(0,b.jsx)("div",{className:"wc-power-elo",children:$?Math.round($.elo):"—"}),(0,b.jsx)("div",{className:"wc-power-sub",children:l($)})]}),(0,b.jsxs)("div",{className:"wc-power-mid",children:[(0,b.jsxs)("div",{className:"wc-power-gap",children:["Δ ",n?"N/A":S.model?.gap!=null?Math.round(S.model.gap):"—"]}),(0,b.jsx)("div",{className:"wc-power-sub",children:n?"different league pools":"Elo gap"})]}),(0,b.jsxs)("div",{className:"wc-power-team",children:[(0,b.jsxs)("div",{className:"wc-power-name",children:[S.away_team," ",S.away_flag]}),(0,b.jsx)("div",{className:"wc-power-elo",children:C?Math.round(C.elo):"—"}),(0,b.jsx)("div",{className:"wc-power-sub",children:l(C)})]})]}),n&&(0,b.jsx)("div",{className:"radar-section-note",children:"League-relative ratings are not directly comparable: 1500 in one division does not equal 1500 in another. Polymarket prices, not this cross-pool Elo ordering, determine the market favorite."})]})),M&&(0,b.jsxs)("div",{className:"wc-study-card",children:["In matchups like this one (",i.bucket_key?.replace("|",", venue: "),"), the stronger side (",E,") has historically gone ",(0,b.jsxs)("b",{children:[Math.round(100*M.w),"% win / ",Math.round(100*M.d),"% draw / ",Math.round(100*M.l),"% loss"]})," ","with average goals ",(0,b.jsxs)("b",{children:[M.gf.toFixed(1),"–",M.ga.toFixed(1)]})," — across ",(0,b.jsx)("b",{children:M.n.toLocaleString()})," ","fifwc"===(S.league||"fifwc")?"internationals since 1980":"club matches from our synced seasons",". That history is exactly where the fair odds above come from."]})]}),(0,b.jsxs)("div",{className:"radar-section",children:[(0,b.jsx)("div",{className:"radar-section-title",children:"Head to head"}),0===i.h2h.played?(0,b.jsx)("div",{className:"radar-section-note",children:"fifwc"===(S.league||"fifwc")?"These two nations have never met in a recorded international — no head-to-head history exists.":"These two clubs haven't met in our synced seasons — first meeting on record."}):(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)("div",{className:"wc-h2h-bar",children:[(0,b.jsxs)("span",{children:[S.home_team," ",i.h2h.w,"W"]}),(0,b.jsxs)("div",{className:"wc-h2h-track",children:[(0,b.jsx)("div",{className:"wc-3way-seg home",style:{width:`${i.h2h.w/i.h2h.played*100}%`}}),(0,b.jsx)("div",{className:"wc-3way-seg draw",style:{width:`${i.h2h.d/i.h2h.played*100}%`}}),(0,b.jsx)("div",{className:"wc-3way-seg away",style:{width:`${i.h2h.l/i.h2h.played*100}%`}})]}),(0,b.jsxs)("span",{children:[i.h2h.l,"W ",S.away_team]})]}),(0,b.jsxs)("div",{className:"radar-section-note",children:[i.h2h.played," meetings all-time · ",i.h2h.d," draws · aggregate ",i.h2h.gf,"–",i.h2h.ga]}),(0,b.jsx)("table",{className:"radar-moves-table",children:(0,b.jsx)("tbody",{children:i.h2h.meetings.map((e,t)=>(0,b.jsxs)("tr",{className:"wc-match-clickable",onClick:()=>m({date:e.date,home:e.home,away:e.away,score:e.score}),children:[(0,b.jsx)("td",{children:e.date}),(0,b.jsxs)("td",{children:[e.home," ",(0,b.jsx)("b",{children:e.score})," ",e.away]}),(0,b.jsx)("td",{children:e.tournament||""}),(0,b.jsx)("td",{children:(0,b.jsx)(nl,{r:e.result_for_a})})]},t))})})]})]}),i.profiles?.home&&i.profiles?.away?(0,b.jsxs)("div",{className:"radar-section",children:[(0,b.jsx)("div",{className:"radar-section-title",children:"Team dossiers — who they played, how they score"}),(0,b.jsxs)("div",{className:"wc-form-grid",children:[(0,b.jsx)(nh,{p:i.profiles.home,flag:S.home_flag,onMatchClick:m,opponentElo:i.elo[S.away_team]?.elo,opponentName:S.away_team,isLive:"live"===S.status,liveDiff:(S.score_home??0)-(S.score_away??0),liveScore:`${S.score_home??0}–${S.score_away??0}`}),(0,b.jsx)(nh,{p:i.profiles.away,flag:S.away_flag,onMatchClick:m,opponentElo:i.elo[S.home_team]?.elo,opponentName:S.home_team,isLive:"live"===S.status,liveDiff:(S.score_away??0)-(S.score_home??0),liveScore:`${S.score_away??0}–${S.score_home??0}`})]})]}):(0,b.jsxs)("div",{className:"radar-section",children:[(0,b.jsx)("div",{className:"radar-section-title",children:"fifwc"===(S.league||"fifwc")?"Form — last 10 internationals":"Form — last 10 league matches"}),(0,b.jsx)("div",{className:"wc-form-grid",children:[{team:S.home_team,flag:S.home_flag,f:i.form.home},{team:S.away_team,flag:S.away_flag,f:i.form.away}].map(({team:e,flag:t,f:a})=>(0,b.jsxs)("div",{className:"wc-form-col",children:[(0,b.jsxs)("div",{className:"wc-form-head",children:[t," ",e," ",(0,b.jsxs)("span",{className:"wc-power-sub",children:["GF ",a?.gf??0," · GA ",a?.ga??0]})]}),(0,b.jsx)("div",{className:"wc-form-chips",children:(a?.chips||[]).map((e,t)=>(0,b.jsx)("span",{title:`${e.date}: vs ${e.opponent}${null!=e.opponent_elo?` (Elo ${e.opponent_elo})`:""} ${e.score} (${e.tournament||""}
8)`,children:(0,b.jsx)(nl,{r:e.result})},t))})]},e))})]}),p&&(0,b.jsx)(nd,{match:p,onClose:()=>m(null)})]})]})}var nm=e.i(66463);let nx=(0,w.default)("alarm-clock",[["circle",{cx:"12",cy:"13",r:"8",key:"3y4lt7"}],["path",{d:"M12 9v4l2 2",key:"1c63tq"}],["path",{d:"M5 3 2 6",key:"18tl5t"}],["path",{d:"m22 6-3-3",key:"1opdir"}],["path",{d:"M6.38 18.7 4 21",key:"17xu3x"}],["path",{d:"M17.64 18.67 20 21",key:"kv2oe2"}]]),ng=(0,w.default)("bot",[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]]),nf=(0,w.default)("book-open",[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]]),nb=(0,w.default)("calendar-days",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M16 14h.01",key:"1gbofw"}],["path",{d:"M8 18h.01",key:"lrp35t"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M16 18h.01",key:"kzsmim"}]]),n_=(0,w.default)("circle-dot",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]]),nv=(0,w.default)("clipboard-list",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"M12 11h4",key:"1jrz19"}],["path",{d:"M12 16h4",key:"n85exb"}],["path",{d:"M8 11h.01",key:"1dfujw"}],["path",{d:"M8 16h.01",key:"18s6g9"}]]),ny=(0,w.default)("gauge",[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]]),nj=(0,w.default)("plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);async function nw(e,t,a=null,s=500){let r=`/api/fcpo/klines?symbol=${encodeURIComponent(e)}&tf=${t}&limit=${s}`;a&&(r+=`&endTime=${a}`);let n=await (0,er.authFetch)(r);if(!n.ok)throw Error(`fcpo klines ${n.status}`);let l=await n.json();return Array.isArray(l)?l.map(e=>({time:Math.floor(e[0]/1e3),open:parseFloat(e[1]),high:parseFloat(e[2]),low:parseFloat(e[3]),close:parseFloat(e[4]),volume:parseFloat(e[5]),openTimeMs:e[0]})):[]}function nN(e){let t=new Set;return e.filter(e=>!t.has(e.time)&&(t.add(e.time),!0))}let nk={poc:{color:"rgba(79,140,255,0.95)",dashed:!1},vah:{color:"rgba(79,140,255,0.55)",dashed:!0},val:{color:"rgba(79,140,255,0.55)",dashed:!0},hi52:{color:"rgba(229,72,77,0.9)",dashed:!1},lo52:{color:"rgba(48,164,108,0.9)",dashed:!1},pmh:{color:"rgba(245,165,36,0.85)",dashed:!1},pml:{color:"rgba(245,165,36,0.85)",dashed:!1},atr_up:{color:"rgba(139,143,163,0.6)",dashed:!0},atr_dn:{color:"rgba(139,143,163,0.6)",dashed:!0}},nS={trending_up:"TRENDING ↑",trending_down:"TRENDING ↓",range_bound:"RANGE-BOUND",vol_squeeze:"VOL SQUEEZE",turning:"TURNING"},n$={pre_open:"PRE-OPEN",session1:"SESSION 1",lunch:"LUNCH",session2:"SESSION 2",break:"BREAK",night:"NIGHT (T+1)",closed:"CLOSED"},nC=["","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],nM={mpob:"var(--danger, #e5484d)",its:"var(--accent, #4f8cff)",amspec:"var(--accent, #4f8cff)",sppoma:"var(--warning, #f5a524)",mpoa:"var(--warning, #f5a524)",reuters_poll:"var(--text-muted, #8b8fa3)",policy:"#b17bdb"};function nE(e,t=0){return null!=e&&Number.isFinite(Number(e))?Number(e).toLocaleString(void 0,{minimumFractionDigits:t,maximumFractionDigits:t}):"—"}function nA(e,t=!0){let a=new Date(e),s={timeZone:"Asia/Kuala_Lumpur",hour:"2-digit",minute:"2-digit",hour12:!1};return t&&(s.day="2-digit",s.month="short"),new Intl.DateTimeFormat("en-GB",s).format(a)}function nT(e){if(e<=0)return"now";let t=Math.floor(e/1e3),a=Math.floor(t/86400),s=Math.floor(t%86400/3600),r=Math.floor(t%3600/60),n=t%60;return a>0?`${a}d ${s}h`:s>0?`${s}:${String(r).padStart(2,"0")}
8:${String(n).padStart(2,"0")}`:`${r}:${String(n).padStart(2,"0")}`}function nF(e){return null!=e&&Number.isFinite(Number(e))?e<90?`${Math.max(0,Math.round(e))}s old`:e<7200?`${Math.round(e/60)}m old`:`${Math.round(e/3600)}h old`:"age unknown"}function nP({points:e,width:t=90,height:a=24}){if(!e||e.length<2)return(0,b.jsx)("span",{style:{color:"var(--text-muted)",fontSize:10},children:"—"});let s=e.map(e=>e.v),r=Math.min(...s),n=Math.max(...s)-r||1,l=e.map((s,l)=>`${(l/(e.length-1)*(t-2)+1).toFixed(1)},${(a-2-(s.v-r)/n*(a-4)).toFixed(1)}`).join(" "),i=s[s.length-1]>=s[0];return(0,b.jsx)("svg",{width:t,height:a,style:{display:"block"},children:(0,b.jsx)("polyline",{points:l,fill:"none",stroke:i?"var(--success, #30a46c)":"var(--danger, #e5484d)",strokeWidth:"1.5"})})}function nR({session:e}){let[,t]=(0,_.useState)(0);(0,_.useEffect)(()=>{let e=setInterval(()=>t(e=>e+1),1e3);return()=>clearInterval(e)},[]);let a=e.next_transition_ms-Date.now(),s=e.is_trading;return(0,b.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,b.jsxs)("span",{style:{display:"inline-flex",alignItems:"center",gap:5,padding:"3px 8px",borderRadius:5,fontSize:11,fontWeight:700,letterSpacing:.4,background:s?"rgba(48,164,108,0.15)":"var(--bg-input, #1a1c25)",color:s?"var(--success, #30a46c)":"var(--text-muted, #8b8fa3)",border:`1px solid ${s?"rgba(48,164,108,0.4)":"var(--border-subtle, #2a2d3a)"}`},children:[(0,b.jsx)(n_,{size:10}),n$[e.state]||e.state.toUpperCase(),e.is_holiday?" · HOLIDAY":""]}),(0,b.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:[n$[e.next_state]||e.next_state," in ",(0,b.jsx)("b",{style:{color:"var(--text-primary, #e6e8f0)",fontVariantNumeric:"tabular-nums"},children:nT(a)})," · ","MYT ",nA(Date.now(),!1)]})]})}function nO({ev:e,onClose:t,onSaved:a}){let[s,r]=(0,_.useState)(null!=e.consensus?String(e.consensus):""),[n,l]=(0,_.useState)(null!=e.prior?String(e.prior):""),[i,o]=(0,_.useState)(null!=e.actual?String(e.actual):""),[c,d]=(0,_.useState)(function(e){if(!e)return"";let t=new Date(new Date(e).getTime()+288e5);return Number.isNaN(t.getTime())?"":t.toISOString().slice(0,16)}(e.released_ts)),[u,h]=(0,_.useState)(e.notes||""),[p,m]=(0,_.useState)(!1),[x,g]=(0,_.useState)("");async function f(){m(!0),g("");let r={notes:u};if(r.consensus=""===s.trim()?null:Number(s),r.prior=""===n.trim()?null:Number(n),r.actual=""===i.trim()?null:Number(i),c&&(r.released_ts=new Date(`${c}:00+08:00`).toISOString()),""!==i.trim()&&!c){g("Public release time is required with an actual; entry time is not evidence time."),m(!1);return}try{await (0,er.authPostJson)(`/api/fcpo/events/${e.id}`,r),a(),t()}catch(e){g(e instanceof Error?e.message:"save failed")}finally{m(!1)}}let v=(t,a,s,r)=>(0,b.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:4,fontSize:11,color:"var(--text-muted)"},children:[t," ",e.unit?`(${e.unit})`:"",(0,b.jsx)("input",{value:a,onChange:e=>s(e.target.value),placeholder:r,style:{background:"var(--bg-input, #1a1c25)",border:"1px solid var(--border-subtle, #2a2d3a)",borderRadius:5,padding:"6px 8px",color:"var(--text-primary, #e6e8f0)",fontSize:12}})]});return(0,b.jsx)("div",{style:{position:"fixed",inset:0,background:"rgba(0,0,0,0.6)",zIndex:300,display:"flex",alignItems:"center",justifyContent:"center"},onClick:t,children:(0,b.jsxs)("div",{onClick:e=>e.stopPropagation(),style:{width:420,maxWidth:"92vw",background:"var(--bg-panel, #14161e)",border:"1px solid var(--border-subtle, #2a2d3a)",borderRadius:8,padding:16,display:"flex",flexDirection:"column",gap:10},children:[(0,b.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",gap:8},children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("div",{style:{fontSize:13,fontWeight:600},children:e.title}),(0,b.jsxs)("div",{style:{fontSize:11,color:"var(--text-muted)",marginTop:2},children:[nA(e.scheduled_ts)," MYT — enter the numbers from the print (this is the human-in-the-loop step)"]})]}),(0,b.jsx)("button",{className:"btn btn-ghost btn-sm",onClick:t,"aria-label":"close",children:(0,b.jsx)(k,{size:14})})]}),(0,b.jsxs)("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:8},children:[v("Prior",n,l,"prev period"),v("Consensus",s,r,"poll / whisper"),v("Actual",i,o,"the print")]}),(0,b.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:4,fontSize:11,color:"var(--text-muted)"},children:["Publicly released (MYT) ",i.trim()?"· required":"",(0,b.jsx)("input",{type:"datetime-local",value:c,onChange:e=>d(e.target.value),style:{background:"var(--bg-input, #1a1c25)",border:"1px solid var(--border-subtle, #2a2d3a)",borderRadius:5,padding:"6px 8px",color:"var(--text-primary, #e6e8f0)",fontSize:12}}),(0,b.jsx)("span",{style:{fontSize:9.5},children:"Use the source publication time, not when you typed the number."})]}),(0,b.jsxs)("label",{style:{display:"flex",flexDirection:"column",gap:4,fontSize:11,color:"var(--text-muted)"},children:["Notes",(0,b.jsx)("textarea",{value:u,onChange:e=>h(e.target.value),rows:3,placeholder:"context — who moved first, how 
8it traded vs soyoil…",style:{background:"var(--bg-input, #1a1c25)",border:"1px solid var(--border-subtle, #2a2d3a)",borderRadius:5,padding:"6px 8px",color:"var(--text-primary, #e6e8f0)",fontSize:12,resize:"vertical"}})]}),x&&(0,b.jsx)("div",{style:{color:"var(--danger, #e5484d)",fontSize:11},children:x}),(0,b.jsxs)("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[(0,b.jsx)("button",{className:"btn btn-sm",onClick:t,children:"Cancel"}),(0,b.jsx)("button",{className:"btn btn-primary btn-sm",onClick:f,disabled:p,children:p?"Saving…":"Save"})]})]})})}function nL(){let[e,t]=(0,_.useState)(null),[a,s]=(0,_.useState)([]),[r,n]=(0,_.useState)({}),[l,i]=(0,_.useState)([]),[o,c]=(0,_.useState)(null),[d,u]=(0,_.useState)([]),[h,p]=(0,_.useState)([]),[m,x]=(0,_.useState)(null),[g,f]=(0,_.useState)(null),[v,y]=(0,_.useState)(""),[j,w]=(0,_.useState)("1d"),[N,k]=(0,_.useState)(null),[S,$]=(0,_.useState)(!1),[C,M]=(0,_.useState)(""),[E,A]=(0,_.useState)(null),[T,F]=(0,_.useState)(!1),[P,R]=(0,_.useState)(!0),[O,L]=(0,_.useState)("desk"),[I,D]=(0,_.useState)({loading:!0,error:"",lastOkMs:null,failedParts:[]}),[z,B]=(0,_.useState)(""),W=v||e?.benchmark_symbol||"FCPOc3",{candles:U,loadMore:H}=function(e="FCPOc3",t="1d"){let[a,s]=(0,_.useState)([]),[r,n]=(0,_.useState)(""),l=(0,_.useRef)(!1),i=(0,_.useRef)([]),o=(0,_.useRef)(`${e}:${t}`);(0,_.useEffect)(()=>{i.current=a},[a]);let c=(0,_.useCallback)(async()=>{let a=`${e}:${t}`;try{let r=await nw(e,t);if(o.current!==a)return;s(r),n("")}catch(e){if(o.current!==a)return;n(e instanceof Error?e.message:"Failed to load FCPO klines")}},[e,t]),d=(0,_.useCallback)(async()=>{if(l.current)return;let a=i.current;if(!a.length||!a[0].openTimeMs)return;l.current=!0;let r=`${e}:${t}`;try{let n=await nw(e,t,a[0].openTimeMs-1);if(!n.length||o.current!==r)return;s(e=>{let t=[...n,...e];return t.sort((e,t)=>e.time-t.time),nN(t)})}catch{}finally{l.current=!1}},[e,t]);return(0,_.useEffect)(()=>{o.current=`${e}:${t}`,l.current=!1,s([]),c()},[c,e,t]),(0,_.useEffect)(()=>{let a=`${e}:${t}`;async function r(){if("u"<typeof document||!document.hidden)try{let r=await nw(e,t,null,5);if(!r.length||o.current!==a)return;s(e=>{if(!e.length)return r;let t=[...e];for(let e of r){let a=t.findIndex(t=>t.time===e.time);a>=0?t[a]=e:t.push(e)}return t.sort((e,t)=>e.time-t.time),nN(t)})}catch{}}let n=setInterval(r,2e4),l=()=>{document.hidden||r()};return document.addEventListener("visibilitychange",l),()=>{clearInterval(n),document.removeEventListener("visibilitychange",l)}},[e,t]),{candles:a,error:r,reload:c,loadMore:d}}(W,j);async function q(){if("1d"===j){F(!0),B("");try{let e=await (0,er.authPostJson)("/api/fcpo/ta",{symbol:W,tf:j});e?.data?.ok&&(A(e.data),R(!0))}catch(e){B(e instanceof Error?e.message:"Daily TA failed")}finally{F(!1)}}}(0,_.useEffect)(()=>{let e=!1;return(A(null),B(""),"1d"!==j)?()=>{e=!0}:((0,er.authGetJson)(`/api/fcpo/ta?symbol=${encodeURIComponent(W)}&tf=${j}`).then(t=>{!e&&t?.data?.snapshot&&A(t.data.snapshot)}).catch(()=>{}),()=>{e=!0})},[W,j]);let V=(0,_.useMemo)(()=>{if(!E||!P)return[];if(E.levels?.length)return E.levels.map(e=>{let t=nk[e.kind||""]||{color:"rgba(245,165,36,0.8)",dashed:!0};return{price:e.price,color:t.color,title:`${e.key?"★ ":""}${e.label}`.slice(0,30),dashed:t.dashed&&!e.key}});let e=(e,t)=>({price:e.price,color:"S"===t?"rgba(48,164,108,0.9)":"rgba(229,72,77,0.9)",title:`${t}${(e.strength||1)>=3?"★":""} ${e.label}`.slice(0,28),dashed:2>(e.strength||1)});return[...(E.supports||[]).map(t=>e(t,"S")),...(E.resistances||[]).map(t=>e(t,"R"))]},[E,P]),G=(0,_.useMemo)(()=>E&&P?(E.trendlines||[]).filter(e=>e.points?.length>=2).map(e=>({points:e.points.map(e=>({time:e.time_s,value:e.value})),color:"rising"===e.direction?"rgba(48,164,108,0.7)":"rgba(229,72,77,0.7)",dashed:!0,title:e.label})):[],[E,P]),J=(0,_.useCallback)(async()=>{try{let e=await (0,er.authGetJson)("/api/fcpo/overview");t(e?.data||null),D(e=>({...e,error:"",lastOkMs:Date.now()}))}catch(e){D(t=>({...t,error:e instanceof Error?e.message:"Overview refresh failed"}))}},[]),Y=(0,_.useCallback)(async()=>{try{let e=await (0,er.authGetJson)("/api/fcpo/bundle"),a=e?.data;if(!a)throw Error("FCPO bundle returned no data");a.overview&&t(a.overview),a.events?.events&&s(a.events.events),a.cross?.series&&n(a.cross.series),a.reads?.reads&&i(a.reads.reads),a.paper&&c(a.paper),a.journal?.entries&&u(a.journal.entries),a.signals?.signals&&p(a.signals.signals),a.signals?.scoreboard&&x(a.signals.scoreboard),D({loading:!1,error:"",lastOkMs:Number(e?.meta?.generated_at_ms)||Date.now(),failedParts:Array.isArray(e?.meta?.failed_parts)?e.meta.failed_parts:[]})}catch(e){D(t=>({...t,loading:!1,error:e instanceof Error?e.message:"FCPO refresh failed"}))}},[]);(0,_.useEffect)(()=>{Y();let e=setInterval(J,5e3),t=setInterval(Y,2e4);return()=>{clearInterval(e),clearInterval(t)}},[J,Y]);let K=(0,_.useMemo)(()=>e?.chain?.find(e=>e.is_benchmark)||null,[e]),X=(0,_.useMemo)(()=>e?.chain?.find(e=>e.symbol===W)||K,[e,W,K]),Z=X?.quote?.last??null,Q=X?.quote?.prev_settle??e?.benchmark_settle??null,ee=null!=Z&&null!=Q?Z-Q:null,et=Date.now(),ea=(0,_.useMemo)(()=>a.filter(e=>new Date(e.scheduled_ts).getTime()>et).slice(0,8),[a,et]),es=(0,_.useMemo)(()=>a.filter(e=>null!=e.actual||new Date(e.scheduled_ts).getTime()<=et).sort((e,t)=>
8new Date(t.scheduled_ts).getTime()-new Date(e.scheduled_ts).getTime()).slice(0,12),[a,et]),en=(0,_.useMemo)(()=>{if(!U.length)return[];let e=U[0].time;return a.filter(e=>["mpob","its","amspec","policy"].includes(e.kind)).map(e=>{let t=Math.floor(new Date(e.scheduled_ts).getTime()/1e3);return{e,t}}).filter(({t})=>t>=e&&t<=et/1e3).map(({e,t})=>({time:t,position:"aboveBar",color:nM[e.kind]||"var(--text-muted)",shape:"arrowDown",text:"mpob"===e.kind?"MPOB":e.kind.toUpperCase().slice(0,6)}))},[a,U,et]);async function el(){$(!0),M("");try{await (0,er.authPostJson)("/api/fcpo/ai/read",{}),await Y()}catch(e){M(e instanceof Error?e.message:"Market read failed")}finally{$(!1)}}let ei=l[0]||null,eo=e?.health?.status||"unavailable",ec=e?.health?.quote_age_sec,ed="delayed"===eo?`INDICATIVE \xb7 ${nF(ec)}`:"closed"===eo?`CLOSED \xb7 ${nF(ec)}`:"stale"===eo?`STALE \xb7 ${nF(ec)}`:"NO QUOTE",eu=ea[0]||null,eh=h.find(e=>!!["long","short"].includes(e.direction)&&!e.grade&&new Date(e.created_at).getTime()+6e4*Number(e.horizon_min||240)>et)||null,ep=r.ZL||null,em=["stale"===eo||"unavailable"===eo||"closed"===eo&&Number(ec||0)>259200?"benchmark quote unavailable or operationally stale":null,!ep||ep.stale?"soyoil relative tape missing or stale":null,eu&&null==eu.consensus?"next catalyst has no consensus loaded":null,!ei?"no market read":et-new Date(ei.created_at||0).getTime()>72e5?"market read older than 2h":null,30>(m?.graded_total||0)?`signal sample unproven (n=${m?.graded_total||0})`:null].filter(Boolean),ex=eh?eh.direction:"stand_aside",eg=eh?`RESEARCH ${eh.direction.toUpperCase()}`:"STAND ASIDE",ef=[["ZL","CBOT soybean oil ¢/lb — the veg-oil complex leader"],["USDMYR","ringgit — weakness supports FCPO"],["BOPO","soyoil premium over palm USD/MT — substitution anchor"],["POGO","palm premium over gasoil USD/MT — biodiesel floor"],["GASOIL","ICE low-sulphur gasoil USD/MT"],["BRENT","Brent crude USD/bbl"]],eb=ef.filter(([e])=>!!r[e]),e_=ef.length-eb.length;return(0,b.jsxs)("div",{className:"fcpo-view",children:[(I.error||I.failedParts.length>0)&&(0,b.jsxs)("div",{className:"fcpo-load-alert",role:"status",children:[(0,b.jsx)(e1.AlertTriangle,{size:14}),(0,b.jsx)("span",{children:I.error||`Partial refresh failed: ${I.failedParts.join(", ")}. Last good values remain visible.`})]}),(0,b.jsxs)("div",{className:"radar-section fcpo-ticker",style:{flexDirection:"row",alignItems:"center",flexWrap:"wrap",gap:14,padding:"10px 14px"},children:[(0,b.jsxs)("div",{style:{display:"flex",gap:4,flexWrap:"wrap"},children:[(0,b.jsx)("button",{className:"btn btn-sm",onClick:()=>y("FCPOc3"),style:"FCPOc3"===W?{borderColor:"var(--accent, #4f8cff)",color:"var(--accent, #4f8cff)"}:{},title:"Continuous benchmark settle line — MPOC official daily settles",children:"FCPOc3"}),(e?.chain||[]).slice(0,4).map(e=>(0,b.jsxs)("button",{className:"btn btn-sm",onClick:()=>y(e.symbol),style:W===e.symbol?{borderColor:"var(--accent, #4f8cff)",color:"var(--accent, #4f8cff)"}:{},title:`last trade ${e.last_trade_date} (${e.days_to_last_trade}d)${e.is_benchmark?" · benchmark":""}`,children:[nC[e.month],String(e.year).slice(2),e.is_benchmark?"★":""]},e.symbol))]}),(0,b.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:8},children:[(0,b.jsx)("span",{style:{fontSize:22,fontWeight:700,fontVariantNumeric:"tabular-nums"}
8,children:null!=Z?`RM ${nE(Z)}`:null!=Q?`RM ${nE(Q)}`:"—"}),null!=ee&&(0,b.jsxs)("span",{style:{fontSize:13,fontWeight:600,color:ee>=0?"var(--success, #30a46c)":"var(--danger, #e5484d)"},children:[ee>=0?"+":"",nE(ee)," vs settle"]})]}),e&&(0,b.jsx)(nR,{session:e.session}),e?.limit_down!=null&&(0,b.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},title:"±10% daily price limits off the benchmark settle",children:["limits ",nE(e.limit_down)," / ",nE(e.limit_up)]}),(0,b.jsx)("span",{className:`fcpo-feed fcpo-feed-${eo}`,title:`Source ${e?.health?.source||"unknown"}; feed class ${e?.health?.feed_class||"unknown"}`,children:ed})]}),(0,b.jsxs)("div",{className:"fcpo-workspace-tabs",role:"tablist","aria-label":"FCPO workspace",children:[["desk","research","paper"].map(e=>(0,b.jsx)("button",{role:"tab","aria-selected":O===e,className:O===e?"active":"",onClick:()=>L(e),children:"desk"===e?"Live desk":"research"===e?"Research ledger":"Paper & journal"},e)),(0,b.jsx)("span",{children:I.lastOkMs?`synced ${nF((Date.now()-I.lastOkMs)/1e3)}`:I.loading?"loading desk…":"not synced"})]}),(0,b.jsxs)("section",{className:"fcpo-command-board","aria-label":"FCPO decision board",children:[(0,b.jsxs)("div",{className:`fcpo-command-call ${ex}`,children:[(0,b.jsx)("small",{children:"DESK POSTURE"}),(0,b.jsx)("strong",{children:eg}),(0,b.jsx)("span",{children:eh?`${eh.kind} trigger \xb7 ${eh.confidence} confidence \xb7 indicative only`:"No approved, unexpired deterministic trigger"})]}),(0,b.jsxs)("div",{className:"fcpo-command-cell",children:[(0,b.jsx)(e8.Database,{size:15}),(0,b.jsx)("small",{children:"PRICE EVIDENCE"}),(0,b.jsx)("strong",{children:e?.health?.source||"No source"}),(0,b.jsxs)("span",{children:[ed," · quotes are delayed, never execution-grade"]})]}),(0,b.jsxs)("div",{className:"fcpo-command-cell",children:[(0,b.jsx)(nx,{size:15}),(0,b.jsx)("small",{children:"NEXT CATALYST"}),(0,b.jsx)("strong",{children:eu?eu.title:"No scheduled rung"}),(0,b.jsx)("span",{children:eu?`${"estimated_schedule"===eu.source?"~":""}${nT(new Date(eu.scheduled_ts).getTime()-et)} \xb7 ${"estimated_schedule"===eu.source?"estimated time · ":""}${null==eu.consensus?"consensus missing":`consensus ${eu.consensus}${eu.unit||""}`}`:"Calendar needs attention"})]}),(0,b.jsxs)("div",{className:"fcpo-command-cell",children:[(0,b.jsx)(ny,{size:15}),(0,b.jsx)("small",{children:"RELATIVE TAPE"}),(0,b.jsx)("strong",{children:ep?`ZL ${Number(ep.change_pct||0)>=0?"+":""}${Number(ep.change_pct||0).toFixed(2)}% / 48h`:"ZL unavailable"}),(0,b.jsx)("span",{children:ep?`${nF(ep.age_sec)}${ep.stale?" · stale":""}`:"Print signals fail closed without soyoil"})]}),(0,b.jsxs)("div",{className:`fcpo-command-cell ${em.length?"warn":"ok"}`,children:[em.length?(0,b.jsx)(e1.AlertTriangle,{size:15}):(0,b.jsx)(tn,{size:15}),(0,b.jsx)("small",{children:"TRUST GATE"}),(0,b.jsx)("strong",{children:em.length?`${em.length} BLOCKERS`:"CLEARED"}),(0,b.jsx)("span",{title:em.join("\n"),children:em[0]||`Signals validated on ${m?.graded_total||0} observations`})]})]}),"desk"===O&&(0,b.jsx)(b.Fragment,{children:(0,b.jsxs)("div",{className:"fcpo-primary-grid",children:[(0,b.jsxs)("div",{className:"radar-section",style:{padding:12,minWidth:0},children:[(0,b.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,b.jsx)(nm.Activity,{size:14}),(0,b.jsxs)("span",{className:"radar-section-title",style:{margin:0},children:[W," · ",j]}),(0,b.jsxs)("button",{className:"btn btn-sm",onClick:q,disabled:T||"1d"!==j,title:"1d"===j?"Runs a daily quant feature read and marks daily structural levels":"TA is daily-only; intraday levels were previously mislabeled",children:[(0,b.jsx)(ng,{size:12})," ",T?"analyzing…":"1d"===j?"Daily desk read":"Daily-only read"]}),E&&(0,b.jsx)("button",{className:"btn btn-ghost btn-sm",onClick:()=>R(e=>!e),title:P?"hide the drawn levels":"show the drawn levels",children:P?"hide lines":"show lines"}),(0,b.jsx)("div",{style:{marginLeft:"auto",display:"flex",gap:4},children:["5m","1h","1d"].map(e=>(0,b.jsx)("button",{className:"btn btn-sm",onClick:()=>w(e),style:j===e?{borderColor:"var(--accent, #4f8cff)",color:"var(--accent, #4f8cff)"}:{},children:e},e))})]}),z&&(0,b.jsxs)("div",{className:"fcpo-inline-error",children:[(0,b.jsx)(e1.AlertTriangle,{size:12})," ",z]}),(0,b.jsx)("div",{style:{height:420},children:U.length?(0,b.jsx)(aT,{candles:U,markers:en,priceLines:V,overlayLines:G,onLoadMore:H,title:""}):(0,b.jsx)("div",{className:"empty-state",style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center"},children:"1d"===j?"No daily bars for this symbol yet.":"No intraday bars yet — they build up while a session is live (delayed feed)."})}),E&&(0,b.jsx)(nz,{snap:E}
8),(0,b.jsx)("div",{style:{fontSize:10,color:"var(--text-muted)"},children:"FCPOc3"===W?"FCPOc3 = official MPOC settle line (flat candles). Pick a month chip for full OHLC history.":"1d"===j?"Daily OHLC = exchange EOD history + today's live (delayed) session bar.":"Intraday bars are synthesized from ~15-min-delayed quotes — time-shifted, for observation not execution."})]}),(0,b.jsxs)("div",{className:"radar-section",style:{padding:12},children:[(0,b.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,b.jsx)(nb,{size:14}),(0,b.jsx)("span",{className:"radar-section-title",style:{margin:0},children:"Data ladder"}),(0,b.jsx)("span",{className:"radar-section-note",style:{marginLeft:"auto"},children:"click a rung to enter consensus/actual"})]}),(0,b.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6,overflowY:"auto",maxHeight:400},children:[0===ea.length&&(0,b.jsx)("div",{className:"empty-state",children:"No upcoming events — the nightly job generates the ladder."}),ea.map(e=>{let t=new Date(e.scheduled_ts).getTime();return(0,b.jsxs)("button",{onClick:()=>k(e),style:{display:"flex",alignItems:"center",gap:8,textAlign:"left",background:"var(--bg-input, #1a1c25)",border:"1px solid var(--border-subtle, #2a2d3a)",borderLeft:`3px solid ${nM[e.kind]||"var(--border-subtle)"}`,borderRadius:6,padding:"7px 9px",cursor:"pointer",color:"var(--text-primary, #e6e8f0)"},children:[(0,b.jsxs)("div",{style:{minWidth:0,flex:1},children:[(0,b.jsx)("div",{style:{fontSize:12,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:e.title}),(0,b.jsxs)("div",{style:{fontSize:10,color:"var(--text-muted)",marginTop:1},children:["estimated_schedule"===e.source?"~":"",nA(e.scheduled_ts)," MYT",null!=e.consensus?` \xb7 consensus ${e.consensus}${e.unit||""}`:" · no consensus yet",null!=e.prior?` \xb7 prior ${e.prior}${e.unit||""}`:"","estimated_schedule"===e.source?" · estimated release time":""]})]}),(0,b.jsxs)("span",{style:{fontSize:11,fontVariantNumeric:"tabular-nums",color:"var(--warning, #f5a524)",whiteSpace:"nowrap"},children:[(0,b.jsx)(nx,{size:10,style:{display:"inline",marginRight:3}}),nT(t-et)]})]},e.id)})]})]})]})}),"research"===O&&(0,b.jsx)(nD,{signals:h,scoreboard:m,onTake:e=>{f({side:"short"===e.direction?"short":"long",symbol:e.symbol,thesis:`[signal:${e.kind}] ${e.reason||""} | invalidation: ${e.invalidation||"—"}`}),L("paper")}}),"desk"===O&&(0,b.jsxs)("div",{className:"fcpo-primary-grid",children:[(0,b.jsxs)("div",{className:"radar-section",style:{padding:12,minWidth:0},children:[(0,b.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,b.jsx)(nm.Activity,{size:14}),(0,b.jsx)("span",{className:"radar-section-title",style:{margin:0},children:"Cross-market tape"}),(0,b.jsx)("span",{className:"radar-section-note",style:{marginLeft:"auto"},children:"prints trade RELATIVE to soyoil — check this before leaning on a surprise"})]}),(0,b.jsxs)("table",{className:"radar-moves-table",style:{width:"100%",fontSize:12},children:[(0,b.jsx)("thead",{children:(0,b.jsxs)("tr",{style:{color:"var(--text-muted)",fontSize:10,textAlign:"left"},children:[(0,b.jsx)("th",{children:"series"}),(0,b.jsx)("th",{children:"48h"}),(0,b.jsx)("th",{style:{textAlign:"right"},children:"last"}),(0,b.jsx)("th",{style:{textAlign:"right"},children:"48h %"}),(0,b.jsx)("th",{style:{textAlign:"right"},children:"freshness"}),(0,b.jsx)("th",{children:"what it is"})]})}),(0,b.jsx)("tbody",{children:eb.map(([e,t])=>{let a=r[e];return(0,b.jsxs)("tr",{className:a.stale?"fcpo-stale-row":"",style:{borderTop:"1px solid var(--border-subtle, #2a2d3a)"},children:[(0,b.jsx)("td",{style:{fontWeight:600,padding:"5px 4px"},children:e}),(0,b.jsx)("td",{children:(0,b.jsx)(nP,{points:a.points})}),(0,b.jsx)("td",{style:{textAlign:"right",fontVariantNumeric:"tabular-nums"},children:nE(a.latest,"USDMYR"===e?3:2)}),(0,b.jsx)("td",{style:{textAlign:"right",fontVariantNumeric:"tabular-nums",color:Number(a.change_pct||0)>=0?"var(--success, #30a46c)":"var(--danger, #e5484d)"},children:null!=a.change_pct?`${a.change_pct>=0?"+":""}${Number(a.change_pct).toFixed(2)}%`:"—"}),(0,b.jsx)("td",{style:{textAlign:"right",color:a.stale?"var(--danger, #e5484d)":"var(--text-muted)"},children:nF(a.age_sec)}
8),(0,b.jsx)("td",{style:{fontSize:10,color:"var(--text-muted)"},children:t})]},e)})})]}),e_>0&&(0,b.jsxs)("div",{className:"fcpo-data-footnote",children:[e_," unavailable series hidden — no empty rows posing as coverage."]})]}),(0,b.jsxs)("div",{className:"radar-section",style:{padding:12},children:[(0,b.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,b.jsx)(ng,{size:14}),(0,b.jsx)("span",{className:"radar-section-title",style:{margin:0},children:"AI market read"}),(0,b.jsxs)("button",{className:"btn btn-sm",style:{marginLeft:"auto"},onClick:el,disabled:S,children:[(0,b.jsx)(ts.RefreshCw,{size:12,style:S?{animation:"spin 1s linear infinite"}:{}}),S?" reading…":" refresh"]})]}),!ei&&(0,b.jsx)("div",{className:"empty-state",children:"No reads yet — runs hourly in-session and before ladder events."}),C&&(0,b.jsxs)("div",{className:"fcpo-inline-error",children:[(0,b.jsx)(e1.AlertTriangle,{size:12})," ",C]}),ei&&(0,b.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[(0,b.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,b.jsx)("span",{style:{fontSize:12,fontWeight:800,letterSpacing:.5,padding:"3px 10px",borderRadius:5,background:"long"===ei.bias?"rgba(48,164,108,0.15)":"short"===ei.bias?"rgba(229,72,77,0.15)":"var(--bg-input, #1a1c25)",color:"long"===ei.bias?"var(--success, #30a46c)":"short"===ei.bias?"var(--danger, #e5484d)":"var(--text-muted)"},children:ei.bias.toUpperCase()}),(0,b.jsxs)("span",{style:{fontSize:11,color:"var(--text-muted)"},children:[ei.confidence," conf · ",ei.horizon]})]}),(0,b.jsx)("div",{style:{fontSize:12,lineHeight:1.5},children:ei.summary}),(0,b.jsx)("ul",{style:{margin:0,paddingLeft:16,fontSize:11,color:"var(--text-muted)",display:"flex",flexDirection:"column",gap:3},children:(ei.reasons||[]).map((e,t)=>(0,b.jsx)("li",{children:e},t))}),ei.invalidation&&(0,b.jsxs)("div",{style:{fontSize:11,color:"var(--warning, #f5a524)"},children:["invalidation: ",ei.invalidation]}),(0,b.jsxs)("div",{style:{fontSize:10,color:"var(--text-muted)"},children:[ei.created_at?`${nA(ei.created_at)} MYT`:"",ei.price_at_read?` @ RM ${nE(ei.price_at_read)}`:""]}),l.length>1&&(0,b.jsx)("div",{style:{display:"flex",gap:4,flexWrap:"wrap",borderTop:"1px solid var(--border-subtle)",paddingTop:6},children:l.slice(1,7).map((e,t)=>(0,b.jsx)("span",{title:`${e.summary}
9${e.created_at?nA(e.created_at)+" MYT":""}`,style:{fontSize:9,fontWeight:700,padding:"2px 6px",borderRadius:4,background:"var(--bg-input, #1a1c25)",color:"long"===e.bias?"var(--success, #30a46c)":"short"===e.bias?"var(--danger, #e5484d)":"var(--text-muted)"},children:e.bias.toUpperCase().slice(0,1)},t))})]})]})]}),"research"===O&&(0,b.jsx)("div",{className:"fcpo-research-stack",children:(0,b.jsxs)("div",{className:"radar-section",style:{padding:12,minWidth:0},children:[(0,b.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,b.jsx)(nv,{size:14}),(0,b.jsx)("span",{className:"radar-section-title",style:{margin:0},children:"Print tracker"}),(0,b.jsx)("span",{className:"radar-section-note",style:{marginLeft:"auto"},children:"surprise vs consensus → measured reaction (the edge dataset)"})]}),(0,b.jsxs)("table",{className:"radar-moves-table",style:{width:"100%",fontSize:11},children:[(0,b.jsx)("thead",{children:(0,b.jsxs)("tr",{style:{color:"var(--text-muted)",fontSize:10,textAlign:"left"},children:[(0,b.jsx)("th",{children:"event"}),(0,b.jsx)("th",{style:{textAlign:"right"},children:"consensus"}),(0,b.jsx)("th",{style:{textAlign:"right"},children:"actual"}),(0,b.jsx)("th",{style:{textAlign:"right"},children:"surprise"}),(0,b.jsx)("th",{style:{textAlign:"right"},children:"px before"}),(0,b.jsx)("th",{style:{textAlign:"right"},children:"+1h"}),(0,b.jsx)("th",{style:{textAlign:"right"},children:"+1d"}),(0,b.jsx)("th",{})]})}),(0,b.jsxs)("tbody",{children:[0===es.length&&(0,b.jsx)("tr",{children:(0,b.jsx)("td",{colSpan:8,children:(0,b.jsx)("div",{className:"empty-state",children:"No released prints tracked yet."})})}),es.map(e=>(0,b.jsxs)("tr",{style:{borderTop:"1px solid var(--border-subtle, #2a2d3a)"},children:[(0,b.jsxs)("td",{style:{padding:"5px 4px"},children:[(0,b.jsx)("span",{style:{color:nM[e.kind]||"inherit",fontWeight:600},children:e.kind.toUpperCase()})," ",(0,b.jsx)("span",{style:{color:"var(--text-muted)"},children:e.period||nA(e.scheduled_ts)})]}),(0,b.jsx)("td",{style:{textAlign:"right",fontVariantNumeric:"tabular-nums"},children:e.consensus??"—"}),(0,b.jsx)("td",{style:{textAlign:"right",fontVariantNumeric:"tabular-nums",fontWeight:600},children:e.actual??"—"}),(0,b.jsx)("td",{style:{textAlign:"right",fontVariantNumeric:"tabular-nums",color:null==e.surprise?"var(--text-muted)":Number(e.surprise)>=0?"var(--success, #30a46c)":"var(--danger, #e5484d)"},children:null!=e.surprise?`${Number(e.surprise)>=0?"+":""}${e.surprise}`:"—"}),(0,b.jsx)("td",{style:{textAlign:"right",fontVariantNumeric:"tabular-nums"},children:e.price_before?nE(e.price_before):"—"}),(0,b.jsx)("td",{style:{textAlign:"right",fontVariantNumeric:"tabular-nums"},children:e.price_1h?nE(e.price_1h):"—"}),(0,b.jsx)("td",{style:{textAlign:"right",fontVariantNumeric:"tabular-nums"},children:e.price_1d?nE(e.price_1d):"—"}),(0,b.jsx)("td",{style:{textAlign:"right"},children:(0,b.jsx)("button",{className:"btn btn-ghost btn-sm",onClick:()=>k(e),title:"enter/correct the print",children:"edit"})})]},e.id))]})]})]})}),"research"===O&&(0,b.jsx)(nW,{journal:d,trades:o?.trades||[],reads:l,onAdd:Y}),"paper"===O&&(0,b.jsxs)("div",{className:"fcpo-paper-grid",children:[(0,b.jsx)(nB,{overview:e,paper:o,latestReadId:ei?.id,onChanged:Y,prefill:g}),(0,b.jsx)(nW,{journal:d,trades:o?.trades||[],reads:l,onAdd:Y})]}),N&&(0,b.jsx)(nO,{ev:N,onClose:()=>k(null),onSaved:Y})]})}let nI={gap:"overnight catch-up: FCPO open vs soyoil-implied fair value",print:"data-ladder surprise (exports/production/stocks vs consensus)",quant:"mean-reversion state with supportive conditional history"};function nD({signals:e,scoreboard:t,onTake:a}){return(0,b.jsxs)("div",{className:"radar-section",style:{padding:12},children:[(0,b.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[(0,b.jsx)(nm.Activity,{size:14}),(0,b.jsx)("span",{className:"radar-section-title",style:{margin:0},children:"Research triggers"}),(0,b.jsx)("span",{className:"radar-section-note",children:"deterministic hypotheses · risk judge fails closed · approved and vetoed cases are graded counterfactually"}),t&&t.graded_total>0&&(0,b.jsx)("span",{style:{marginLeft:"auto",display:"flex",gap:6,flexWrap:"wrap"},children:Object.entries(t.by_kind).map(([e,t])=>(0,b.jsxs)("span",{title:`${t.n} graded \xb7 ${t.hits} hit / ${t.misses} miss / ${t.flat} flat \xb7 avg ${t.avg_move_pct??"—"}%`,style:{fontSize:10,fontWeight:700,padding:"2px 8px",borderRadius:4,background:"var(--bg-input, #1a1c25)",border:"1px solid var(--border-subtle, #2a2d3a)",color:null==t.hit_rate?"var(--text-muted)":t.hit_rate>=55?"var(--success, #30a46c)":t.hit_rate<=45?"var(--danger, #e5484d)":"var(--warning, #f5a524)"},children:[e,": ",null!=t.hit_rate?`${t.hit_rate}%`:"—"," (n=",t.n,")"]},e))})]}),0===e.length&&(0,b.jsx)("div",{className:"empty-state",children:"No signals yet — they fire on open-gap residuals, ladder-print surprises you enter, and stats-backed mean-reversion extremes."}),(0,b.jsx)("div",{style:{display:"flex",flexDirection:"column",gap:5,maxHeight:260,overflowY:"auto"},children:e.map(e=>{let t,s="long"===(t=e.direction)?{color:"var(--success, #30a46c)",label:"▲ LONG"}:"short"===t?{color:"var(--danger, #e5484d)",label:"▼ SHORT"}:{color:"var(--text-muted, #8b8fa3)",label:"⏸ STAND ASIDE"};return(0,b.jsxs)("div",{style:{display:"flex",alignItems:"flex-start",ga
9p:8,fontSize:11,background:"var(--bg-input, #1a1c25)",border:"1px solid var(--border-subtle, #2a2d3a)",borderLeft:`3px solid ${s.color}`,borderRadius:6,padding:"7px 9px",opacity:"stand_aside"===e.direction?.65:1},children:[(0,b.jsx)("span",{title:nI[e.kind]||e.kind,style:{fontSize:9,fontWeight:800,letterSpacing:.5,padding:"2px 6px",borderRadius:4,background:"var(--bg-panel, #14161e)",border:"1px solid var(--border-subtle)",whiteSpace:"nowrap"},children:e.kind.toUpperCase()}),(0,b.jsx)("span",{style:{fontWeight:700,color:s.color,whiteSpace:"nowrap"},children:s.label}),(0,b.jsx)("span",{style:{whiteSpace:"nowrap"},children:e.symbol}),null!=e.entry_ref&&(0,b.jsxs)("span",{style:{color:"var(--text-muted)",whiteSpace:"nowrap"},children:["@ ",nE(e.entry_ref)]}),(0,b.jsxs)("span",{style:{fontSize:9.5,color:"var(--text-muted)",whiteSpace:"nowrap"},children:["(",e.confidence,")"]}),(0,b.jsx)("span",{style:{minWidth:0,color:"var(--text-muted)"},title:`${e.reason||""}
10invalidation: ${e.invalidation||"—"}`,children:e.reason}),(0,b.jsxs)("span",{style:{marginLeft:"auto",display:"flex",alignItems:"center",gap:6,whiteSpace:"nowrap"},children:[e.grade?(0,b.jsxs)("span",{style:{fontSize:9.5,fontWeight:800,padding:"2px 7px",borderRadius:4,background:"hit"===e.grade?"rgba(48,164,108,0.15)":"miss"===e.grade?"rgba(229,72,77,0.15)":"var(--bg-panel, #14161e)",color:"hit"===e.grade?"var(--success, #30a46c)":"miss"===e.grade?"var(--danger, #e5484d)":"var(--text-muted)"},children:[e.grade.toUpperCase()," ",null!=e.move_pct?`${Number(e.move_pct)>0?"+":""}${Number(e.move_pct).toFixed(2)}%`:""]}):(0,b.jsx)("span",{style:{fontSize:9.5,color:"var(--text-muted)"},children:"grading…"}),(0,b.jsx)("span",{style:{fontSize:9.5,color:"var(--text-muted)"},children:nA(e.created_at)}),"stand_aside"!==e.direction&&!e.grade&&(0,b.jsx)("button",{className:"btn btn-ghost btn-sm",onClick:()=>a(e),title:"pre-fill the paper ticket with this signal as the thesis",children:"take→paper"})]})]},e.id)})})]})}function nz({snap:e}){let[t,a]=(0,_.useState)(!1),s=e.features||{},r=e.created_at?(Date.now()-new Date(e.created_at).getTime())/36e5:null,n=null!=r&&r>36,l=(0,_.useMemo)(()=>{let e=s.trend||{},t=s.vol||{},a=s.meanrev||{},r=s.curve||{},n=s.flow||{},l=s.relval||{},i=a.conditional_forward?Object.entries(a.conditional_forward)[0]:null;return[["Trend",[["5d / 20d / 60d",[e.ret_5d_pct,e.ret_20d_pct,e.ret_60d_pct].map(e=>null!=e?`${e>0?"+":""}${e}%`:"—").join(" / ")],["EMA posture",e.ema_posture??"—"],["ADX14",e.adx14??"—"],["52w range pos",null!=e.pos_in_52w_range_pct?`${e.pos_in_52w_range_pct}%`:"—"],["mom t-stat 20d",e.mom_tstat_20d??"—"]]],["Volatility",[["ATR14",null!=t.atr14_rm?`RM ${t.atr14_rm} (${t.atr14_pct}%)`:"—"],["Parkinson 20d ann.",null!=t.parkinson_20d_ann_pct?`${t.parkinson_20d_ann_pct}%`:"—"],["vol regime pctile",null!=t.vol_regime_pctile?`${t.vol_regime_pctile}`:"—"],["±10% limit",null!=t.limit_move_in_atr?`${t.limit_move_in_atr} ATRs away`:"—"]]],["Mean reversion",[["z20 / z60",`${a.z20??"—"} / ${a.z60??"—"}`],["RSI14",a.rsi14??"—"],["1d autocorr (60d)",a.ret_autocorr_1d_60d??"—"],...i?[[`hist: ${i[0].replace(/_/g," ")}`,`${i[1].mean_pct>0?"+":""}${i[1].mean_pct}% avg, ${i[1].hit_rate_up}% up (n=${i[1].n})`]]:[]]],["Curve / carry",[["state",(r.state||"—").split(" (")[0]],["slope ann.",null!=r.curve_slope_ann_pct?`${r.curve_slope_ann_pct}%`:"—"],["benchmark carry",null!=r.benchmark_carry_ann_pct?`${r.benchmark_carry_ann_pct}%/yr`:"—"]]],["Flow",[["volume 5d/60d",null!=n.vol_5d_vs_60d?`${n.vol_5d_vs_60d}\xd7`:"—"],["OI 20d",null!=n.oi_chg_20d_pct?`${n.oi_chg_20d_pct>0?"+":""}${n.oi_chg_20d_pct}%`:"—"],["read",n.oi_read??"—"]]],["Relative value",[["vs soyoil",l.soyoil_relval_read?l.soyoil_relval_read.split(" (")[0]:"—"],["soyoil corr/beta 60d",null!=l.soyoil_corr_60d?`${l.soyoil_corr_60d} / ${l.soyoil_beta_60d}`:"—"],["vs gasoil",l.gasoil_relval_read?l.gasoil_relval_read.split(" (")[0]:"—"],["valuation quality",l.valuation_warning??l.valuation_status??"—"]]]]},[s]);return(0,b.jsxs)("div",{style:{fontSize:11,lineHeight:1.55,background:"var(--bg-input, #1a1c25)",border:"1px solid var(--border-subtle, #2a2d3a)",borderRadius:6,padding:"9px 11px",display:"flex",flexDirection:"column",gap:7},children:[(0,b.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[e.regime&&(0,b.jsx)("span",{style:{fontSize:10,fontWeight:800,letterSpacing:.4,padding:"2px 8px",borderRadius:4,background:"var(--bg-panel, #14161e)",border:"1px solid var(--border-subtle, #2a2d3a)",color:"var(--text-primary, #e6e8f0)"},children:nS[e.regime]||e.regime.toUpperCase()}),(0,b.jsx)("span",{style:{fontSize:10,fontWeight:800,letterSpacing:.4,padding:"2px 8px",borderRadius:4,background:"bullish"===e.bias?"rgba(48,164,108,0.15)":"bearish"===e.bias?"rgba(229,72,77,0.15)":"var(--bg-panel, #14161e)",color:"bullish"===e.bias?"var(--success, #30a46c)":"bearish"===e.bias?"var(--danger, #e5484d)":"var(--text-muted)"},children:(e.bias||"neutral").toUpperCase()}),null!=e.conviction&&(0,b.jsxs)("span",{title:`conviction ${e.conviction}/5`,style:{letterSpacing:2,color:"var(--warning, #f5a524)",fontSize:10},children:["●".repeat(e.conviction),(0,b.jsx)("span",{style:{opacity:.25},children:"●".repeat(Math.max(0,5-e.conviction))})]}),(0,b.jsx)("span",{style:{color:"var(--text-muted)",fontSize:10},children:e.created_at?`read ${nA(e.created_at)} MYT @ RM ${nE(e.price_at)}`:""}),n&&(0,b.jsxs)("span",{className:"fcpo-stale-badge",children:["STALE · ",Math.round(r||0),"h"]}),e.features&&(0,b.jsx)("button",{className:"btn btn-ghost btn-sm",style:{marginLeft:"auto"},onClick:()=>a(e=>!e),children:t?"hide stats":"show stats"})]}),n&&(0,b.jsxs)("div",{className:"fcpo-inline-error",children:[(0,b.jsx)(e1.AlertTriangle,{size:12})," This daily snapshot is stale. Its levels are historical context, not a current call."]}),(0,b.jsx)("div",{children:e.summary}),!!e.risk_flags?.length&&(0,b.jsx)("div",{style:{display:"flex",gap:5,flexWrap:"wrap"},children:e.risk_flags.map((e,t)=>(0,b.jsxs)("span",{style:{fontSize:9.5,padding:"2px 7px",borderRadius:4,background:"rgba(245,165,36,0.1)",border:"1px solid rgba(245,165,36,0.3)",color:"var(--warning, #f5a524)"},children:["⚠ ",e]},t))}),t&&(0,b.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(210px, 1fr))",gap:8,borderTop:"1px solid var(--border-subtle, #2a2d3a)",paddingTop:8},children:l.map(([e,t])=>(0,b.jsxs)("div",{children:[(0,b.jsx)("div",{style:{fontSize:9.5,fontWeight:800,letterSpacing:.6,color:"var(--text-muted)",marginBottom:3},children:e.toUpperCase()}),t.map(([e,t],a)=>(0,b.jsxs)("div",{style:{display:"flex",justifyContent:"space-between",gap:8,fontSize:10.5,padding:"1px 0"},children:[(0,b.jsx)("span",{style:{color:"var(--text-muted)"},children:e}),(0,b.jsx)("span",{style:{fontVariantNumeric:"tabular-nums",textAlign:"right"},children:String(t)})]},a))]},e))})]})}function nB({overview:e,paper:t,latestReadId:a,onChanged:s,prefill:r}){let[n,l]=(0,_.useState)("long"),[i,o]=(0,_.useState)(""),[c,d]=(0,_.useState)(1),[u,h]=(0,_.useState)(""),[p,m]=(0,_.useState)(!1),[x,g]=(0,_.useState)(null);(0,_.useEffect)(()=>{r&&(l(r.side),o(r.symbol),h(r.thesis))},[r]);let f=(e?.chain||[]).slice(0,4),v=i||e?.benchmark_symbol||"",y=e?.session?.is_trading;async function j(){m(!0),g(null);try{let e=await (0,er.authPostJson)("/api/fcpo/paper/order",{symbol:v,side:n,contracts:c,thesis:u,ai_read_id:a||null});
10e?.ok?(g({ok:!0,text:`filled ${n} ${c}x ${v} @ RM ${nE(e.fill_price)}${e.warning?` — ${e.warning}`:""}`}),h(""),s()):g({ok:!1,text:e?.error||"rejected"})}catch(e){g({ok:!1,text:e?.message||"order failed"})}finally{m(!1)}}async function w(e){m(!0);try{let t=await (0,er.authPostJson)("/api/fcpo/paper/close",{position_id:e});g(t?.ok?{ok:!0,text:`closed for ${Number(t.realized_myr)>=0?"+":""}RM ${nE(t.realized_myr,2)}`}:{ok:!1,text:t?.error||"close failed"}),s()}catch(e){g({ok:!1,text:e?.message||"close failed"})}finally{m(!1)}}let N=(0,_.useMemo)(()=>(t?.equity_curve||[]).map(e=>({time:Math.floor(new Date(e.recorded_at).getTime()/1e3),value:Number(e.equity_myr)})),[t]);return(0,b.jsxs)("div",{className:"radar-section",style:{padding:12},children:[(0,b.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,b.jsx)(nf,{size:14}),(0,b.jsx)("span",{className:"radar-section-title",style:{margin:0},children:"Paper desk"}),t&&(0,b.jsxs)("span",{style:{marginLeft:"auto",fontSize:12,fontVariantNumeric:"tabular-nums"},children:["eq ",(0,b.jsxs)("b",{children:["RM ",nE(t.equity_myr,0)]}),(0,b.jsxs)("span",{style:{marginLeft:6,color:t.unrealized_myr>=0?"var(--success, #30a46c)":"var(--danger, #e5484d)"},children:[t.unrealized_myr>=0?"+":"",nE(t.unrealized_myr,0)," open"]})]})]}),(0,b.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[(0,b.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,b.jsx)("div",{style:{display:"flex",borderRadius:6,overflow:"hidden",border:"1px solid var(--border-subtle, #2a2d3a)"},children:["long","short"].map(e=>(0,b.jsx)("button",{onClick:()=>l(e),style:{padding:"5px 12px",fontSize:11,fontWeight:700,border:"none",cursor:"pointer",background:n===e?"long"===e?"rgba(48,164,108,0.25)":"rgba(229,72,77,0.25)":"var(--bg-input, #1a1c25)",color:n===e?"long"===e?"var(--success, #30a46c)":"var(--danger, #e5484d)":"var(--text-muted)"},children:e.toUpperCase()},e))}),(0,b.jsx)("select",{value:v,onChange:e=>o(e.target.value),style:{background:"var(--bg-input, #1a1c25)",border:"1px solid var(--border-subtle, #2a2d3a)",borderRadius:6,color:"var(--text-primary, #e6e8f0)",fontSize:11,padding:"4px 6px"},children:f.map(e=>(0,b.jsxs)("option",{value:e.symbol,children:[e.symbol,e.is_benchmark?" ★":""]},e.symbol))}),(0,b.jsx)("input",{type:"number",min:1,value:c,onChange:e=>d(Math.max(1,Number(e.target.value)||1)),style:{width:52,background:"var(--bg-input, #1a1c25)",border:"1px solid var(--border-subtle, #2a2d3a)",borderRadius:6,color:"var(--text-primary, #e6e8f0)",fontSize:11,padding:"4px 6px"},title:"contracts (25 MT, RM25/point each)"})]}),(0,b.jsx)("textarea",{value:u,onChange:e=>h(e.target.value),rows:2,placeholder:"Thesis (required) — why this trade, what invalidates it. No thesis, no trade.",style:{background:"var(--bg-input, #1a1c25)",border:"1px solid var(--border-subtle, #2a2d3a)",borderRadius:6,padding:"6px 8px",color:"var(--text-primary, #e6e8f0)",fontSize:11,resize:"vertical"}}),(0,b.jsx)("button",{className:`btn btn-sm ${"long"===n?"btn-success":"btn-danger"}`,onClick:j,disabled:p||!u.trim()||!y,title:y?u.trim()?"":"write the thesis first":"market closed — orders only inside FCPO sessions",children:p?"…":`paper ${n.toUpperCase()} ${c}x ${v}${!y?" (closed)":""}`}),x&&(0,b.jsx)("div",{style:{fontSize:11,color:x.ok?"var(--success, #30a46c)":"var(--danger, #e5484d)"},children:x.text})]}),(0,b.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[(t?.positions||[]).map(e=>(0,b.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:11,background:"var(--bg-input, #1a1c25)",border:"1px solid var(--border-subtle, #2a2d3a)",borderRadius:6,padding:"6px 8px"},title:e.thesis||"",children:[(0,b.jsxs)("span",{style:{fontWeight:700,color:"long"===e.side?"var(--success, #30a46c)":"var(--danger, #e5484d)"},children:["long"===e.side?"▲":"▼"," ",e.contracts,"x ",e.symbol]}),(0,b.jsxs)("span",{style:{color:"var(--text-muted)"},children:["@ ",nE(e.entry_price)]}),(0,b.jsxs)("span",{style:{marginLeft:"auto",fontVariantNumeric:"tabular-nums",fontWeight:600,color:Number(e.unrealized_myr||0)>=0?"var(--success, #30a46c)":"var(--danger, #e5484d)"},children:[Number(e.unrealized_myr||0)>=0?"+":"","RM ",nE(e.unrealized_myr,0)]}),(0,b.jsx)("button",{className:"btn btn-ghost btn-sm",onClick:()=>w(e.id),disabled:p||!y,children:"close"})]},e.id)),t&&!t.positions?.length&&(0,b.jsx)("div",{style:{fontSize:11,color:"var(--text-muted)"},children:"flat — the research says overtrading is what kills retail here"})]}),N.length>1&&(0,b.jsx)(eE,{equityCurve:N,height:120,compact:!0})]})}function nW({journal:e,trades:t,reads:a,onAdd:s}){let[r,n]=(0,_.useState)(""),[l,i]=(0,_.useState)(!1),o=(0,_.useMemo)(()=>{let s=[];for(let t of e)s.push({ts:new Date(t.created_at).getTime(),kind:t.entry_type||"note",text:t.body});for(let e of t)s.push({ts:new Date(e.executed_at).getTime(),kind:"trade",text:`${e.action} ${e.side} ${e.contracts}x ${e.symbol} @ RM ${nE(e.price)}${null!=e.realized_myr?` → ${Number(e.realized_myr)>=0?"+":""}RM ${nE(e.realized_myr,2)}`:""}${e.thesis?` — ${e.thesis}`:""}`});for(let e of a)e.created_at&&s.push({ts:new Date(e.created_at).getTime(),kind:"ai",text:`${e.bias.toUpperCase()} (${e.confidence}) — ${e.summary}`});return s.sort((e,t)=>
10t.ts-e.ts).slice(0,40)},[e,t,a]);async function c(){if(r.trim()){i(!0);try{await (0,er.authPostJson)("/api/fcpo/journal",{body:r.trim(),entry_type:"observation"}),n(""),s()}catch{}finally{i(!1)}}}let d={trade:"var(--accent, #4f8cff)",ai:"#b17bdb",postmortem:"var(--warning, #f5a524)",observation:"var(--text-muted, #8b8fa3)",note:"var(--text-muted, #8b8fa3)"};return(0,b.jsxs)("div",{className:"radar-section",style:{padding:12},children:[(0,b.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,b.jsx)(nv,{size:14}),(0,b.jsx)("span",{className:"radar-section-title",style:{margin:0},children:"Decision log"}),(0,b.jsx)("span",{className:"radar-section-note",style:{marginLeft:"auto"},children:"trades + AI reads + your observations, one timeline"})]}),(0,b.jsxs)("div",{style:{display:"flex",gap:6},children:[(0,b.jsx)("input",{value:r,onChange:e=>n(e.target.value),onKeyDown:e=>{"Enter"===e.key&&c()},placeholder:"log an observation — how did the 14:30 reopen trade after the print?",style:{flex:1,background:"var(--bg-input, #1a1c25)",border:"1px solid var(--border-subtle, #2a2d3a)",borderRadius:6,padding:"6px 8px",color:"var(--text-primary, #e6e8f0)",fontSize:11}}),(0,b.jsxs)("button",{className:"btn btn-sm",onClick:c,disabled:l||!r.trim(),children:[(0,b.jsx)(nj,{size:12})," log"]})]}),(0,b.jsxs)("div",{style:{display:"flex",flexDirection:"column",gap:3,maxHeight:260,overflowY:"auto"},children:[0===o.length&&(0,b.jsx)("div",{className:"empty-state",children:"Nothing logged yet."}),o.map((e,t)=>(0,b.jsxs)("div",{style:{display:"flex",gap:8,fontSize:11,padding:"4px 2px",borderTop:t?"1px solid var(--border-subtle, #2a2d3a)":"none"},children:[(0,b.jsx)("span",{style:{color:"var(--text-muted)",whiteSpace:"nowrap",fontVariantNumeric:"tabular-nums"},children:nA(e.ts)}),(0,b.jsx)("span",{style:{color:d[e.kind]||"var(--text-muted)",fontWeight:700,minWidth:44,textTransform:"uppercase",fontSize:9,paddingTop:1},children:e.kind}),(0,b.jsx)("span",{style:{minWidth:0},children:e.text})]},t))]})]})}let nU={mlb:"⚾",nba:"🏀",nhl:"🏒",atp:"🎾",wta:"🎾",nfl:"🏈","soccer-fifwc":"⚽","league-of-legends":"🎮","rainbow-six-siege":"🎮",overwatch:"🎮","counter-strike":"🎮","international-cricket":"🏏"},nH={bet365:{label:"bet365",cls:"src-b365"},espn:{label:"ESPN",cls:"src-espn"},polymarket:{label:"Polymarket",cls:"src-pm"},clob_jump:{label:"⚡ price jump",cls:"src-jump"}},nq=e=>null==e?"—":`${(100*e).toFixed(1)}c`;function nV(){let[e,t]=(0,_.useState)([]),[a,s]=(0,_.useState)(0),[r,n]=(0,_.useState)(!0),{openTab:l}=(0,ez.useMarketTabs)();(0,_.useEffect)(()=>{let e=!1,a=()=>(0,er.authGetJson)("/api/sports/live").then(a=>{e||(t(a.data?.events||[]),s(a.data?.streaming_tokens||0),n(!1))}).catch(()=>!e&&n(!1));a();let r=window.setInterval(a,5e3);return()=>{e=!0,window.clearInterval(r)}},[]);let i=new Map;for(let t of e){let e=t.series||"other";i.has(e)||i.set(e,[]),i.get(e).push(t)}return(0,b.jsxs)("div",{className:"wc-view",children:[(0,b.jsxs)("div",{className:"wc-toolbar",children:[(0,b.jsx)("span",{className:"wc-title",children:"📡 Live Sports"}),(0,b.jsxs)("span",{className:"wc-note",children:[e.length," live events · ",a," markets streaming sub-second · click any event for its detail page"]})]}),r?(0,b.jsx)("div",{className:"empty-state",children:"Scanning live events…"}):0===e.length?(0,b.jsx)("div",{className:"empty-state",children:"Nothing live on Polymarket right now."}):Array.from(i.entries()).map(([e,t])=>(0,b.jsxs)("div",{className:"wc-day",children:[(0,b.jsxs)("div",{className:"wc-day-head",children:[nU[e]||"🎲"," ",e]}),t.map(e=>(0,b.jsxs)("div",{className:"ls-event ls-clickable",onClick:()=>{let t;return t=nU[e.series||""]||"📡",void("soccer-fifwc"===e.series?l({kind:"wc",marketId:e.event_id,title:`⚽ ${e.title}`}):l({kind:"sport",marketId:e.event_id,title:`${t} ${e.title.slice(0,40)}`}))},children:[(0,b.jsxs)("div",{className:"ls-event-head",children:[(0,b.jsx)("span",{className:"ls-event-title",children:e.title}),(0,b.jsxs)("span",{className:"ls-event-score",children:[e.score||""," ",e.period?`\xb7 ${e.period}`:""," ",null!=e.elapsed?`\xb7 ${e.elapsed}'`:""]}),e.jump?(0,b.jsx)("span",{className:"wc-jump-badge",children:"⚡ jump"}):null,(0,b.jsx)("span",{className:"ls-open-hint",children:"open ›"})]}),(0,b.jsx)("div",{className:"ls-mkts",children:e.markets.slice(0,3).map((e,t)=>(0,b.jsxs)("span",{className:`ls-mkt${e.streamed?" streamed":""}`,children:[e.question.replace(/^Will\s+/i,"").slice(0,36)," ",(0,b.jsx)("b",{children:nq(e.price)}),e.streamed?(0,b.jsx)("span",{className:"ls-dot"}):null]},t))})]},e.event_id))]},e))]})}function nG({label:e,home:t,away:a}){let s=Number(t),r=Number(a);if(!Number.isFinite(s)&&!Number.isFinite(r))return(0,b.jsxs)("div",{className:"wc-statbar",children:[(0,b.jsx)("span",{className:"wc-statbar-val",children:String(t??"—")}),(0,b.jsx)("div",{className:"wc-statbar-track"}),(0,b.jsx)("span",{className:"wc-statbar-val",children:String(a??"—")}),(0,b.jsx)("span",{className:"wc-statbar-label",children:e})]});let n=Number.isFinite(s)?s:0,l=Number.isFinite(r)?r:0,i=n+l||1;return(0,b.jsxs)("div",{className:"wc-statbar",children:[(0,b.jsx)("span",{className:"wc-statbar-val",children:n}),(0,b.jsxs)("div",{className:"wc-statbar-track",children:[(0,b.jsx)("div",{className:"wc-statbar-h",style:{width:`${n/i*100}%`}}),(0,b.jsx)("div",{className:"wc-statbar-a",style:{width:`${l/i*100}%`}})]}),(0,b.jsx)("span",{className:"wc-statbar-val",children:l}),(0,b.jsx)("span",{className:"wc-statbar-label",children:e})]})}function nJ({history:e}){let t=(0,_.useRef)(null),a=(0,_.useRef)(null),s=(0,_.useRef)(new Map),r=["#4f8cff","#ff7b7b","#9aa0a6"];(0,_.useEffect)(()=>
10{if(!t.current)return;let e=(0,A.createChart)(t.current,{...(0,T.makeChartOptions)(260),autoSize:!0,rightPriceScale:{borderVisible:!1}});return a.current=e,()=>{e.remove(),a.current=null,s.current.clear()}},[]),(0,_.useEffect)(()=>{let t=a.current;t&&(Object.entries(e).forEach(([e,a],n)=>{let l=s.current.get(e);l||(l=t.addSeries(A.LineSeries,{color:r[n%r.length],lineWidth:2,priceFormat:{type:"custom",formatter:e=>`${(100*e).toFixed(1)}c`}}),s.current.set(e,l)),l.setData(a.map(e=>({time:e.t,value:e.p})))}),t.timeScale().fitContent())},[e]);let n=Object.keys(e);return 0===n.length?null:(0,b.jsxs)("div",{className:"wc-chart",children:[(0,b.jsx)("div",{className:"wc-chart-legend",children:n.map((e,t)=>(0,b.jsxs)("span",{style:{color:r[t%r.length]},children:["━ ",e.replace(/^Will\s+/i,"").slice(0,34)]},e))}),(0,b.jsx)("div",{ref:t,className:"wc-chart-canvas",style:{height:260}})]})}function nY({eventId:e,onClose:t,inline:a=!1,onTitle:s}){let[r,n]=(0,_.useState)(null),l=(0,_.useRef)(new Map),[i,o]=(0,_.useState)(new Set);if((0,_.useEffect)(()=>{let t=!1,a=()=>(0,er.authGetJson)(`/api/sports/live/${e}`).then(e=>{if(t||!e.data)return;let a=e.data,r=new Set;a.markets.forEach((e,t)=>{let a=l.current.get(String(t));null!=e.price&&null!=a&&Math.abs(e.price-a)>=.004&&r.add(String(t)),null!=e.price&&l.current.set(String(t),e.price)}),r.size&&(o(r),window.setTimeout(()=>o(new Set),1200)),n(a);let i=nU[a.series||""]||"📡",c=a.live?` \xb7 ${a.score||""} ${null!=a.elapsed?a.elapsed+"'":a.period||""}`:"";s?.(`${i} ${String(a.title).slice(0,36)}${c}`.trim())}).catch(()=>{});a();let r=window.setInterval(a,3e3);return()=>{t=!0,window.clearInterval(r)}},[e]),!r)return(0,b.jsx)(s7.OverlayWrap,{inline:a,onClose:t,children:(0,b.jsx)("div",{className:"radar-overlay-panel",onClick:e=>e.stopPropagation(),children:(0,b.jsx)("div",{className:"empty-state",children:"Loading event…"})})});let c=r.jump&&Date.now()-(r.jump.ts_ms||0)<12e4;return(0,b.jsx)(s7.OverlayWrap,{inline:a,onClose:t,children:(0,b.jsxs)("div",{className:"radar-overlay-panel",onClick:e=>e.stopPropagation(),children:[(0,b.jsxs)("div",{className:"radar-overlay-head",children:[(0,b.jsxs)("div",{className:"wc-match-head",children:[(0,b.jsxs)("div",{className:"wc-match-title",children:[(0,b.jsxs)("span",{className:"wc-team-big",children:[nU[r.series||""]||"📡"," ",r.title]}),(0,b.jsx)("span",{className:"wc-score-big",children:r.score||""})]}),(0,b.jsxs)("div",{className:"wc-match-sub",children:[r.live?(0,b.jsxs)("span",{className:"wc-live-badge",children:["● LIVE ",null!=r.elapsed?`${r.elapsed}'`:r.period||""]}):r.ended?"ended":"pre-game",c?(0,b.jsxs)("span",{className:"wc-jump-badge",children:["⚡ book jumped ",(100*(r.jump?.delta||0)).toFixed(0),"pp — before any score feed printed"]}):null,r.event_slug?(0,b.jsxs)(b.Fragment,{children:[" · ",(0,b.jsx)("a",{className:"radar-link",href:`https://polymarket.com/event/${r.event_slug}`,target:"_blank",rel:"noreferrer",children:"trade on Polymarket ↗"})]}):null]})]}),!a&&(0,b.jsx)("button",{className:"radar-overlay-close",onClick:t,children:"×"})]}),(0,b.jsx)("div",{className:"wc-outcomes ls-outcomes",children:r.markets.slice(0,6).map((e,t)=>(0,b.jsxs)("div",{className:`wc-outcome-card${i.has(String(t))?" wc-row-flash":""}`,children:[(0,b.jsx)("div",{className:"wc-outcome-label",children:e.question.replace(/^Will\s+/i,"").slice(0,48)}),(0,b.jsx)("div",{className:"wc-outcome-price",children:nq(e.price)}),(0,b.jsx)("div",{className:"wc-outcome-fair",children:e.streamed?(0,b.jsxs)("span",{className:"ls-streamtag",children:[(0,b.jsx)("span",{className:"ls-dot"})," sub-second stream"]}):(0,b.jsx)("span",{className:"wc-power-sub",children:"listing price"})})]},t))}),(0,b.jsxs)("div",{className:"radar-section-note",children:["No fair-odds model for this sport yet — signals here are ",(0,b.jsx)("b",{children:"price-action"}),": the ⚡ tripwire fires when the book moves ≥8pp within seconds (usually a score the feeds haven't printed). The World Cup pages carry the full model."]}),r.b365&&r.b365.stats.length>0&&(0,b.jsxs)("div",{className:"radar-section",children:[(0,b.jsxs)("div",{className:"radar-section-title",children:["Live stats — bet365 scout feed",null!=r.b365.age_s?(0,b.jsxs)("span",{className:"wc-power-sub",style:{marginLeft:8},children:["updated ",r.b365.age_s,"s ago"]}):null]}),(0,b.jsxs)("div",{className:"wc-livestrip",children:[(0,b.jsxs)("div",{className:"wc-livestrip-head",children:[r.b365.home," ",(0,b.jsx)("span",{className:"wc-power-sub",children:"vs"})," ",r.b365.away,null!=r.b365.minute?(0,b.jsxs)("span",{className:"wc-power-sub",style:{marginLeft:8},children:["minute ",r.b365.minute]}):null]}),r.b365.stats.map((e,t)=>(0,b.jsx)(nG,{label:e.label,home:e.home,away:e.away},t))]})]}),(0,b.jsxs)("div",{className:"radar-section",children:[(0,b.jsx)("div",{className:"radar-section-title",children:"Price history (today)"}),(0,b.jsx)(nJ,{history:r.history})]}),(0,b.jsxs)("div",{className:"radar-section",children:[(0,b.jsx)("div",{className:"radar-section-title",children:"Data feed — this event, source-labeled"}),0===r.feed.length?(0,b.jsx)("div",{className:"radar-section-note",children:"No datapoints recorded yet — they appear here as scores change."}):(0,b.jsx)("div",{className:"ls-feed-inline",children:r.feed.map((e,t)=>(0,b.jsxs)("div",{className:"ls-feed-row",children:[(0,b.jsx)("span",{className:"ls-feed-time",children:new Date(e.ts_ms).toLocaleTimeString()}),(0,b.jsx)("span",{className:`ls-src ${nH[e.source]?.cls||""}`,children:nH[e.source]?.label||e.source}),(0,b.jsx)("span",{className:"ls-feed-score",children:e.score})]},`${e.ts_ms}-${t}`))})]})]})})}let nK={lol:{icon:"🧙",label:"LoL"},cs2:{icon:"🔫",label:"CS2"},val:{icon:"🎯",label:"Valorant"},dota2:{icon:"🛡️",label:"Dota 2"}},nX=e=>null==e?"—":`${(100*e).toFixed(0)}c`;function nZ({eventId:e,onClose:t,inline:a=!1,onTitle:s}){let{openTab:r}=(0,ez.useMarketTabs)(),[n,l]=(0,_.useState)(null),[i,o]=(0,_.useState)(!1);(0,_.useEffect)(()=>{let t=!1,a=()=>(0,er.authGetJson)(`/api/esports/matches/${e}`).then(e=>{if(t||!e.data)return;l({match:e.data.match,signals:e.data.signals||[],commentary:e.data.commentary||[]});let a=e.data.match;a&&s&&s(`${nK[a.title]?.icon||"🎮"} ${a.t1} v ${a.t2}`)}).catch(()=>{});a();let r=window.setInterval(a,2e4);return()=>{t=!0,window.clearInterval(r)}},[e,s]);let c=n?.match,d=(n?.signals||[]).filter(e=>"no_play"!==e.signal),u=i?n?.signals||[]:d.slice(0,8);return(0,b.jsx)(s7.OverlayWrap,{inline:a,onClose:t,children:(0,b.jsxs)("div",{className:"radar-overlay-panel wc-overlay",onClick:e=>e.stopPropagation(),children:[c&&(0,b.jsxs)("div",{className:"radar-section",children:[(0,b.jsxs)("div",{className:"radar-section-title",children:[nK[c.title]?.icon||"🎮"," ",c.t1," ",(0,b.jsx)("span",{className:"wc-power-sub",children:"vs"})," ",c.t2,(0,b.jsxs)("span",{className:"wc-power-sub",children:[" · BO",c.best_of||"?",c.tournament?` \xb7 ${c.tournament}`:""]}),"live"===c.status?(0,b.jsxs)("span",{className:"radar-up",children:[" · 🔴 maps ",c.maps_t1??0,"-",c.maps_t2??0,c.map_score?` \xb7 m${c.current_map} ${c.map_score}`:""]}):"finished"===c.status?(0,b.jsxs)("span",{className:"wc-power-sub",children:[" · final ",c.maps_t1,"-",c.maps_t2]}):null]}),(0,b.jsxs)("div",{className:"wc-power-sub",children:[c.t1," ",nX(c.prices?.t1)," · ",c.t2," ",nX(c.prices?.t2),(0,b.jsx)("button",{className:"radar-addr-btn",style:{marginLeft:10},onClick:()=>r({kind:"sport",marketId:e,title:`📈 ${c.t1} v ${c.t2}`}),children:"📈 live stream chart"})]})]}),(0,b.jsxs)("div",{className:"radar-section",children:[(0,b.jsxs)("div",{className:"radar-section-title",children:["🤖 AI Live Read ",(0,b.jsx)("span",{className:"wc-power-sub",children:"— one decision every ~3 min while live; graded after the series"})]}),n?0===u.length?(0,b.jsx)("div",{className:"empty-state",children:0===d.length&&(n.signals||[]).length>0?"No actionable calls yet — the brain has passed (no_play) so far.":"No signals yet — they start once the series is live."}):u.map((e,t)=>(0,b.jsxs)("div",{className:"radar-gtm-row",children:[(0,b.jsx)("span",{className:`radar-badge ${"no_play"===e.signal?"":e.signal.includes("under")?"radar-badge-down":"radar-badge-up"}`,children:"no_play"===e.signal?"no play":e.signal.replace("back_","").replace("_"," ")})," ",e.bet?(0,b.jsx)("b",{children:e.bet}):null,null!=e.entry_price?(0,b.jsxs)("span",{className:"wc-power-sub",children:[" @ ",nX(e.entry_price)]}):null,e.confidence?(0,b.jsxs)("span",{className:"wc-power-sub",children:[" · ",e.confidence]}):null,(0,b.jsxs)("span",{className:"wc-power-sub",children:[" · m",e.minute,e.score?` (${e.score})`:""]}),e.result?(0,b.jsxs)("span",{className:"win"===e.result?"radar-up":"radar-down",children:[" · ",e.result.toUpperCase()]}):null,e.polymarket_url?(0,b.jsx)("a",{className:"radar-link",href:e.polymarket_url,target:"_blank",rel:"noreferrer",onClick:e=>e.stopPropagation(),children:" ↗ trade"}):null,e.reason?(0,b.jsx)("div",{className:"wc-power-sub",children:e.reason}):null]},t)):(0,b.jsx)("div",{className:"wc-power-sub",children:"loading…"}),n&&n.signals.length>u.length&&!i?(0,b.jsxs)("button",{className:"radar-addr-btn",onClick:()=>o(!0),children:["▸ show all ",n.signals.length," reads (incl. no-plays)"]}):i?(0,b.jsx)("button",{className:"radar-addr-btn",onClick:()=>o(!1),children:"▾ collapse"}):null]}),n&&n.commentary.length>0&&(0,b.jsxs)("div",{className:"radar-section",children:[(0,b.jsxs)("div",{className:"radar-section-title",children:["📜 Narration ",(0,b.jsx)("span",{className:"wc-power-sub",children:"— synthesized from series state 
10+ market moves"})]}),n.commentary.slice(-12).reverse().map((e,t)=>(0,b.jsxs)("div",{className:"wc-power-sub",children:[e.disp," ",e.text]},t))]})]})})}function nQ(){let{openTab:e}=(0,ez.useMarketTabs)(),[t,a]=(0,_.useState)([]),[s,r]=(0,_.useState)(""),[n,l]=(0,_.useState)(!0),[i,o]=(0,_.useState)(null),[c,d]=(0,_.useState)({});(0,_.useEffect)(()=>{let e=!1,t=()=>(0,er.authGetJson)(`/api/esports/matches${s?`?title=${s}`:""}`).then(t=>{e||a(t.data?.matches||[])}).catch(()=>{}).finally(()=>{e||l(!1)});t();let r=window.setInterval(t,3e4);return()=>{e=!0,window.clearInterval(r)}},[s]);let u=t.filter(e=>"live"===e.status),h=t.filter(e=>"scheduled"===e.status),p=t.filter(e=>"finished"===e.status),m=(e,t)=>(0,b.jsxs)("div",{className:"radar-gtm-row",style:{padding:"4px 8px"},children:[(0,b.jsx)("span",{className:`radar-badge ${"no_play"===e.signal?"":e.signal.includes("under")?"radar-badge-down":"radar-badge-up"}`,children:"no_play"===e.signal?"no play":e.signal.replace("back_","").replace("_"," ")})," ",e.bet?(0,b.jsx)("b",{children:e.bet}):null,null!=e.entry_price?(0,b.jsxs)("span",{className:"wc-power-sub",children:[" @ ",nX(e.entry_price)]}):null,e.confidence?(0,b.jsxs)("span",{className:"wc-power-sub",children:[" · ",e.confidence]}):null,(0,b.jsxs)("span",{className:"wc-power-sub",children:[" · m",e.minute,e.score?` (${e.score})`:""]}),e.result?(0,b.jsxs)("span",{className:"win"===e.result?"radar-up":"radar-down",children:[" · ",e.result.toUpperCase()]}):null,e.reason?(0,b.jsx)("div",{className:"wc-power-sub",children:e.reason}):null]},t),x=t=>{let a=nK[t.title]||{icon:"🎮",label:t.title},s=t.prices?.t1,r=t.prices?.t2,n=i===t.event_id,l=c[t.event_id];return(0,b.jsxs)(_.Fragment,{children:[(0,b.jsxs)("tr",{onClick:()=>{var e;return e=t.event_id,void(o(t=>t===e?null:e),!c[e]&&(0,er.authGetJson)(`/api/esports/matches/${e}`).then(t=>d(a=>({...a,[e]:{signals:t.data?.signals||[],commentary:t.data?.commentary||[]}}))).catch(()=>{}))},style:{cursor:"pointer"},children:[(0,b.jsxs)("td",{className:"radar-num",children:[a.icon," ",a.label]}),(0,b.jsxs)("td",{className:"radar-col-q",children:[(0,b.jsxs)("div",{className:"radar-q",children:[t.t1," ",(0,b.jsx)("span",{className:"wc-power-sub",children:"vs"})," ",t.t2,t.best_of?(0,b.jsxs)("span",{className:"wc-power-sub",children:[" · BO",t.best_of]}):null,(0,b.jsxs)("span",{className:"wc-power-sub",children:[" ",n?"▾":"▸"]})]}),t.tournament?(0,b.jsx)("div",{className:"wc-power-sub",children:t.tournament}):null]}),(0,b.jsxs)("td",{className:"radar-num",children:[nX(s)," / ",nX(r)]}),(0,b.jsx)("td",{className:"radar-num",children:"live"===t.status?(0,b.jsxs)("span",{className:"radar-up",children:["🔴 ",t.maps_t1??0,"-",t.maps_t2??0,t.map_score?` \xb7 m${t.current_map??"?"} ${t.map_score}`:""]}):"finished"===t.status?(0,b.jsxs)("span",{className:"wc-power-sub",children:[t.maps_t1??"—","-",t.maps_t2??"—"," final"]}):function(e){if(!e)return"—";let t=new Date(e),a=Math.round((e-Date.now())/6e4);return a>-30&&a<0?"kicking off":a>=0&&a<60?`in ${a}m`:a>=60&&a<2160?`in ${Math.round(a/60)}h`:t.toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}(t.start_ts)})]}),n&&(0,b.jsx)("tr",{children:(0,b.jsxs)("td",{colSpan:4,style:{background:"rgba(255,255,255,0.02)"},children:[(0,b.jsx)("div",{className:"radar-section-title",style:{fontSize:12},children:"🤖 AI signals"}),l?0===l.signals.length?(0,b.jsx)("div",{className:"wc-power-sub",children:"No signals yet — the brain reads live series every ~3 min."}):l.signals.slice(0,8).map(m):(0,b.jsx)("div",{className:"wc-power-sub",children:"loading…"}),l&&l.commentary.length>0&&(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)("div",{className:"radar-section-title",style:{fontSize:12,marginTop:6},children:"📜 Narration"}),l.commentary.slice(-5).map((e,t)=>(0,b.jsxs)("div",{className:"wc-power-sub",children:[e.disp," ",e.text]},t))]}),(0,b.jsx)("button",{className:"radar-addr-btn",style:{marginTop:6},onClick:a=>{let s;a.stopPropagation(),s=nK[t.title]||{icon:"🎮",label:t.title},e({kind:"es",marketId:t.event_id,title:`${s.icon} ${t.t1} v ${t.t2}`})},children:"▸ open live stream view"})]})},`${t.event_id}-x`)]},t.event_id)},g=(e,t)=>t.length>0&&(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)("div",{className:"radar-section-title",style:{marginTop:14},children:e}),(0,b.jsxs)("table",{className:"radar-table",children:[(0,b.jsx)("thead",{children:(0,b.jsxs)("tr",{children:[(0,b.jsx)("th",{children:"Game"}),(0,b.jsx)("th",{className:"radar-col-q",children:"Match"}),(0,b.jsx)("th",{children:"Prices"}),(0,b.jsx)("th",{children:"Status"})]})}),(0,b.jsx)("tbody",{children:t.map(x)})]})]});return(0,b.jsx)("div",{className:"radar-view",children:(0,b.jsxs)("div",{className:"radar-section",children:[(0,b.jsx)("div",{className:"radar-section-title",children:"🎮 Esports — Polymarket board"}),(0,b.jsx)("div",{className:"radar-section-note",children:"LoL + CS2 carry the volume (~$20
10M/day); Valorant/Dota light up during majors. Books trade in-play — map winners restart fresh each map. Click a match for the live stream view."}),(0,b.jsx)("div",{className:"trader-chart-pills",style:{marginTop:8},children:["","lol","cs2","val","dota2"].map(e=>(0,b.jsx)("button",{className:`trader-chart-pill${s===e?" active":""}`,onClick:()=>r(e),children:""===e?"All":nK[e]?.label||e},e||"all"))}),n?(0,b.jsx)("div",{className:"empty-state",children:"Loading the slate…"}):0===t.length?(0,b.jsx)("div",{className:"empty-state",children:"No esports matches in the window — the fixtures sync runs every 30 min."}):(0,b.jsxs)(b.Fragment,{children:[g("🔴 Live",u),g("Upcoming",h),g("Recently finished",p.slice(-20).reverse())]})]})})}function n0(){let[e,t]=(0,_.useState)(null),[a,s]=(0,_.useState)(!1),[r,n]=(0,_.useState)(null),[l,i]=(0,_.useState)([]),[o,c]=(0,_.useState)(null),[d,u]=(0,_.useState)(!0),[h,p]=(0,_.useState)(null),[m,x]=(0,_.useState)(()=>Date.now()),{openTab:g}=(0,ez.useMarketTabs)(),f=(e=!1)=>(0,er.authGetJson)("/api/radar/uma-lock").then(e=>{e.ok?(t(e.data),s(!1)):s(!0)}).catch(()=>{e||s(!0)});(0,_.useEffect)(()=>{f();let e=setInterval(()=>f(!0),5e3);return()=>clearInterval(e)},[]),(0,_.useEffect)(()=>{let e=setInterval(()=>x(Date.now()),1e3);return()=>clearInterval(e)},[]),(0,_.useEffect)(()=>{if(!h)return;let e=setTimeout(()=>p(null),2500);return()=>clearTimeout(e)},[h]),(0,_.useEffect)(()=>{(0,er.authGetJson)("/api/wallets").then(e=>i((e.data?.wallets||e.wallets||e.data||[]).map(e=>({id:String(e.id),label:e.label||e.name,address:e.address||e.proxy_address})))).catch(()=>{})},[]);let v=async(e,t,a="saved ✓")=>{c(e);try{await t(),await f(!0),p({msg:a,ok:!0})}catch{p({msg:"failed — try again",ok:!1})}finally{c(null)}},y=e=>(0,er.authPostJson)("/api/radar/uma-lock",e),j=e=>{if(!e)return"—";let t=Math.max(0,Math.round((m-e)/1e3));return t<60?`${t}s ago`:t<3600?`${Math.round(t/60)}m ago`:`${Math.round(t/3600)}h ago`},w=(e,t)=>g({kind:"radar",marketId:e,title:t.slice(0,40)});if(!e)return(0,b.jsx)("div",{className:"wc-bot",children:(0,b.jsxs)("div",{className:"wc-bot-loading",children:[(0,b.jsx)("span",{className:"wc-bot-spin"})," ",a?"couldn’t reach the bonder — retrying…":"loading UMA bonder…"]})});let N={...e.cfg,...r||{}},k=e.state||{},S=e.heartbeat||{},$=!S.last_run_ms||m-S.last_run_ms>15e4,C=k.closed||[],M=C.filter(e=>e.won).length,E=k.realized||0,A=(k.log||[]).slice().reverse().slice(0,40);return(0,b.jsxs)("div",{className:"wc-bot",children:[(0,b.jsxs)("div",{className:"wc-bot-head",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("b",{children:"🔓 UMA-Lock Auto-Bonder"})," ",(0,b.jsxs)("span",{className:"wc-power-sub",children:["— watches every oracle proposal; when a dispute window DIES on-chain it waits ",Math.round((N.delay_s||300)/60)," min, then buys the leftover cents on the proposed side. A disputed market is never touched. Free money, mechanically collected."]})]}),(0,b.jsxs)("span",{className:"wc-power-sub",children:["registry ",S.registry??0," proposals · ",S.matched??0," matched to markets"]})]}),(0,b.jsxs)("div",{className:"wc-bot-worker",children:[(0,b.jsx)("span",{className:`wc-bot-dot${$?" stale":""}`}),(0,b.jsxs)("span",{children:["worker ",!1===S.ok?"⚠ error":$?"idle":"live"," · last scan ",j(S.last_run_ms)]}),(0,b.jsxs)("span",{className:"wc-power-sub",children:[" · ",(k.watch||[]).length," proposals on watch · ",(k.open||[]).length," tickets held"]}),(0,b.jsx)("span",{className:"wc-bot-spacer"}),(0,b.jsx)("span",{className:"wc-power-sub wc-bot-refresh",children:"● auto-refresh 5s"})]}),N.enabled&&(0,b.jsxs)("div",{className:`wc-bot-pill${E<0?" neg":""}`,children:["● ",N.mode.toUpperCase()," running · paid ",M,"/",C.length," · realized ",(0,b.jsxs)("b",{className:E>=0?"radar-up":"radar-down",children:[E>=0?"+":"","$",E.toFixed(0)]})]}),(0,b.jsxs)("div",{className:`wc-bot-acct${N.enabled?" on":""}`,children:[(0,b.jsxs)("div",{className:"wc-bot-acct-head",children:[(0,b.jsx)("span",{className:`wc-bot-mode ${N.mode}`,children:"live"===N.mode?"● LIVE":"PAPER"}),(0,b.jsx)("b",{children:"UMA Bonder"}),(0,b.jsx)("button",{className:`wc-bot-sw${N.enabled?" on":""}`,disabled:"tog"===o,onClick:()=>v("tog",()=>y({enabled:!e.cfg.enabled}),e.cfg.enabled?"turned OFF":"turned ON ✓"),children:"tog"===o?"···":N.enabled?"ON":"OFF"}),(0,b.jsx)("button",{className:`wc-bot-log${d?" on":""}`,onClick:()=>u(!d),children:"📋 log"}),(0,b.jsx)("span",{className:"wc-bot-spacer"}),(0,b.jsx)("span",{className:"wc-power-sub",children:"record "}),(0,b.jsxs)("b",{className:E>=0?"radar-up":"radar-down",children:[E>=0?"+":"","$",E.toFixed(0)]}),(0,b.jsxs)("span",{className:"wc-power-sub",children:[" · ",M,"/",C.length," paid",C.length-M>0?(0,b.jsxs)("b",{className:"radar-down",children:[" · ",C.length-M," REVERSED"]}):null]})]}),(0,b.jsxs)("div",{className:"wc-bot-row",children:[(0,b.jsxs)("div",{className:"wc-bot-modesel",children:[(0,b.jsx)("button",{className:"paper"===N.mode?"on":"",disabled:"mode"===o,onClick:()=>v("mode",()=>y({mode:"paper"}),"mode → paper"),children:"Paper"}),(0,b.jsx)("button",{className:"live"===N.mode?"on":"",disabled:"mode"===o||!N.account_id,title:N.account_id?"":"bind a wallet first",onClick:()=>v("mode",()=>y({mode:"live"}),"mode → LIVE"),children:"Live"})]}),(0,b.jsxs)("label",{className:"wc-bot-field",children:[(0,b.jsx)("span",{children:"wallet (for live)"}),(0,b.jsxs)("select",{value:N.account_id||"",onChange:e=>v("wallet",()=>y({account_id:e.target.value||null}),"wallet bound ✓"),children:[(0,b.jsx)("option",{value:"",children:"— none —"}),l.map(e=>(0,b.jsx)("option",{value:e.id,children:e.label||e.address?.slice(0,10)||e.id.slice(0,8)},e.id))]})]})]}),(0,b.jsxs)("div",{className:"wc-bot-adv",children:[[["per_market_usd","$ / ticket",5],["delay_s","buy after (sec)",30],["max_price","max price (0-1)",.001],["min_residual_c","min residual ¢",.1],["max_open","max open tickets",1]].map(([e,t,a])=>(0,b.jsxs)("label",{className:"wc-bot-field",children:[(0,b.jsx)("span",{children:t}),(0,b.jsx)("input",{type:"number",step:a,value:N[e]??0,onChange:t=>n(a=>({...a||{},[e]:+t.target.value}))})]},e)),null!==r&&(0,b.jsx)("button",{className:"wc-bot-apply",disabled:"cfg"===o,onClick:()=>v("cfg",async()=>{await y(r),n(null)},"config saved ✓"),children:"cfg"===o?"saving…":"Save config"})]}),(k.watch||[]).length>0&&(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)("div",{className:"wc-bot-pos-label",children:"proposals on wat
10ch"}),(0,b.jsxs)("table",{className:"wc-bot-pos",children:[(0,b.jsx)("thead",{children:(0,b.jsxs)("tr",{children:[(0,b.jsx)("th",{children:"state"}),(0,b.jsx)("th",{children:"market"})]})}),(0,b.jsx)("tbody",{children:(k.watch||[]).slice(0,10).map(e=>(0,b.jsxs)("tr",{style:{cursor:"pointer"},onClick:()=>w(e.market_id,e.question),children:[(0,b.jsx)("td",{className:e.disputed?"radar-down":e.state.includes("DEAD")?"radar-up":"",style:{whiteSpace:"nowrap",fontWeight:600},children:e.state}),(0,b.jsx)("td",{children:e.question})]},e.market_id))})]})]}),(k.open||[]).length>0&&(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)("div",{className:"wc-bot-pos-label",children:"open tickets"}),(0,b.jsxs)("table",{className:"wc-bot-pos",children:[(0,b.jsx)("thead",{children:(0,b.jsxs)("tr",{children:[(0,b.jsx)("th",{children:"mode"}),(0,b.jsx)("th",{children:"side"}),(0,b.jsx)("th",{children:"shares"}),(0,b.jsx)("th",{children:"entry"}),(0,b.jsx)("th",{children:"residual"}),(0,b.jsx)("th",{children:"market"}),(0,b.jsx)("th",{children:"age"})]})}),(0,b.jsx)("tbody",{children:(k.open||[]).map(e=>(0,b.jsxs)("tr",{style:{cursor:"pointer"},onClick:()=>w(e.market_id,e.question),children:[(0,b.jsx)("td",{children:e.mode}),(0,b.jsx)("td",{className:"radar-up",children:e.side.toUpperCase()}),(0,b.jsx)("td",{children:Math.round(e.sh)}),(0,b.jsxs)("td",{children:[(100*e.entry).toFixed(1),"¢"]}),(0,b.jsxs)("td",{className:"radar-up",children:["+",((1-e.entry)*100).toFixed(1),"¢"]}),(0,b.jsx)("td",{children:e.question}),(0,b.jsx)("td",{className:"wc-power-sub",children:j(e.ts)})]},e.market_id))})]})]})]}),d&&(0,b.jsxs)("div",{className:"wc-bot-feed",children:[(0,b.jsxs)("div",{className:"wc-bot-feed-head",children:["📋 live decisions ",(0,b.jsx)("span",{className:"wc-power-sub",children:"— newest first"})]}),0===A.length?(0,b.jsx)("div",{className:"wc-power-sub wc-bot-feed-empty",children:N.enabled?"scanning the oracle… the feed fills with proposals, dying windows, buys, skips and payouts.":"the bonder is OFF — turn it ON to see it work."}):A.map((e,t)=>(0,b.jsxs)("div",{className:`wc-bot-logrow ${"buy"===e.kind||"grade"===e.kind?"filled":"error"===e.kind?"failed":"skipped"}`,children:[(0,b.jsx)("span",{className:"wc-bot-feed-time",children:j(e.ts)}),(0,b.jsx)("span",{className:"buy"===e.kind||"grade"===e.kind?"radar-up":"error"===e.kind?"radar-down":"wc-power-sub",style:{minWidth:44,fontWeight:700},children:e.kind}),(0,b.jsx)("span",{children:e.msg})]},t))]}),h&&(0,b.jsx)("div",{className:`wc-bot-flash${h.ok?"":" err"}`,children:h.msg})]})}function n1({title:e,sub:t,children:a}){return(0,b.jsxs)("div",{style:{marginBottom:26},children:[(0,b.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10,margin:"0 0 10px"},children:[(0,b.jsx)("h2",{style:{fontSize:16,margin:0},children:e}),(0,b.jsx)("span",{className:"wc-power-sub",children:t})]}),a]})}function n2(){return(0,b.jsxs)("div",{style:{padding:"16px 18px",maxWidth:1400,height:"100%",overflowY:"auto"},children:[(0,b.jsxs)("div",{style:{marginBottom:18},children:[(0,b.jsx)("h1",{style:{fontSize:20,margin:0},children:"🤖 Auto Traders"}),(0,b.jsx)("div",{className:"wc-power-sub",children:"Soccer execution is the active production priority. Non-soccer and legacy agent cockpits are hidden while their backend services are paused."})]}),(0,b.jsx)(n1,{title:"⚽ Soccer agents",sub:"UnderPilot, wallet-bound US391 and GoalPilot live canaries, plus GoalPilot paper controls",children:(0,b.jsx)(rH,{})})]})}let n5=["total","live","daily","weekly","monthly"],n4={total:"all",live:"live",daily:"1d",weekly:"7d",monthly:"30d"},n3=(e,t=0)=>`${(e||0)>=0?"+":"−"}$${Math.abs(e||0).toFixed(t)}`,n6=(e,t=0)=>`$${Math.abs(e||0).toFixed(t)}`;function n8(e){return e?[...e.backtest||[],...e.live||[]].sort((e,t)=>e[0]-t[0]):[]}function n9({pts:e}){let[t,a]=(0,_.useState)(null),s=(0,_.useRef)(null),r=(0,_.useCallback)(t=>{let r=s.current?.getBoundingClientRect();!r||r.width<2||e.length<2||a(Math.round(Math.min(1,Math.max(0,(t.clientX-r.left)/r.width))*(e.length-1)))},[e.length]);if(e.length<2)return(0,b.jsx)("div",{className:"wc-power-sub",style:{height:56,display:"flex",alignItems:"center"},children:"not enough settles yet"});let n=Math.min(0,...e.map(e=>e.v)),l=Math.max(0,...e.map(e=>e.v)),i=Math.max(1e-6,l-n),o=t=>t/(e.length-1)*100,c=e=>40-(e-n)/i*36-2,d=e.map((e,t)=>`${o(t).toFixed(2)},${c(e.v).toFixed(2)}`).join(" "),u=e[e.length-1].v>=0,h=null!=t?e[t]:null;return(0,b.jsxs)("div",{ref:s,style:{position:"relative"},onMouseMove:r,onMouseLeave:()=>a(null),children:[(0,b.jsxs)("svg",{viewBox:"0 0 100 42",preserveAspectRatio:"none",style:{width:"100%",height:56,display:"block"},children:[n<0&&l>0&&(0,b.jsx)("line",{x1:"0",x2:"100",y1:c(0),y2:c(0),stroke:"currentColor",opacity:"0.15",strokeWidth:"0.5"}),(0,b.jsx)("polyline",{points:d,fill:"none",stroke:u?"#31c48d":"#f05252",strokeWidth:"1.4",vectorEffect:"non-scaling-stroke"}),h&&(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)("line",{x1:o(t),x2:o(t),y1:"0",y2:"42",stroke:"currentColor",opacity:"0.25",strokeWidth:"0.5",vectorEffect:"non-scaling-stroke"}),(0,b.jsx)("circle",{cx:o(t),cy:c(h.v),r:"1.8",fill:h.v>=0?"#31c48d":"#f05252"})]})]}),h&&(0,b.jsxs)("div",{style:{position:"absolute",top:-6,left:`${Math.min(78,Math.max(0,o(t)))}%`,transform:"translateY(-100%)",background:"rgba(20,24,32,0.95)",border:"1px solid rgba(255,255,255,0.15)",borderRadius:6,padding:"4px 8px",fontSize:11,whiteSpace:"nowrap",pointerEvents:"none",zIndex:5},children:[(0,b.jsx)("b",{style:{color:h.v>=0?"#31c48d":"#f05252"},children:n3(h.v,2)}),(0,b.jsxs)("span",{style:{opacity:.7}
10,children:[" · trade #",t+1," · ",new Date(h.t).toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})]})]})]})}function n7({rows:e}){let t=(0,_.useMemo)(()=>{let t=new Map;for(let[a,s]of e){let e=new Date(a).toISOString().slice(0,7),r=t.get(e)||{pnl:0,n:0};r.pnl+=s,r.n+=1,t.set(e,r)}return[...t.entries()].sort((e,t)=>t[0].localeCompare(e[0]))},[e]);if(!t.length)return null;let a=Math.max(...t.map(([,e])=>Math.abs(e.pnl)),1);return(0,b.jsxs)("div",{style:{marginTop:8,borderTop:"1px solid rgba(255,255,255,0.08)",paddingTop:7},children:[(0,b.jsx)("div",{className:"wc-power-sub",style:{fontSize:10,marginBottom:4},children:"month by month"}),(0,b.jsx)("div",{style:{maxHeight:190,overflowY:"auto",fontVariantNumeric:"tabular-nums"},children:t.map(([e,t])=>(0,b.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:11,padding:"2px 0"},children:[(0,b.jsx)("span",{style:{width:52,opacity:.75},children:e}),(0,b.jsx)("span",{style:{flex:1,height:6,background:"rgba(255,255,255,0.05)",borderRadius:2,position:"relative"},children:(0,b.jsx)("span",{style:{position:"absolute",left:0,top:0,height:6,borderRadius:2,width:`${Math.max(2,Math.abs(t.pnl)/a*100)}%`,background:t.pnl>=0?"#31c48d":"#f05252",opacity:.75}})}),(0,b.jsx)("b",{className:t.pnl>=0?"radar-up":"radar-down",style:{width:66,textAlign:"right"},children:n3(t.pnl)}),(0,b.jsx)("span",{className:"wc-power-sub",style:{width:34,textAlign:"right"},children:t.n})]},e))})]})}function le({state:e,series:t,win:a,setWin:s,merged:r}){let n,l,i,o,[c,d]=(0,_.useState)(!1),u=(0,_.useMemo)(()=>"live"===a?[...t&&t.live||[]].sort((e,t)=>e[0]-t[0]):n8(t),[t,a]),h=(0,_.useMemo)(()=>(function(e,t){let a="daily"===t?Date.now()-864e5:"weekly"===t?Date.now()-7*864e5:"monthly"===t?Date.now()-30*864e5:0,s=0,r=[];for(let[t,n]of e)a&&t<a||(s+=n,r.push({t,v:Math.round(100*s)/100}));return r})(u,"live"===a?"total":a),[u,a]),p=(0,_.useMemo)(()=>n8(t).reduce((e,[,t])=>e+t,0),[t]),m=h.length?h[h.length-1].v:0,x=e.service?.config,g=e.live||{},f=t?.label||`${(e.asset||"").toUpperCase()} ${e.window_min||15}m`,v=u.length,y=(0,_.useMemo)(()=>u.filter(([,e])=>e>0).length,[u]),j=v?100*y/v:null,w=e.service?.live_enabled&&!e.service?.stale,N=(0,_.useMemo)(()=>(e.signals||[]).filter(e=>"filled"===e.execution),[e.signals]),k=(0,_.useMemo)(()=>(e.signals||[]).filter(e=>"filled"!==e.execution),[e.signals]),S="box"===e.asset;return(0,b.jsxs)("div",{className:`wc-bot-acct${w||r?" on":""}`,style:c||r?{gridColumn:"1 / -1"}:void 0,children:[(0,b.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:8},children:[(0,b.jsx)("span",{className:"wc-bot-mode live",children:"LIVE"}),(0,b.jsx)("b",{style:{flex:1,fontSize:13,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:f}),!w&&!r&&(0,b.jsx)("span",{className:"wc-power-sub",children:"idle"}),!r&&(0,b.jsx)("button",{className:`wc-bot-log${c?" on":""}`,onClick:()=>d(!c),children:c?"close ×":"open"})]}),(0,b.jsxs)("div",{style:{display:"flex",gap:16,margin:"6px 0 4px",alignItems:"baseline"},children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{className:"wc-power-sub",children:"total "}),(0,b.jsx)("b",{className:p>=0?"radar-up":"radar-down",children:n3(p)})]}),"total"===a?(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{className:"wc-power-sub",children:"today "}),(0,b.jsx)("b",{className:Number(g.today_pnl_usd||0)>=0?"radar-up":"radar-down",children:n3(g.today_pnl_usd)})]}):(0,b.jsxs)("div",{children:[(0,b.jsxs)("span",{className:"wc-power-sub",children:[n4[a]," "]}),(0,b.jsx)("b",{className:m>=0?"radar-up":"radar-down",children:n3(m)}),(0,b.jsxs)("span",{className:"wc-power-sub",style:{fontSize:10},children:[" · ",h.length," trade",1===h.length?"":"s"]})]}),Number(g.open||0)>0&&(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{className:"wc-power-sub",children:"open "}),(0,b.jsx)("b",{children:g.open})]}),(0,b.jsx)("span",{style:{flex:1}}),n5.map(e=>(0,b.jsx)("button",{style:{fontSize:10,padding:"1px 5px",opacity:a===e?1:.45,background:"none",border:"1px solid rgba(255,255,255,0.18)",borderRadius:4,cursor:"pointer",color:"inherit"},onClick:()=>s(e),children:n4[e]},e))]}),(0,b.jsx)(n9,{pts:h}),(0,b.jsxs)("div",{style:{display:"flex",gap:14,flexWrap:"wrap",fontSize:11,marginTop:2},children:[(0,b.jsxs)("span",{className:"wc-power-sub",children:[v.toLocaleStr
10ing()," trades"]}),null!=g.signals_evaluated&&(0,b.jsxs)("span",{className:"wc-power-sub",children:[Number(g.signals_evaluated).toLocaleString()," windows evaluated"]}),null!=j&&(0,b.jsxs)("span",{className:"wc-power-sub",children:[j.toFixed(1),"% won"]}),x&&(0,b.jsxs)("span",{className:"wc-power-sub",children:["cap ",Math.round(100*Number(x.price_cap||0)),"¢"]}),!r&&e.service?.health?.balance_usd!=null&&(0,b.jsxs)("span",{className:"wc-power-sub",children:["balance ",(0,b.jsx)("b",{children:n6(e.service.health.balance_usd)})]})]}),e.service?.reconciliation&&(l=(n=e.service.reconciliation).checked_at_ms?Math.max(0,Math.round((Date.now()-n.checked_at_ms)/6e4)):null,i="ok"===n.status?"#31c48d":"mismatch"===n.status?"#f05252":"rgba(255,255,255,0.5)",o="ok"===n.status?`✓ every trade matches Polymarket & Kalshi records \xb7 ${n.polymarket_markets??"?"} + ${n.kalshi_markets??"?"} markets`:"mismatch"===n.status?`⚠ ${n.mismatch_count} market${1===n.mismatch_count?"":"s"} don't match the venues' records`:"stale"===n.status?"reconciliation check is late":"error"===n.status?"reconciliation check failed":"reconciliation not available",(0,b.jsxs)("div",{style:{fontSize:11,marginTop:4,color:i},title:JSON.stringify("ok"===n.status?n.known_exceptions:n.mismatches),children:[o,null!=l?(0,b.jsxs)("span",{className:"wc-power-sub",children:[" · checked ",l," min ago"]}):null]})),(0,b.jsx)(n7,{rows:u}),c&&!r&&(0,b.jsxs)("div",{style:{marginTop:8,borderTop:"1px solid rgba(255,255,255,0.08)",paddingTop:8},children:[(0,b.jsx)("div",{className:"wc-power-sub",style:{fontSize:10,marginBottom:4},children:S?`all positions \xb7 ${N.length.toLocaleString()} \xb7 newest first`:"latest entries"}),0===N.length&&(0,b.jsx)("div",{className:"wc-power-sub",children:k.length?"No entry yet.":"No window evaluated yet."}),(0,b.jsx)("div",{style:S?{maxHeight:460,overflowY:"auto",paddingRight:4}:void 0,children:N.map(e=>{let t,a,s;return(0,b.jsxs)("div",{style:{display:"flex",gap:10,alignItems:"baseline",padding:"3px 0",fontSize:11,borderBottom:"1px solid rgba(255,255,255,0.04)"},children:[S&&(0,b.jsx)("span",{className:"wc-power-sub",style:{minWidth:92,fontVariantNumeric:"tabular-nums"},children:(t=e.evaluated_at_ms)?new Date(t).toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"}):""}),(0,b.jsx)("b",{style:{minWidth:S?300:185},children:e.name}),null!=e.z?(0,b.jsxs)("span",{className:"wc-power-sub",children:["min ",e.minute," · z ",e.z.toFixed(2)]}):(0,b.jsxs)("span",{className:"wc-power-sub",children:["min ",e.minute," · ",Number(e.pairs||0).toFixed(0)," pairs",null!=e.pair_cost?` @ ${(100*e.pair_cost).toFixed(1)}\xa2`:"",e.poly_outcome?` \xb7 Poly ${e.poly_outcome} ${Number(e.poly_shares||0).toFixed(2)}${null!=e.poly_avg?` @ ${(100*e.poly_avg).toFixed(1)}\xa2`:""}`:"",e.kalshi_outcome?` \xb7 Kalshi ${"yes"===e.kalshi_outcome?"Up":"Down"} ${Number(e.kalshi_count||0).toFixed(0)}${null!=e.kalshi_avg?` @ ${(100*e.kalshi_avg).toFixed(1)}\xa2`:""}`:"",Number(e.unhedged_usd||0)>=1?` \xb7 ${n6(e.unhedged_usd)} unhedged`:"",Number(e.backstop_shares||0)>=1?` \xb7 backstop ${Number(e.backstop_shares).toFixed(0)}`:e.rescued?" · rescued":"",e.venues_split?" · venues split":""]}),(0,b.jsx)("span",{style:{flex:1}}),null!=e.z&&(0,b.jsx)("span",{children:(e=>{if(null==e.close_k)return"—";let t=Number(e.close_k).toLocaleString(void 0,{maximumFractionDigits:2}),a=null==e.move_bps?"":` (${e.move_bps>=0?"+":""}${Number(e.move_bps).toFixed(0)} bps)`;return`${t}${a}`})(e)}),(0,b.jsx)("b",{style:{minWidth:56,textAlign:"right"},children:n6(e.cost_usd)}),null!=e.won&&(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)("b",{className:e.won?"radar-up":"radar-down",style:{minWidth:60,textAlign:"right"},children:n3(e.pnl,2)}),(0,b.jsx)("b",{className:e.won?"radar-up":"radar-down",style:{minWidth:52,textAlign:"right",opacity:.8},children:(a=e.pnl,(s=e.cost_usd)?`${(a||0)>=0?"+":"−"}${Math.abs(100*(a||0)/s).toFixed(1)}%`:"—")})]}),null==e.won&&S&&(0,b.jsx)("span",{className:"wc-power-sub",style:{minWidth:60,textAlign:"right"},children:"open"})]},e.id)})}),k.length>0&&(0,b.jsxs)("div",{className:"wc-power-sub",style:{fontSize:10,marginTop:6},children:[k.length," more window",1===k.length?"":"s"," shown here took no position — ",(function(e){let t=new Map;for(let a of e){let e="error"===a.execution?"order error":"below_z"
10===a.skip?"no signal":(a.skip||"not entered").replace(/_/g," ");t.set(e,(t.get(e)||0)+1)}return[...t.entries()].sort((e,t)=>t[1]-e[1])})(k).map(([e,t])=>`${t} ${e}`).join(" · ")]})]})]})}function lt(){let[e,t]=(0,_.useState)({}),[a,s]=(0,_.useState)({}),[r,n]=(0,_.useState)("total"),[l,i]=(0,_.useState)(!1),[o,c]=(0,_.useState)(!1),[d,u]=(0,_.useState)(null),[h,p]=(0,_.useState)(!1);(0,_.useEffect)(()=>{let e=!1,a=async()=>{try{let[a,r]=await Promise.all([(0,er.authGetJson)("/api/worldcup/autotrade/status"),(0,er.authGetJson)(`/api/worldcup/autotrade/pm15m-series${o?"?sizing=auto20":""}`)]);if(e)return;t(a?.data?.pm15m_agent||{}),s(r?.data||{}),u(o&&r?.meta||null),p(!1)}catch{e||p(!0)}};a();let r=setInterval(()=>void a(),1e4);return()=>{e=!0,clearInterval(r)}},[o]);let m=Object.values(e).sort((e,t)=>(t.window_min||0)-(e.window_min||0)||(e.asset||"").localeCompare(t.asset||"")),x=m.reduce((e,t)=>e+n8(a[t.account_id]).reduce((e,[,t])=>e+t,0),0),g=m.reduce((e,t)=>e+Number(t.live?.today_pnl_usd||0),0),f=m.reduce((e,t)=>e+Number(t.live?.open||0),0),v=m.reduce((e,t)=>e+n8(a[t.account_id]).length,0),y=(0,_.useMemo)(()=>({label:`All strategies combined \xb7 ${m.length} bots`,window_min:0,backtest:m.flatMap(e=>a[e.account_id]?.backtest||[]).sort((e,t)=>e[0]-t[0]),live:m.flatMap(e=>a[e.account_id]?.live||[]).sort((e,t)=>e[0]-t[0])}),[m,a]),j=(0,_.useMemo)(()=>({account_id:"merged",asset:"",window_min:0,service:{live_enabled:!0,stale:!1},live:{today_pnl_usd:m.reduce((e,t)=>e+Number(t.live?.today_pnl_usd||0),0),open:m.reduce((e,t)=>e+Number(t.live?.open||0),0)},signals:[]}),[m]);return(0,b.jsxs)("div",{style:{padding:"16px 18px",maxWidth:1400,height:"100%",overflowY:"auto"},children:[(0,b.jsx)("div",{style:{display:"flex",alignItems:"baseline",gap:12,marginBottom:6},children:(0,b.jsx)("h1",{style:{fontSize:20,margin:0},children:"Bots"})}),v>0&&(0,b.jsxs)("div",{className:`wc-bot-pill${x<0?" neg":""}`,style:{marginBottom:10},children:["● ",m.length," BOTS · ",v.toLocaleString()," trades · total"," ",(0,b.jsx)("b",{className:x>=0?"radar-up":"radar-down",children:n3(x)})," ","· today ",(0,b.jsx)("b",{className:g>=0?"radar-up":"radar-down",children:n3(g)}),f>0?(0,b.jsxs)(b.Fragment,{children:[" · ",f," open"]}):null]}),h&&(0,b.jsx)("div",{className:"empty-state",children:"Cockpit API unreachable."}),!h&&!m.length&&(0,b.jsx)("div",{className:"empty-state",children:"Loading bots…"}),m.length>1&&(0,b.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:6,fontSize:11,cursor:"pointer",margin:"0 0 8px"},children:[(0,b.jsx)("input",{type:"checkbox",checked:l,onChange:e=>i(e.target.checked)}),"merged view — every strategy as one book"]}),m.length>0&&(0,b.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:6,fontSize:11,cursor:"pointer",margin:"0 0 8px"},children:[(0,b.jsx)("input",{type:"checkbox",checked:o,onChange:e=>c(e.target.checked)}),"20% sizing — replay the backtest under the live sizing rules"]}),o&&d&&(0,b.jsxs)("div",{className:"wc-power-sub",style:{fontSize:11,margin:"-2px 0 10px",lineHeight:1.5},children:["Backtest as one account from ",n6(d.start_capital),": ends at ",(0,b.jsx)("b",{children:n6(d.end_capital)}),", worst drawdown ",(0,b.jsxs)("b",{children:[d.max_drawdown_pct.toFixed(1),"%"]}),d.brake_hit_ms?(0,b.jsxs)(b.Fragment,{children:[" · ",(0,b.jsxs)("b",{className:"radar-down",children:["brake hit ",new Date(d.brake_hit_ms).toLocaleDateString()]})]}):(0,b.jsx)(b.Fragment,{children:" · brake never hit"})," ","· ",d.trades.toLocaleString()," trades. ",d.rule,". Live curves are unchanged."]}),l?(0,b.jsx)(le,{state:j,series:y,win:r,setWin:n,merged:!0}):(0,b.jsx)("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(300px, 1fr))",gap:10,alignItems:"start"},children:m.map(e=>(0,b.jsx)(le,{state:e,series:a[e.account_id],win:r,setWin:n},e.account_id))})]})}let la=e=>e.takes?(0,b.jsxs)(b.Fragment,{children:[Number(e.entry||0).toFixed(3)," ",(0,b.jsx)("span",{className:"wc-power-sub",children:"·"})," $",Number(e.size||0).toFixed(0)]}):(0,b.jsx)("span",{className:"wc-power-sub",children:e.skip?String(e.skip).replace(/_/g," ").slice(0,18):"over cap"});function ls({p:e}){let t=e.summary;return(0,b.jsxs)("div",{style:{marginTop:8,borderTop:"1px solid rgba(255,255,255,0.08)",paddingTop:8},children:[(0,b.jsxs)("div",{style:{display:"flex",gap:14,flexWrap:"wrap",fontSize:11,marginBottom:6},children:[(0,b.jsxs)("span",{className:"wc-power-sub",children:[t.windows," windows"]}),(0,b.jsxs)("span",{className:"wc-power-sub",children:["traded ",(0,b.jsx)("b",{children:t.both})]}),t.missed>0&&(0,b.jsxs)("span",{className:"wc-power-sub",children:["missed ",(0,b.jsx)("b",{className:"radar-down",children:t.missed})," ","(",(0,b.jsx)("b",{className:"radar-down",children:lr(-t.missed_pnl_usd,2)}),")"]}),t.unknown>0&&(0,b.jsxs)("span",{className:"wc-power-sub",children:[t.unknown," pre-date the config record"]}),(0,b.jsx)("span",{style:{flex:1}}),(0,b.jsxs)("span",{className:"wc-power-sub",children:["size ",lr(t.size_gap_usd)," · total vs rule"," ",(0,b.jsx)("b",{className:t.pnl_gap_usd>=0?"radar-up":"radar-down",children:lr(t.pnl_gap_usd,2)})]})]}),(0,b.jsx)("div",{style:{maxHeight:340,overflowY:"auto",fontVariantNumeric:"tabular-nums"},children:(0,b.jsxs)("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:11},children:[(0,b.jsx)("thead",{children:(0,b.jsxs)("tr",{style:{textAlign:"left",opacity:.6},children:[(0,b.jsx)("th",{style:{fontWeight:400},children:"window"}),(0,b.jsx)("th",{style:{fontWeight:400},children:"side"}),(0,b.jsx)("th",{style:{fontWeight:400,color:ln},children:"rule would buy"}),(0,b.jsx)("th",{style:{fontWeight:400,color:ll},children:"we bought"}),(0,b.jsx)("th",{style:{fontWeight:400,textAlign:"right"},children:"P&L diff"})]})}),(0,b.jsx)("tbody",{children:e.rows.map(e=>{let t=e.model.takes&&e.actual.takes,a=null==e.model.pnl?null:t?null==e.actual.pnl?null:e.actual.pnl-e.model.pnl:e.model.takes?-e.model.pnl:null;return(0,b.jsxs)("tr",{style:{borderTop:"1px solid rgba(255,255,255,0.04)",background:t?void 0:"rgba(240,82,82,0.06)"},children:[(0,b.jsx)("td",{style:{padding:"2px 0",whiteSpace:"nowrap"},children:e.name.replace(/^[A-Z]+ \d+m · /,"")}),(0,b.jsx)("td",{children:e.side}),(0,b.jsx)("td",{style:{color:ln},children:la(e.model)}
10),(0,b.jsxs)("td",{style:{color:ll},children:[la(e.actual),!1===e.config_known&&(0,b.jsx)("span",{className:"wc-power-sub",children:" · config not recorded"})]}),(0,b.jsxs)("td",{style:{textAlign:"right"},children:[null==a?(0,b.jsx)("span",{className:"wc-power-sub",children:"—"}):(0,b.jsx)("b",{className:a>=0?"radar-up":"radar-down",children:lr(a,2)}),e.estimated&&(0,b.jsx)("span",{className:"wc-power-sub",title:"result read off the next window's open",children:"*"})]})]},e.id)})})]})}),(0,b.jsx)("div",{className:"wc-power-sub",style:{fontSize:10,marginTop:5},children:"The rule runs the config that was live at each window, not today's, so a sizing change is not counted as drift. Its price is the book's ask at signal time, which matched the study's own estimate to a median of 0.000 across 215 signals. A window the rule wanted and we skipped is charged as the profit it would have made. * marks a result read off the next window's open, which agreed with the venue on 97 of 98 settled fills."})]})}let lr=(e,t=0)=>`${(e||0)>=0?"+":"−"}$${Math.abs(e||0).toFixed(t)}`,ln="#7aa2f7",ll="#31c48d";function li(e){if(!e?.length)return[];let t=[...e].sort((e,t)=>e[0]-t[0]),a=0;return t.map(([e,s],r)=>(a+=s,{x:r/Math.max(1,t.length-1),y:a/(r+1),cum:a,n:r+1,t:e}))}function lo(e){let t=new Map;for(let[a,s]of e||[]){let e=new Date(a).toISOString().slice(0,7),r=t.get(e)||{pnl:0,n:0};r.pnl+=s,r.n+=1,t.set(e,r)}return t}function lc({series:e,showBt:t,showLv:a}){let s=(0,_.useMemo)(()=>lo(e.backtest),[e.backtest]),r=(0,_.useMemo)(()=>lo(e.live),[e.live]),n=(0,_.useMemo)(()=>{let e=new Set;if(t)for(let t of s.keys())e.add(t);if(a)for(let t of r.keys())e.add(t);return[...e].sort().reverse()},[s,r,t,a]);if(!n.length)return null;let l=e=>e?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)("b",{className:e.pnl>=0?"radar-up":"radar-down",children:lr(e.pnl)})," ",(0,b.jsxs)("span",{className:"wc-power-sub",children:["(",e.n,")"]})]}):(0,b.jsx)("span",{className:"wc-power-sub",children:"—"});return(0,b.jsxs)("div",{style:{marginTop:10,borderTop:"1px solid rgba(255,255,255,0.08)",paddingTop:8},children:[(0,b.jsx)("div",{className:"wc-power-sub",style:{fontSize:10,marginBottom:4},children:"month by month · realised, trade count in brackets"}),(0,b.jsx)("div",{style:{maxHeight:210,overflowY:"auto"},children:(0,b.jsxs)("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:11,fontVariantNumeric:"tabular-nums"},children:[(0,b.jsx)("thead",{children:(0,b.jsxs)("tr",{style:{textAlign:"left",opacity:.6},children:[(0,b.jsx)("th",{style:{fontWeight:400,padding:"2px 0"},children:"month"}),t&&(0,b.jsx)("th",{style:{fontWeight:400,textAlign:"right",color:ln},children:"modelled"}),a&&(0,b.jsx)("th",{style:{fontWeight:400,textAlign:"right",color:ll},children:"live"})]})}),(0,b.jsx)("tbody",{children:n.map(e=>(0,b.jsxs)("tr",{style:{borderTop:"1px solid rgba(255,255,255,0.04)"},children:[(0,b.jsx)("td",{style:{padding:"2px 0"},children:e}),t&&(0,b.jsx)("td",{style:{textAlign:"right"},children:l(s.get(e))}),a&&(0,b.jsx)("td",{style:{textAlign:"right"},children:l(r.get(e))})]},e))})]})})]})}function ld({series:e,showBt:t,showLv:a}){let[s,r]=(0,_.useState)(null),n=(0,_.useRef)(null),l=(0,_.useMemo)(()=>li(e.backtest),[e.backtest]),i=(0,_.useMemo)(()=>li(e.live),[e.live]),o=[...t?l:[],...a?i:[]];if(!o.length)return(0,b.jsx)("div",{className:"wc-power-sub",style:{height:120,display:"flex",alignItems:"center"},children:"nothing to plot"});let c=Math.min(0,...o.map(e=>e.y)),d=Math.max(0,...o.map(e=>e.y)),u=Math.max(1e-6,d-c),h=e=>56-(e-c)/u*50-3,p=e=>e.map(e=>`${(100*e.x).toFixed(2)},${h(e.y).toFixed(2)}`).join(" "),m=e=>null!=s&&e.length?e[Math.round(s*(e.length-1))]:null,x=t?m(l):null,g=a?m(i):null;return(0,b.jsxs)("div",{ref:n,style:{position:"relative"},onMouseMove:e=>{let t=n.current?.getBoundingClientRect();t&&!(t.width<2)&&r(Math.min(1,Math.max(0,(e.clientX-t.left)/t.width)))},onMouseLeave:()=>r(null),children:[(0,b.jsxs)("svg",{viewBox:"0 0 100 58",preserveAspectRatio:"none",style:{width:"100%",height:132,display:"block"},children:[c<0&&d>0&&(0,b.jsx)("line",{x1:"0",x2:"100",y1:h(0),y2:h(0),stroke:"currentColor",opacity:"0.18",strokeWidth:"0.4"}),t&&l.length>1&&(0,b.jsx)("polyline",{points:p(l),fill:"none",stroke:ln,strokeWidth:"1.3",vectorEffect:"non-scaling-stroke",opacity:"0.95"}),a&&i.length>1&&(0,b.jsx)("polyline",{points:p(i),fill:"none",stroke:ll,strokeWidth:"1.6",vectorEffect:"non-scaling-stroke"}),null!=s&&(0,b.jsx)("line",{x1:100*s,x2:100*s,y1:"0",y2:"58",stroke:"currentColor",opacity:"0.22",strokeWidth:"0.4",vectorEffect:"non-scaling-stroke"}
10),x&&(0,b.jsx)("circle",{cx:100*x.x,cy:h(x.y),r:"1.5",fill:ln}),g&&(0,b.jsx)("circle",{cx:100*g.x,cy:h(g.y),r:"1.7",fill:ll})]}),(x||g)&&(0,b.jsxs)("div",{style:{position:"absolute",top:-4,left:`${Math.min(70,Math.max(0,100*(s||0)))}%`,transform:"translateY(-100%)",background:"rgba(20,24,32,0.96)",border:"1px solid rgba(255,255,255,0.15)",borderRadius:6,padding:"5px 9px",fontSize:11,whiteSpace:"nowrap",pointerEvents:"none",zIndex:5},children:[x&&(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{style:{color:ln},children:"modelled"})," ",(0,b.jsx)("b",{children:lr(x.y,2)}),"/trade · ",x.n.toLocaleString()," trades · ",lr(x.cum)," total"]}),g&&(0,b.jsxs)("div",{children:[(0,b.jsx)("span",{style:{color:ll},children:"live"})," ",(0,b.jsx)("b",{children:lr(g.y,2)}),"/trade · ",g.n.toLocaleString()," trades · ",lr(g.cum)," total"]})]}),(0,b.jsx)("div",{className:"wc-power-sub",style:{fontSize:10,marginTop:2},children:"average $ per trade, left to right across each series' own lifetime"})]})}function lu({state:e,series:t,parity:a}){let[s,r]=(0,_.useState)(!0),[n,l]=(0,_.useState)(!0),[i,o]=(0,_.useState)(!1),[c,d]=(0,_.useState)(!1),[u,h]=(0,_.useState)(!0),p=e.service?.config,m=e.live||{},x=e.research,g=t?.label||`${(e.asset||"").toUpperCase()} ${e.window_min||15}m`,f=Number(m.settled||0),v=Number(m.wins||0),y=f?100*v/f:null,j=e.study_only?["study","#8b93a7"]:e.ledger_available?e.service?.stale?["stale","#f0a852"]:e.service?.live_enabled?["live",ll]:["orders off","#8b93a7"]:["ledger offline","#f0a852"];return(0,b.jsxs)("div",{style:{border:"1px solid rgba(255,255,255,0.12)",borderRadius:10,padding:"12px 14px",marginBottom:14,background:"rgba(255,255,255,0.02)"},children:[(0,b.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:10,marginBottom:8},children:[(0,b.jsx)("b",{style:{fontSize:15},children:g}),(0,b.jsx)("span",{style:{fontSize:10,padding:"1px 6px",borderRadius:4,border:`1px solid ${j[1]}`,color:j[1]},children:j[0]}),(0,b.jsx)("span",{style:{flex:1}}),f>0&&(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)("span",{className:"wc-power-sub",children:[f," settled · ",v,"W/",Number(m.losses||0),"L",null!=y?` \xb7 ${y.toFixed(0)}%`:""]}),(0,b.jsx)("b",{className:Number(m.pnl_usd||0)>=0?"radar-up":"radar-down",children:lr(m.pnl_usd,2)})]})]}),(0,b.jsxs)("div",{style:{display:"flex",gap:14,alignItems:"center",flexWrap:"wrap",marginBottom:4},children:[(0,b.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:5,fontSize:11,cursor:"pointer"},children:[(0,b.jsx)("input",{type:"checkbox",checked:s,onChange:e=>r(e.target.checked)}),(0,b.jsx)("span",{style:{width:14,height:2,background:ln,display:"inline-block"}})," modelled",x?.trades?(0,b.jsxs)("span",{className:"wc-power-sub",children:["(",x.trades.toLocaleString(),")"]}):null]}),(0,b.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:5,fontSize:11,cursor:"pointer"},children:[(0,b.jsx)("input",{type:"checkbox",checked:n,onChange:e=>l(e.target.checked)}),(0,b.jsx)("span",{style:{width:14,height:2,background:ll,display:"inline-block"}})," live",f?(0,b.jsxs)("span",{className:"wc-power-sub",children:["(",f,")"]}):null]}),(0,b.jsx)("span",{style:{flex:1}}),p&&(0,b.jsxs)("span",{className:"wc-power-sub",style:{fontSize:11},children:["minutes ",(p.entry_minutes||[]).join("–")," · z ≥ ",p.z_min," · cap ",Math.round(100*Number(p.price_cap||0)),"¢",p.stake_usd?` \xb7 $${p.stake_usd}`:""]})]}),t?(0,b.jsx)(ld,{series:t,showBt:s,showLv:n}):(0,b.jsx)("div",{className:"wc-power-sub",style:{height:120},children:"loading…"}),t&&u&&(0,b.jsx)(lc,{series:t,showBt:s,showLv:n}),(0,b.jsxs)("div",{style:{display:"flex",gap:18,flexWrap:"wrap",margin:"8px 0 2px",fontSize:11},children:[null!=m.deployed_usd&&(0,b.jsxs)("span",{className:"wc-power-sub",children:["deployed ",(0,b.jsxs)("b",{children:["$",Number(m.deployed_usd).toLocaleString(void 0,{maximumFractionDigits:0})]})]}),m.open?(0,b.jsxs)("span",{className:"wc-power-sub",children:["open ",(0,b.jsx)("b",{children:m.open})]}):null,null!=m.today_pnl_usd&&(0,b.jsxs)("span",{className:"wc-power-sub",children:["today ",(0,b.jsx)("b",{className:Number(m.today_pnl_usd)>=0?"radar-up":"radar-down",children:lr(m.today_pnl_usd)})]}),e.service?.health?.balance_usd!=null&&(0,b.jsxs)("span",{className:"wc-power-sub",children:["balance ",(0,b.jsxs)("b",{children:["$",Number(e.service.health.balance_usd).toLocaleStr
10ing(void 0,{maximumFractionDigits:0})]})]}),x?.max_drawdown_usd!=null&&(0,b.jsxs)("span",{className:"wc-power-sub",children:["modelled drawdown ",(0,b.jsxs)("b",{children:["$",Number(x.max_drawdown_usd).toFixed(0)]})]}),(0,b.jsx)("span",{style:{flex:1}}),(0,b.jsx)("button",{onClick:()=>h(!u),style:{fontSize:10,padding:"1px 7px",background:"none",border:"1px solid rgba(255,255,255,0.18)",borderRadius:4,cursor:"pointer",color:"inherit",marginRight:6},children:u?"hide months":"months"}),a&&(0,b.jsx)("button",{onClick:()=>d(!c),style:{fontSize:10,padding:"1px 7px",background:"none",border:"1px solid rgba(255,255,255,0.18)",borderRadius:4,cursor:"pointer",color:"inherit",marginRight:6},children:c?"hide comparison":`rule vs us (${a.summary.windows})`}),(0,b.jsx)("button",{onClick:()=>o(!i),style:{fontSize:10,padding:"1px 7px",background:"none",border:"1px solid rgba(255,255,255,0.18)",borderRadius:4,cursor:"pointer",color:"inherit"},children:i?"hide entries":`entries (${(e.signals||[]).length})`})]}),c&&a&&(0,b.jsx)(ls,{p:a}),i&&(0,b.jsxs)("div",{style:{marginTop:8,borderTop:"1px solid rgba(255,255,255,0.08)",paddingTop:8},children:[0===(e.signals||[]).length&&(0,b.jsx)("div",{className:"wc-power-sub",children:e.ledger_error||"No window evaluated yet."}),(e.signals||[]).map(e=>{let t,a="filled"===e.execution;return(0,b.jsxs)("div",{style:{display:"flex",gap:10,alignItems:"baseline",padding:"3px 0",fontSize:11,borderBottom:"1px solid rgba(255,255,255,0.04)"},children:[(0,b.jsx)("b",{style:{minWidth:190},children:e.name}),(0,b.jsxs)("span",{className:"wc-power-sub",children:["min ",e.minute," · z ",e.z.toFixed(2)," · ",(t=e.evaluated_at_ms)?`${new Date(t).toISOString().slice(11,16)}Z`:"—"]}),(0,b.jsx)("span",{style:{flex:1}}),a?(0,b.jsxs)("span",{children:["entry ",(0,b.jsxs)("b",{children:[(100*Number(e.avg_price||0)).toFixed(1),"¢"]})," · ",(0,b.jsxs)("b",{children:["$",Number(e.cost_usd||0).toFixed(0)]})]}):null!=e.best_ask?(0,b.jsxs)("span",{className:"wc-power-sub",children:["ask ",Math.round(100*Number(e.best_ask)),"¢",e.skip?` \xb7 ${e.skip.replace(/_/g," ")}`:""]}):(0,b.jsx)("span",{className:"wc-power-sub",children:(e.skip||"—").replace(/_/g," ")}),null!=e.won&&(0,b.jsx)("b",{className:e.won?"radar-up":"radar-down",style:{minWidth:62,textAlign:"right"},children:lr(e.pnl,2)})]},e.id)})]})]})}function lh(){let[e,t]=(0,_.useState)({}),[a,s]=(0,_.useState)({}),[r,n]=(0,_.useState)({}),[l,i]=(0,_.useState)(!1),[o,c]=(0,_.useState)(!1);(0,_.useEffect)(()=>{let e=!1,a=async()=>{try{let[a,r,l]=await Promise.all([(0,er.authGetJson)("/api/worldcup/autotrade/status"),(0,er.authGetJson)("/api/worldcup/autotrade/pm15m-series"),(0,er.authGetJson)("/api/worldcup/autotrade/pm15m-parity")]);if(e)return;t(a?.data?.pm15m_agent||{}),s(r?.data||{}),n(l?.data||{}),i(!1)}catch{e||i(!0)}};a();let r=setInterval(()=>void a(),6e4);return()=>{e=!0,clearInterval(r)}},[]);let d=Object.values(e).sort((e,t)=>!!e.study_only!=!!t.study_only?e.study_only?1:-1:(t.window_min||0)-(e.window_min||0)||(e.asset||"").localeCompare(t.asset||"")),u=d.reduce((e,t)=>e+Number(t.live?.pnl_usd||0),0),h=d.reduce((e,t)=>e+Number(t.live?.settled||0),0),p=(0,_.useMemo)(()=>({label:`All strategies combined \xb7 ${d.length} lanes`,window_min:0,backtest:d.flatMap(e=>a[e.account_id]?.backtest||[]).sort((e,t)=>e[0]-t[0]),live:d.flatMap(e=>a[e.account_id]?.live||[]).sort((e,t)=>e[0]-t[0])}),[d,a]),m=(0,_.useMemo)(()=>({account_id:"merged",asset:"",window_min:0,ledger_available:!0,service:{live_enabled:!0,stale:!1},live:{settled:d.reduce((e,t)=>e+Number(t.live?.settled||0),0),wins:d.reduce((e,t)=>e+Number(t.live?.wins||0),0),losses:d.reduce((e,t)=>e+Number(t.live?.losses||0),0),pnl_usd:d.reduce((e,t)=>e+Number(t.live?.pnl_usd||0),0),deployed_usd:d.reduce((e,t)=>e+Number(t.live?.deployed_usd||0),0),today_pnl_usd:d.reduce((e,t)=>e+Number(t.live?.today_pnl_usd||0),0),open:d.reduce((e,t)=>e+Number(t.live?.open||0),0)},research:{trades:d.reduce((e,t)=>e+Number(t.research?.trades||0),0)},signals:[]}),[d]);return(0,b.jsxs)("div",{style:{padding:"16px 18px",maxWidth:1200,height:"100%",overflowY:"auto"},children:[(0,b.jsxs)("div",{style:{display:"flex",alignItems:"baseline",gap:12,marginBottom:14},children:[(0,b.jsx)("h1",{style:{fontSize:20,margin:0},children:"Research"}),h>0&&(0,b.jsxs)("span",{className:"wc-power-sub",children:[h," settled · ",(0,b.jsx)("b",{className:u>=0?"radar-up":"radar-down",children:lr(u,2)})," realised"]})]}),d.length>1&&(0,b.jsxs)("label",{style:{display:"flex",alignItems:"center",gap:6,fontSize:11,cursor:"pointer",margin:"0 0 10px"},children:[(0,b.jsx)("input",{type:"checkbox",checked:o,onChange:e=>c(e.target.checked)}),"merged view — every strategy as one book"]}),l&&(0,b.jsx)("div",{className:"empty-state",children:"Cockpit API unreachable."}),!l&&!d.length&&(0,b.jsx)("div",{className:"empty-state",children:"Loading lanes…"}),o?(0,b.jsx)(lu,{state:m,series:p}):d.map(e=>(0,b.jsx)(lu,{state:e,series:a[e.account_id],parity:r[e.account_id]},e.account_id))]})}function lp(e){if("string"==typeof e||"number"==typeof e)return""+e;let t="";if(Array.isArray(e))for(let a=0,s;a<e.length;a++)""!==(s=lp(e[a]))&&(t+=(t&&" ")+s);else for(let a in e)e[a]&&(t+=(t&&" ")+a);return t}e.i(39057);var lm={value:()=>{}};function lx(){for(var e,t=0,a=arguments.length,s={};t<a;++t){if(!(e=arguments[t]+"")||e in s||/[\s.]/.test(e))throw Error("illegal type: "+e);s[e]=[]}return new lg(s)}function lg(e){this._=e}function lf(e,t,a){for(var s=0,r=e.length;s<r;++s)if(e[s].name===t){e[s]=lm,e=e.slice(0,s).concat(e.slice(s+1));break}return null!=a&&e.push({name:t,value:a}),e}function lb(){}function l_(e){return null==e?lb:function(){return this.querySelector(e)}}function lv(){return[]}function ly(e){return null==e?lv:function(){return this.querySelectorAll(e)}}function lj(e){return function(){return this.matches(e)}}function lw(e){return function(t){return t.matches(e)}}lg.prototype=lx.prototype={constructor:lg,on:function(e,t){var a,s=this._,r=(e+"").trim().split(/^|\s+/).map(function(e){var t="",a=e.indexOf(".");if(a>=0&&(t=e.slice(a+1),e=e.slice(0,a)),e&&!s.hasOwnProperty(e))throw Error("unknown type: "+e);return{type:e,name:t}}),n=-1,l=r.length;if(arguments.length<2){for(;++n<l;)if((a=(e=r[n]).type)&&(a=function(e,t){for(var a,s=0,r=e.length;s<r;++s)if((a=e[s]).name===t)return a.value}(s[a],e.name)))return a;return}if(null!=t&&"function"!=typeof t)throw Error("invalid callback: "+t);for(;++n<l;)if(a=(e=r[n]).type)s[a]=lf(s[a],e.name,t);else if(null==t)for(a in s)s[a]=lf(s[a],e.name,null);return this},copy:function(){var e={},t=this._;for(var a in t)e[a]=t[a].slice();return new lg(e)},call:function(e,t){if((a=arguments.length-2)>0)for(var a,s,r=Array(a),n=0;n<a;++n)r[n]=arguments[n+2];if(!this._.hasOwnProperty(e))throw Error("unknown type: "+e);for(s=this._[e],n=0,a=s.length;n<a;++n)s[n].value.apply(t,r)},apply:function(e,t,a){if(!this._.hasOwnProperty(e))throw Error("unknown type: "+e);for(var s=this._[e],r=0,n=s.length;r<n;++r)s[r].value.apply(t,a)}};var lN=Array.prototype.find;function lk(){return this.firstElementChild}var lS=Array.prototype.filter;function l$(){return Array.from(this.children)}function lC(e){return Array(e.length)}function lM(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}
10function lE(e,t,a,s,r,n){for(var l,i=0,o=t.length,c=n.length;i<c;++i)(l=t[i])?(l.__data__=n[i],s[i]=l):a[i]=new lM(e,n[i]);for(;i<o;++i)(l=t[i])&&(r[i]=l)}function lA(e,t,a,s,r,n,l){var i,o,c,d=new Map,u=t.length,h=n.length,p=Array(u);for(i=0;i<u;++i)(o=t[i])&&(p[i]=c=l.call(o,o.__data__,i,t)+"",d.has(c)?r[i]=o:d.set(c,o));for(i=0;i<h;++i)c=l.call(e,n[i],i,n)+"",(o=d.get(c))?(s[i]=o,o.__data__=n[i],d.delete(c)):a[i]=new lM(e,n[i]);for(i=0;i<u;++i)(o=t[i])&&d.get(p[i])===o&&(r[i]=o)}function lT(e){return e.__data__}function lF(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}lM.prototype={constructor:lM,appendChild:function(e){return this._parent.insertBefore(e,this._next)},insertBefore:function(e,t){return this._parent.insertBefore(e,t)},querySelector:function(e){return this._parent.querySelector(e)},querySelectorAll:function(e){return this._parent.querySelectorAll(e)}};var lP="http://www.w3.org/1999/xhtml";let lR={svg:"http://www.w3.org/2000/svg",xhtml:lP,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function lO(e){var t=e+="",a=t.indexOf(":");return a>=0&&"xmlns"!==(t=e.slice(0,a))&&(e=e.slice(a+1)),lR.hasOwnProperty(t)?{space:lR[t],local:e}:e}function lL(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function lI(e,t){return e.style.getPropertyValue(t)||lL(e).getComputedStyle(e,null).getPropertyValue(t)}function lD(e){return e.trim().split(/^|\s+/)}function lz(e){return e.classList||new lB(e)}function lB(e){this._node=e,this._names=lD(e.getAttribute("class")||"")}function lW(e,t){for(var a=lz(e),s=-1,r=t.length;++s<r;)a.add(t[s])}function lU(e,t){for(var a=lz(e),s=-1,r=t.length;++s<r;)a.remove(t[s])}function lH(){this.textContent=""}function lq(){this.innerHTML=""}function lV(){this.nextSibling&&this.parentNode.appendChild(this)}function lG(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function lJ(e){var t=lO(e);return(t.local?function(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}:function(e){return function(){var t=this.ownerDocument,a=this.namespaceURI;return a===lP&&t.documentElement.namespaceURI===lP?t.createElement(e):t.createElementNS(a,e)}})(t)}function lY(){return null}function lK(){var e=this.parentNode;e&&e.removeChild(this)}function lX(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function lZ(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function lQ(e){return function(){var t=this.__on;if(t){for(var a,s=0,r=-1,n=t.length;s<n;++s)(a=t[s],e.type&&a.type!==e.type||a.name!==e.name)?t[++r]=a:this.removeEventListener(a.type,a.listener,a.options);++r?t.length=r:delete this.__on}}}function l0(e,t,a){return function(){var s,r=this.__on,n=function(e){t.call(this,e,this.__data__)};if(r){for(var l=0,i=r.length;l<i;++l)if((s=r[l]).type===e.type&&s.name===e.name){this.removeEventListener(s.type,s.listener,s.options),this.addEventListener(s.type,s.listener=n,s.options=a),s.value=t;return}}this.addEventListener(e.type,n,a),s={type:e.type,name:e.name,value:t,listener:n,options:a},r?r.push(s):this.__on=[s]}}function l1(e,t,a){var s=lL(e),r=s.CustomEvent;"function"==typeof r?r=new r(t,a):(r=s.document.createEvent("Event"),a?(r.initEvent(t,a.bubbles,a.cancelable),r.detail=a.detail):r.initEvent(t,!1,!1)),e.dispatchEvent(r)}lB.prototype={add:function(e){0>this._names.indexOf(e)&&(this._names.push(e),this._node.setAttribute("class",this._names.join(" ")))},remove:function(e){var t=this._names.indexOf(e);t>=0&&(this._names.splice(t,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(e){return this._names.indexOf(e)>=0}};var l2=[null];function l5(e,t){this._groups=e,this._parents=t}function l4(){return new l5([[document.documentElement]],l2)}function l3(e){return"string"==typeof e?new l5([[document.querySelector(e)]],[document.documentElement]):new l5([[e]],l2)}function l6(e,t){if(e=function(e){let t;for(;t=e.sourceEvent;)e=t;return e}(e),void 0===t&&(t=e.currentTarget),t){var a=t.ownerSVGElement||t;if(a.createSVGPoint){var s=a.createSVGPoint();return s.x=e.clientX,s.y=e.clientY,[(s=s.matrixTransform(t.getScreenCTM().inverse())).x,s.y]}if(t.getBoundingClientRect){var r=t.getBoundingClientRect();return[e.clientX-r.left-t.clientLeft,e.clientY-r.top-t.clientTop]}}return[e.pageX,e.pageY]}l5.prototype=l4.prototype={constructor:l5,select:function(e){"function"!=typeof e&&(e=l_(e));for(var t=this._groups,a=t.length,s=Array(a),r=0;r<a;++r)for(var n,l,i=t[r],o=i.length,c=s[r]=Array(o),d=0;d<o;++d)(n=i[d])&&(l=e.call(n,n.__data__,d,i))&&("__data__"in n&&(l.__data__=n.__data__),c[d]=l);return new l5(s,this._parents)},selectAll:function(e){if("function"==typeof e){var t;t=e,e=function(){var e;return e=t.apply(this,arguments),null==e?[]:Array.isArray(e)?e:Array.from(e)}}else e=ly(e);for(var a=this._groups,s=a.length,r=[],n=[],l=0;l<s;++l)for(var i,o=a[l],c=o.length,d=0;d<c;++d)(i=o[d])&&(r.push(e.call(i,i.__data__,d,o)),n.push(i));return new l5(r,n)},selectChild:function(e){var t;return this.select(null==e?lk:(t="function"==typeof e?e:lw(e),function(){return lN.call(this.children,t)}))},selectChildren:function(e){var t;return this.selectAll(null==e?l$:(t="function"==typeof e?e:lw(e),function(){return lS.call(this.children,t)}))},filter:function(e){"function"!=typeof e&&(e=lj(e));for(var t=this._groups,a=t.length,s=Array(a),r=0;r<a;++r)for(var n,l=t[r],i=l.length,o=s[r]=[],c=0;c<i;++c)(n=l[c])&&e.call(n,n.__data__,c,l)&&o.push(n);return new l5(s,this._parents)},data:function(e,t){if(!arguments.length)return Array.from(this,lT);var a=t?lA:lE,s=this._parents,r=this._groups;"function"!=typeof e&&(b=e,e=function(){return b});for(var n=r.length,l=Array(n),i=Array(n),o=Array(n),c=0;c<n;++c){var d=s[c],u=r[c],h=u.length,p="object"==typeof(f=e.call(d,d&&d.__data__,c,s))&&"length"in f?f:Array.from(f),m=p.length,x=i[c]=Array(m),g=l[c]=Array(m);a(d,u,x,g,o[c]=Array(h),p,t);for(var f,b,_,v,y=0,j=0;y<m;++y)if(_=x[y]){for(y>=j&&(j=y+1);!(v=g[j])&&++j<m;);_._next=v||null}}return(l=new l5(l,s))._enter=i,l._exit=o,l},enter:function(){return new l5(this._enter||this._groups.map(lC),this._parents)},exit:function(){return new l5(this._exit||this._groups.map(lC),this._parents)},join:function(e,t,a){var s=this.enter(),r=this,n=this.exit();return"function"==typeof e?(s=e(s))&&(s=s.selection()):s=s.append(e+""),null!=t&&(r=t(r))&&(r=r.selection()),null==a?n.remove():a(n),s&&r?s.merge(r).order():r},merge:function(e){for(var t=e.selection?e.selection():e,a=this._groups,s=t._groups,r=a.length,n=s.length,l=Math.min(r,n),i=Array(r),o=0;o<l;++o)for(var c,d=a[o],u=s[o],h=d.length,p=i[o]=Array(h),m=0;m<h;++m)(c=d[m]||u[m])&&(p[m]=c);for(;o<r;++o)i[o]=a[o];return new l5(i,this._parents)},selection:function(){return this},order:function(){for(var e=this._groups,t=-1,a=e.length;++t<a;)for(var s,r=e[t],n=r.length-1,l=r[n];--n>=0;)(s=r[n])&&(l&&4^s.compareDocumentPosition(l)&&l.parentNode.insertBefore(s,l),l=s);return this},sort:function(e){function t(t,a){return t&&a?e(t.__data__,a.__data__):!t-!a}e||(e=lF);for(var a=this._groups,s=a.length,r=Array(s),n=0;n<s;++n){for(var l,i=a[n],o=i.length,c=r[n]=Array(o),d=0;d<o;++d)(l=i[d])&&(c[d]=l);c.sort(t)}return new l5(r,this._parents).order()},call:function(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this},nodes:function(){return Array.from(this)},node:function(){for(var e=this._groups,t=0,a=e.length;t<a;++t)for(var s=e[t],r=0,n=s.length;r<n;++r){var l=s[r];if(l)return l}return null},size:function(){let e=0;for(let t of this)++e;return e},empty:function(){return!this.node()},each:function(e){for(var t=this._groups,a=0,s=t.length;a<s;++a)for(var r,n=t[a],l=0,i=n.length;l<i;++l)(r=n[l])&&e.call(r,r.__data__,l,n);return this},attr:function(e,t){var a=lO(e);if(arguments.length<2){var s=this.node();return a.local?s.getAttributeNS(a.space,a.local):s.getAttribute(a)}return this.each((null==t?a.local?function(e){return function(){this.removeAttributeNS(e.space,e.local)}}:function(e){return function(){this.removeAttribute(e)}}:"function"==typeof t?a.local?function(e,t){return function(){var a=t.a
10pply(this,arguments);null==a?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,a)}}:function(e,t){return function(){var a=t.apply(this,arguments);null==a?this.removeAttribute(e):this.setAttribute(e,a)}}:a.local?function(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}:function(e,t){return function(){this.setAttribute(e,t)}})(a,t))},style:function(e,t,a){return arguments.length>1?this.each((null==t?function(e){return function(){this.style.removeProperty(e)}}:"function"==typeof t?function(e,t,a){return function(){var s=t.apply(this,arguments);null==s?this.style.removeProperty(e):this.style.setProperty(e,s,a)}}:function(e,t,a){return function(){this.style.setProperty(e,t,a)}})(e,t,null==a?"":a)):lI(this.node(),e)},property:function(e,t){return arguments.length>1?this.each((null==t?function(e){return function(){delete this[e]}}:"function"==typeof t?function(e,t){return function(){var a=t.apply(this,arguments);null==a?delete this[e]:this[e]=a}}:function(e,t){return function(){this[e]=t}})(e,t)):this.node()[e]},classed:function(e,t){var a=lD(e+"");if(arguments.length<2){for(var s=lz(this.node()),r=-1,n=a.length;++r<n;)if(!s.contains(a[r]))return!1;return!0}return this.each(("function"==typeof t?function(e,t){return function(){(t.apply(this,arguments)?lW:lU)(this,e)}}:t?function(e){return function(){lW(this,e)}}:function(e){return function(){lU(this,e)}})(a,t))},text:function(e){return arguments.length?this.each(null==e?lH:("function"==typeof e?function(e){return function(){var t=e.apply(this,arguments);this.textContent=null==t?"":t}}:function(e){return function(){this.textContent=e}})(e)):this.node().textContent},html:function(e){return arguments.length?this.each(null==e?lq:("function"==typeof e?function(e){return function(){var t=e.apply(this,arguments);this.innerHTML=null==t?"":t}}:function(e){return function(){this.innerHTML=e}})(e)):this.node().innerHTML},raise:function(){return this.each(lV)},lower:function(){return this.each(lG)},append:function(e){var t="function"==typeof e?e:lJ(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})},insert:function(e,t){var a="function"==typeof e?e:lJ(e),s=null==t?lY:"function"==typeof t?t:l_(t);return this.select(function(){return this.insertBefore(a.apply(this,arguments),s.apply(this,arguments)||null)})},remove:function(){return this.each(lK)},clone:function(e){return this.select(e?lZ:lX)},datum:function(e){return arguments.length?this.property("__data__",e):this.node().__data__},on:function(e,t,a){var s,r,n=(e+"").trim().split(/^|\s+/).map(function(e){var t="",a=e.indexOf(".");return a>=0&&(t=e.slice(a+1),e=e.slice(0,a)),{type:e,name:t}}),l=n.length;if(arguments.length<2){var i=this.node().__on;if(i){for(var o,c=0,d=i.length;c<d;++c)for(s=0,o=i[c];s<l;++s)if((r=n[s]).type===o.type&&r.name===o.name)return o.value}return}for(s=0,i=t?l0:lQ;s<l;++s)this.each(i(n[s],t,a));return this},dispatch:function(e,t){return this.each(("function"==typeof t?function(e,t){return function(){return l1(this,e,t.apply(this,arguments))}}:function(e,t){return function(){return l1(this,e,t)}})(e,t))},[Symbol.iterator]:function*(){for(var e=this._groups,t=0,a=e.length;t<a;++t)for(var s,r=e[t],n=0,l=r.length;n<l;++n)(s=r[n])&&(yield s)}};let l8={passive:!1},l9={capture:!0,passive:!1};function l7(e){e.stopImmediatePropagation()}function ie(e){e.preventDefault(),e.stopImmediatePropagation()}function it(e){var t=e.document.documentElement,a=l3(e).on("dragstart.drag",ie,l9);"onselectstart"in t?a.on("selectstart.drag",ie,l9):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function ia(e,t){var a=e.document.documentElement,s=l3(e).on("dragstart.drag",null);t&&(s.on("click.drag",ie,l9),setTimeout(function(){s.on("click.drag",null)},0)),"onselectstart"in a?s.on("selectstart.drag",null):(a.style.MozUserSelect=a.__noselect,delete a.__noselect)}let is=e=>()=>e;function ir(e,{sourceEvent:t,subject:a,target:s,identifier:r,active:n,x:l,y:i,dx:o,dy:c,dispatch:d}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},subject:{value:a,enumerable:!0,configurable:!0},target:{value:s,enumerable:!0,configurable:!0},identifier:{value:r,enumerable:!0,configurable:!0},active:{value:n,enumerable:!0,configurable:!0},x:{value:l,enumerable:!0,configurable:!0},y:{value:i,enumerable:!0,configurable:!0},dx:{value:o,enumerable:!0,configurable:!0},dy:{value:c,enumerable:!0,configurable:!0},_:{value:d}})}function il(e){return!e.ctrlKey&&!e.button}function ii(){return this.parentNode}function io(e,t){return null==t?{x:e.x,y:e.y}:t}function ic(){return navigator.maxTouchPoints||"ontouchstart"in this}function id(){var e,t,a,s,r=il,n=ii,l=io,i=ic,o={},c=lx("start","drag","end"),d=0,u=0;function h(e){e.on("mousedown.drag",p).filter(i).on("touchstart.drag",g).on("touchmove.drag",f,l8).on("touchend.drag touchcancel.drag",b).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function p(l,i){if(!s&&r.call(this,l,i)){var o=_(this,n.call(this,l,i),l,i,"mouse");o&&(l3(l.view).on("mousemove.drag",m,l9).on("mouseup.drag",x,l9),it(l.view),l7(l),a=!1,e=l.clientX,t=l.clientY,o("start",l))}}function m(s){if(ie(s),!a){var r=s.clientX-e,n=s.clientY-t;a=r*r+n*n>u}o.mouse("drag",s)}function x(e){l3(e.view).on("mousemove.drag mouseup.drag",null),ia(e.view,a),ie(e),o.mouse("end",e)}function g(e,t){if(r.call(this,e,t)){var a,s,l=e.changedTouches,i=n.call(this,e,t),o=l.length;for(a=0;a<o;++a)(s=_(this,i,e,t,l[a].identifier,l[a]))&&(l7(e),s("start",e,l[a]))}}function f(e){var t,a,s=e.changedTouches,r=s.length;for(t=0;t<r;++t)(a=o[s[t].identifier])&&(ie(e),a("drag",e,s[t]))}function b(e){var t,a,r=e.changedTouches,n=r.length;for(s&&clearTimeout(s),s=setTimeout(function(){s=null},500),t=0;t<n;++t)(a=o[r[t].identifier])&&(l7(e),a("end",e,r[t]))}
10function _(e,t,a,s,r,n){var i,u,p,m=c.copy(),x=l6(n||a,t);if(null!=(p=l.call(e,new ir("beforestart",{sourceEvent:a,target:h,identifier:r,active:d,x:x[0],y:x[1],dx:0,dy:0,dispatch:m}),s)))return i=p.x-x[0]||0,u=p.y-x[1]||0,function a(n,l,c){var g,f=x;switch(n){case"start":o[r]=a,g=d++;break;case"end":delete o[r],--d;case"drag":x=l6(c||l,t),g=d}m.call(n,e,new ir(n,{sourceEvent:l,subject:p,target:h,identifier:r,active:g,x:x[0]+i,y:x[1]+u,dx:x[0]-f[0],dy:x[1]-f[1],dispatch:m}),s)}}return h.filter=function(e){return arguments.length?(r="function"==typeof e?e:is(!!e),h):r},h.container=function(e){return arguments.length?(n="function"==typeof e?e:is(e),h):n},h.subject=function(e){return arguments.length?(l="function"==typeof e?e:is(e),h):l},h.touchable=function(e){return arguments.length?(i="function"==typeof e?e:is(!!e),h):i},h.on=function(){var e=c.on.apply(c,arguments);return e===c?h:e},h.clickDistance=function(e){return arguments.length?(u=(e*=1)*e,h):Math.sqrt(u)},h}function iu(e){return((e=Math.exp(e))+1/e)/2}ir.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};let ih=function e(t,a,s){function r(e,r){var n,l,i=e[0],o=e[1],c=e[2],d=r[0],u=r[1],h=r[2],p=d-i,m=u-o,x=p*p+m*m;if(x<1e-12)l=Math.log(h/c)/t,n=function(e){return[i+e*p,o+e*m,c*Math.exp(t*e*l)]};else{var g=Math.sqrt(x),f=(h*h-c*c+s*x)/(2*c*a*g),b=(h*h-c*c-s*x)/(2*h*a*g),_=Math.log(Math.sqrt(f*f+1)-f);l=(Math.log(Math.sqrt(b*b+1)-b)-_)/t,n=function(e){var s,r,n=e*l,d=iu(_),u=c/(a*g)*(d*(((s=Math.exp(2*(s=t*n+_)))-1)/(s+1))-((r=Math.exp(r=_))-1/r)/2);return[i+u*p,o+u*m,c*d/iu(t*n+_)]}}return n.duration=1e3*l*t/Math.SQRT2,n}return r.rho=function(t){var a=Math.max(.001,+t),s=a*a;return e(a,s,s*s)},r}(Math.SQRT2,2,4);var ip,im,ix=0,ig=0,ib=0,i_=0,iv=0,iy=0,ij="object"==typeof performance&&performance.now?performance:Date,iw="object"==typeof window&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function iN(){return iv||(iw(ik),iv=ij.now()+iy)}function ik(){iv=0}function iS(){this._call=this._time=this._next=null}function i$(e,t,a){var s=new iS;return s.restart(e,t,a),s}function iC(){iv=(i_=ij.now())+iy,ix=ig=0;try{iN(),++ix;for(var e,t=ip;t;)(e=iv-t._time)>=0&&t._call.call(void 0,e),t=t._next;--ix}finally{ix=0,function(){for(var e,t,a=ip,s=1/0;a;)a._call?(s>a._time&&(s=a._time),e=a,a=a._next):(t=a._next,a._next=null,a=e?e._next=t:ip=t);im=e,iE(s)}(),iv=0}}function iM(){var e=ij.now(),t=e-i_;t>1e3&&(iy-=t,i_=e)}function iE(e){!ix&&(ig&&(ig=clearTimeout(ig)),e-iv>24?(e<1/0&&(ig=setTimeout(iC,e-ij.now()-iy)),ib&&(ib=clearInterval(ib))):(ib||(i_=ij.now(),ib=setInterval(iM,1e3)),ix=1,iw(iC)))}function iA(e,t,a){var s=new iS;return t=null==t?0:+t,s.restart(a=>{s.stop(),e(a+t)},t,a),s}iS.prototype=i$.prototype={constructor:iS,restart:function(e,t,a){if("function"!=typeof e)throw TypeError("callback is not a function");a=(null==a?iN():+a)+(null==t?0:+t),this._next||im===this||(im?im._next=this:ip=this,im=this),this._call=e,this._time=a,iE()},stop:function(){this._call&&(this._call=null,this._time=1/0,iE())}};var iT=lx("start","end","cancel","interrupt"),iF=[];function iP(e,t,a,s,r,n){var l=e.__transition;if(l){if(a in l)return}else e.__transition={};!function(e,t,a){var s,r=e.__transition;function n(o){var c,d,u,h;if(1!==a.state)return i();for(c in r)if((h=r[c]).name===a.name){if(3===h.state)return iA(n);4===h.state?(h.state=6,h.timer.stop(),h.on.call("interrupt",e,e.__data__,h.index,h.group),delete r[c]):+c<t&&(h.state=6,h.timer.stop(),h.on.call("cancel",e,e.__data__,h.index,h.group),delete r[c])}if(iA(function(){3===a.state&&(a.state=4,a.timer.restart(l,a.delay,a.time),l(o))}),a.state=2,a.on.call("start",e,e.__data__,a.index,a.group),2===a.state){for(c=0,a.state=3,s=Array(u=a.tween.length),d=-1;c<u;++c)(h=a.tween[c].value.call(e,e.__data__,a.index,a.group))&&(s[++d]=h);s.length=d+1}}function l(t){for(var r=t<a.duration?a.ease.call(null,t/a.duration):(a.timer.restart(i),a.state=5,1),n=-1,l=s.length;++n<l;)s[n].call(e,r);5===a.state&&(a.on.call("end",e,e.__data__,a.index,a.group),i())}function i(){for(var s in a.state=6,a.timer.stop(),delete r[t],r)return;delete e.__transition}r[t]=a,a.timer=i$(function(e){a.state=1,a.timer.restart(n,a.delay,a.time),a.delay<=e&&n(e-a.delay)},0,a.time)}(e,a,{name:t,index:s,group:r,on:iT,tween:iF,time:n.time,delay:n.delay,duration:n.duration,ease:n.ease,timer:null,state:0})}function iR(e,t){var a=iL(e,t);if(a.state>0)throw Error("too late; already scheduled");return a}function iO(e,t){var a=iL(e,t);if(a.state>3)throw Error("too late; already running");return a}function iL(e,t){var a=e.__transition;if(!a||!(a=a[t]))throw Error("transition not found");return a}function iI(e,t){var a,s,r,n=e.__transition,l=!0;if(n){for(r in t=null==t?null:t+"",n){if((a=n[r]).name!==t){l=!1;continue}s=a.state>2&&a.state<5,a.state=6,a.timer.stop(),a.on.call(s?"interrupt":"cancel",e,e.__data__,a.index,a.group),delete n[r]}l&&delete e.__transition}}function iD(e,t){return e*=1,t*=1,function(a){return e*(1-a)+t*a}}var iz=180/Math.PI,iB={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};
vendor: 6,062 bytes, line 10
10function iW(e,t,a,s,r,n){var l,i,o;return(l=Math.sqrt(e*e+t*t))&&(e/=l,t/=l),(o=e*a+t*s)&&(a-=e*o,s-=t*o),(i=Math.sqrt(a*a+s*s))&&(a/=i,s/=i,o/=i),e*s<t*a&&(e=-e,t=-t,o=-o,l=-l),{translateX:r,translateY:n,rotate:Math.atan2(t,e)*iz,skewX:Math.atan(o)*iz,scaleX:l,scaleY:i}}function iU(e,t,a,s){function r(e){return e.length?e.pop()+" ":""}return function(n,l){var i,o,c,d,u=[],h=[];return n=e(n),l=e(l),!function(e,s,r,n,l,i){if(e!==r||s!==n){var o=l.push("translate(",null,t,null,a);i.push({i:o-4,x:iD(e,r)},{i:o-2,x:iD(s,n)})}else(r||n)&&l.push("translate("+r+t+n+a)}(n.translateX,n.translateY,l.translateX,l.translateY,u,h),i=n.rotate,o=l.rotate,i!==o?(i-o>180?o+=360:o-i>180&&(i+=360),h.push({i:u.push(r(u)+"rotate(",null,s)-2,x:iD(i,o)})):o&&u.push(r(u)+"rotate("+o+s),c=n.skewX,d=l.skewX,c!==d?h.push({i:u.push(r(u)+"skewX(",null,s)-2,x:iD(c,d)}):d&&u.push(r(u)+"skewX("+d+s),!function(e,t,a,s,n,l){if(e!==a||t!==s){var i=n.push(r(n)+"scale(",null,",",null,")");l.push({i:i-4,x:iD(e,a)},{i:i-2,x:iD(t,s)})}else(1!==a||1!==s)&&n.push(r(n)+"scale("+a+","+s+")")}(n.scaleX,n.scaleY,l.scaleX,l.scaleY,u,h),n=l=null,function(e){for(var t,a=-1,s=h.length;++a<s;)u[(t=h[a]).i]=t.x(e);return u.join("")}}}var iH=iU(function(e){let t=new("function"==typeof DOMMatrix?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?iB:iW(t.a,t.b,t.c,t.d,t.e,t.f)},"px, ","px)","deg)"),iq=iU(function(e){return null==e?iB:(c||(c=document.createElementNS("http://www.w3.org/2000/svg","g")),c.setAttribute("transform",e),e=c.transform.baseVal.consolidate())?iW((e=e.matrix).a,e.b,e.c,e.d,e.e,e.f):iB},", ",")",")");function iV(e,t,a){var s=e._id;return e.each(function(){var e=iO(this,s);(e.value||(e.value={}))[t]=a.apply(this,arguments)}),function(e){return iL(e,s).value[t]}}function iG(e,t,a){e.prototype=t.prototype=a,a.constructor=e}function iJ(e,t){var a=Object.create(e.prototype);for(var s in t)a[s]=t[s];return a}function iY(){}var iK="\\s*([+-]?\\d+)\\s*",iX="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",iZ="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",iQ=/^#([0-9a-f]{3,8})$/,i0=RegExp(`^rgb\\(${iK},${iK},${iK}\\)$`),i1=RegExp(`^rgb\\(${iZ},${iZ},${iZ}\\)$`),i2=RegExp(`^rgba\\(${iK},${iK},${iK},${iX}\\)$`),i5=RegExp(`^rgba\\(${iZ},${iZ},${iZ},${iX}\\)$`),i4=RegExp(`^hsl\\(${iX},${iZ},${iZ}\\)$`),i3=RegExp(`^hsla\\(${iX},${iZ},${iZ},${iX}\\)$`),i6={aliceblue:0xf0f8ff,antiquewhite:0xfaebd7,aqua:65535,aquamarine:8388564,azure:0xf0ffff,beige:0xf5f5dc,bisque:0xffe4c4,black:0,blanchedalmond:0xffebcd,blue:255,blueviolet:9055202,brown:0xa52a2a,burlywood:0xdeb887,cadetblue:6266528,chartreuse:8388352,chocolate:0xd2691e,coral:0xff7f50,cornflowerblue:6591981,cornsilk:0xfff8dc,crimson:0xdc143c,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:0xb8860b,darkgray:0xa9a9a9,darkgreen:25600,darkgrey:0xa9a9a9,darkkhaki:0xbdb76b,darkmagenta:9109643,darkolivegreen:5597999,darkorange:0xff8c00,darkorchid:0x9932cc,darkred:9109504,darksalmon:0xe9967a,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:0xff1493,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:0xb22222,floralwhite:0xfffaf0,forestgreen:2263842,fuchsia:0xff00ff,gainsboro:0xdcdcdc,ghostwhite:0xf8f8ff,gold:0xffd700,goldenrod:0xdaa520,gray:8421504,green:32768,greenyellow:0xadff2f,grey:8421504,honeydew:0xf0fff0,hotpink:0xff69b4,indianred:0xcd5c5c,indigo:4915330,ivory:0xfffff0,khaki:0xf0e68c,lavender:0xe6e6fa,lavenderblush:0xfff0f5,lawngreen:8190976,lemonchiffon:0xfffacd,lightblue:0xadd8e6,lightcoral:0xf08080,lightcyan:0xe0ffff,lightgoldenrodyellow:0xfafad2,lightgray:0xd3d3d3,lightgreen:9498256,lightgrey:0xd3d3d3,lightpink:0xffb6c1,lightsalmon:0xffa07a,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:0xb0c4de,lightyellow:0xffffe0,lime:65280,limegreen:3329330,linen:0xfaf0e6,magenta:0xff00ff,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:0xba55d3,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:0xc71585,midnightblue:1644912,mintcream:0xf5fffa,mistyrose:0xffe4e1,moccasin:0xffe4b5,navajowhite:0xffdead,navy:128,oldlace:0xfdf5e6,olive:8421376,olivedrab:7048739,orange:0xffa500,orangered:0xff4500,orchid:0xda70d6,palegoldenrod:0xeee8aa,palegreen:0x98fb98,paleturquoise:0xafeeee,palevioletred:0xdb7093,papayawhip:0xffefd5,peachpuff:0xffdab9,peru:0xcd853f,pink:0xffc0cb,plum:0xdda0dd,powderblue:0xb0e0e6,purple:8388736,rebeccapurple:6697881,red:0xff0000,rosybrown:0xbc8f8f,royalblue:4286945,saddlebrown:9127187,salmon:0xfa8072,sandybrown:0xf4a460,seagreen:3050327,seashell:0xfff5ee,sienna:0xa0522d,silver:0xc0c0c0,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:0xfffafa,springgreen:65407,steelblue:4620980,tan:0xd2b48c,teal:32896,thistle:0xd8bfd8,tomato:0xff6347,turquoise:4251856,violet:0xee82ee,wheat:0xf5deb3,white:0xffffff,whitesmoke:0xf5f5f5,yellow:0xffff00,yellowgreen:0x9acd32};function i8(){return this.rgb().formatHex()}function i9(){return this.rgb().formatRgb()}function i7(e){var t,a;return e=(e+"").trim().toLowerCase(),(t=iQ.exec(e))?(a=t[1].length,t=parseInt(t[1],16),6===a?oe(t):3===a?new os(t>>8&15|t>>4&240,t>>4&15|240&t,(15&t)<<4|15&t,1):8===a?ot(t>>24&255,t>>16&255,t>>8&255,(255&t)/255):4===a?ot(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|240&t,((15&t)<<4|15&t)/255):null):(t=i0.exec(e))?new os(t[1],t[2],t[3],1):(t=i1.exec(e))?new os(255*t[1]/100,255*t[2]/100,255*t[3]/100,1):(t=i2.exec(e))?ot(t[1],t[2],t[3],t[4]):(t=i5.exec(e))?ot(255*t[1]/100,255*t[2]/100,255*t[3]/100,t[4]):(t=i4.exec(e))?oc(t[1],t[2]/100,t[3]/100,1):(t=i3.exec(e))?oc(t[1],t[2]/100,t[3]/100,t[4]):i6.hasOwnProperty(e)?oe(i6[e]):"transparent"===e?new os(NaN,NaN,NaN,0):null}function oe(e){return new os(e>>16&255,e>>8&255,255&e,1)}function ot(e,t,a,s){return s<=0&&(e=t=a=NaN),new os(e,t,a,s)}function oa(e,t,a,s){var r;return 1==arguments.length?((r=e)instanceof iY||(r=i7(r)),r)?new os((r=r.rgb()
10).r,r.g,r.b,r.opacity):new os:new os(e,t,a,null==s?1:s)}function os(e,t,a,s){this.r=+e,this.g=+t,this.b=+a,this.opacity=+s}function or(){return`#${oo(this.r)}${oo(this.g)}${oo(this.b)}`}function on(){let e=ol(this.opacity);return`${1===e?"rgb(":"rgba("}${oi(this.r)}, ${oi(this.g)}, ${oi(this.b)}${1===e?")":`, ${e})`}`}function ol(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function oi(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function oo(e){return((e=oi(e))<16?"0":"")+e.toString(16)}function oc(e,t,a,s){return s<=0?e=t=a=NaN:a<=0||a>=1?e=t=NaN:t<=0&&(e=NaN),new ou(e,t,a,s)}function od(e){if(e instanceof ou)return new ou(e.h,e.s,e.l,e.opacity);if(e instanceof iY||(e=i7(e)),!e)return new ou;if(e instanceof ou)return e;var t=(e=e.rgb()).r/255,a=e.g/255,s=e.b/255,r=Math.min(t,a,s),n=Math.max(t,a,s),l=NaN,i=n-r,o=(n+r)/2;return i?(l=t===n?(a-s)/i+(a<s)*6:a===n?(s-t)/i+2:(t-a)/i+4,i/=o<.5?n+r:2-n-r,l*=60):i=o>0&&o<1?0:l,new ou(l,i,o,e.opacity)}function ou(e,t,a,s){this.h=+e,this.s=+t,this.l=+a,this.opacity=+s}function oh(e){return(e=(e||0)%360)<0?e+360:e}function op(e){return Math.max(0,Math.min(1,e||0))}function om(e,t,a){return(e<60?t+(a-t)*e/60:e<180?a:e<240?t+(a-t)*(240-e)/60:t)*255}function ox(e,t,a,s,r){var n=e*e,l=n*e;return((1-3*e+3*n-l)*t+(4-6*n+3*l)*a+(1+3*e+3*n-3*l)*s+l*r)/6}iG(iY,i7,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:i8,formatHex:i8,formatHex8:function(){return this.rgb().formatHex8()},formatHsl:function(){return od(this).formatHsl()},formatRgb:i9,toString:i9}),iG(os,oa,iJ(iY,{brighter(e){return e=null==e?1.4285714285714286:Math.pow(1.4285714285714286,e),new os(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=null==e?.7:Math.pow(.7,e),new os(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new os(oi(this.r),oi(this.g),oi(this.b),ol(this.opacity))},displayable(){return -.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:or,formatHex:or,formatHex8:function(){return`#${oo(this.r)}${oo(this.g)}${oo(this.b)}${oo((isNaN(this.opacity)?1:this.opacity)*255)}`},formatRgb:on,toString:on})),iG(ou,function(e,t,a,s){return 1==arguments.length?od(e):new ou(e,t,a,null==s?1:s)},iJ(iY,{brighter(e){return e=null==e?1.4285714285714286:Math.pow(1.4285714285714286,e),new ou(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=null==e?.7:Math.pow(.7,e),new ou(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,a=this.l,s=a+(a<.5?a:1-a)*t,r=2*a-s;return new os(om(e>=240?e-240:e+120,r,s),om(e,r,s),om(e<120?e+240:e-120,r,s),this.opacity)},clamp(){return new ou(oh(this.h),op(this.s),op(this.l),ol(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){let e=ol(this.opacity);return`${1===e?"hsl(":"hsla("}${oh(this.h)}, ${100*op(this.s)}%, ${100*op(this.l)}%${1===e?")":`, ${e})`}`}}));let og=e=>()=>e;function of(e,t){var a=t-e;return a?function(t){return e+t*a}:og(isNaN(e)?t:e)}let ob=function e(t){var a,s=1==(a=+t)?of:function(e,t){var s,r,n;return t-e?(s=e,r=t,s=Math.pow(s,n=a),r=Math.pow(r,n)-s,n=1/n,function(e){return Math.pow(s+e*r,n)}):og(isNaN(e)?t:e)};function r(e,t){var a=s((e=oa(e)).r,(t=oa(t)).r),r=s(e.g,t.g),n=s(e.b,t.b),l=of(e.opacity,t.opacity);return function(t){return e.r=a(t),e.g=r(t),e.b=n(t),e.opacity=l(t),e+""}}return r.gamma=e,r}(1);function o_(e){return function(t){var a,s,r=t.length,n=Array(r),l=Array(r),i=Array(r);for(a=0;a<r;++a)s=oa(t[a]),n[a]=s.r||0,l[a]=s.g||0,i[a]=s.b||0;return n=e(n),l=e(l),i=e(i),s.opacity=1,function(e){return s.r=n(e),s.g=l(e),s.b=i(e),s+""}}}o_(function(e){var t=e.length-1;return function(a){var s=a<=0?a=0:a>=1?(a=1,t-1):Math.floor(a*t),r=e[s],n=e[s+1],l=s>0?e[s-1]:2*r-n,i=s<t-1?e[s+2]:2*n-r;return ox((a-s/t)*t,l,r,n,i)}}),o_(function(e){var t=e.length;return function(a){var s=Math.floor(((a%=1)<0?++a:a)*t),r=e[(s+t-1)%t],n=e[s%t],l=e[(s+1)%t],i=e[(s+2)%t];return ox((a-s/t)*t,r,n,l,i)}});var ov=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,oy=RegExp(ov.source,"g");function oj(e,t){var a,s,r,n,l,i=ov.lastIndex=oy.lastIndex=0,o=-1,c=[],d=[];for(e+="",t+="";(r=ov.exec(e))&&(n=oy.exec(t));)(l=n.index)>
10i&&(l=t.slice(i,l),c[o]?c[o]+=l:c[++o]=l),(r=r[0])===(n=n[0])?c[o]?c[o]+=n:c[++o]=n:(c[++o]=null,d.push({i:o,x:iD(r,n)})),i=oy.lastIndex;return i<t.length&&(l=t.slice(i),c[o]?c[o]+=l:c[++o]=l),c.length<2?d[0]?(a=d[0].x,function(e){return a(e)+""}):(s=t,function(){return s}):(t=d.length,function(e){for(var a,s=0;s<t;++s)c[(a=d[s]).i]=a.x(e);return c.join("")})}function ow(e,t){var a;return("number"==typeof t?iD:t instanceof i7?ob:(a=i7(t))?(t=a,ob):oj)(e,t)}var oN=l4.prototype.constructor;function ok(e){return function(){this.style.removeProperty(e)}}var oS=0;function o$(e,t,a,s){this._groups=e,this._parents=t,this._name=a,this._id=s}var oC=l4.prototype;o$.prototype=(function(e){return l4().transition(e)}).prototype={constructor:o$,select:function(e){var t=this._name,a=this._id;"function"!=typeof e&&(e=l_(e));for(var s=this._groups,r=s.length,n=Array(r),l=0;l<r;++l)for(var i,o,c=s[l],d=c.length,u=n[l]=Array(d),h=0;h<d;++h)(i=c[h])&&(o=e.call(i,i.__data__,h,c))&&("__data__"in i&&(o.__data__=i.__data__),u[h]=o,iP(u[h],t,a,h,u,iL(i,a)));return new o$(n,this._parents,t,a)},selectAll:function(e){var t=this._name,a=this._id;"function"!=typeof e&&(e=ly(e));for(var s=this._groups,r=s.length,n=[],l=[],i=0;i<r;++i)for(var o,c=s[i],d=c.length,u=0;u<d;++u)if(o=c[u]){for(var h,p=e.call(o,o.__data__,u,c),m=iL(o,a),x=0,g=p.length;x<g;++x)(h=p[x])&&iP(h,t,a,x,p,m);n.push(p),l.push(o)}return new o$(n,l,t,a)},selectChild:oC.selectChild,selectChildren:oC.selectChildren,filter:function(e){"function"!=typeof e&&(e=lj(e));for(var t=this._groups,a=t.length,s=Array(a),r=0;r<a;++r)for(var n,l=t[r],i=l.length,o=s[r]=[],c=0;c<i;++c)(n=l[c])&&e.call(n,n.__data__,c,l)&&o.push(n);return new o$(s,this._parents,this._name,this._id)},merge:function(e){if(e._id!==this._id)throw Error();for(var t=this._groups,a=e._groups,s=t.length,r=a.length,n=Math.min(s,r),l=Array(s),i=0;i<n;++i)for(var o,c=t[i],d=a[i],u=c.length,h=l[i]=Array(u),p=0;p<u;++p)(o=c[p]||d[p])&&(h[p]=o);for(;i<s;++i)l[i]=t[i];return new o$(l,this._parents,this._name,this._id)},selection:function(){return new oN(this._groups,this._parents)},transition:function(){for(var e=this._name,t=this._id,a=++oS,s=this._groups,r=s.length,n=0;n<r;++n)for(var l,i=s[n],o=i.length,c=0;c<o;++c)if(l=i[c]){var d=iL(l,t);iP(l,e,a,c,i,{time:d.time+d.delay+d.duration,delay:0,duration:d.duration,ease:d.ease})}return new o$(s,this._parents,e,a)},call:oC.call,nodes:oC.nodes,node:oC.node,size:oC.size,empty:oC.empty,each:oC.each,on:function(e,t){var a,s,r,n,l,i,o=this._id;return arguments.length<2?iL(this.node(),o).on.on(e):this.each((a=o,s=e,r=t,i=(s+"").trim().split(/^|\s+/).every(function(e){var t=e.indexOf(".");return t>=0&&(e=e.slice(0,t)),!e||"start"===e})?iR:iO,function(){var e=i(this,a),t=e.on;t!==n&&(l=(n=t).copy()).on(s,r),e.on=l}))},attr:function(e,t){var a=lO(e),s="transform"===a?iq:ow;return this.attrTween(e,"function"==typeof t?(a.local?function(e,t,a){var s,r,n;return function(){var l,i,o=a(this);return null==o?void this.removeAttributeNS(e.space,e.local):(l=this.getAttributeNS(e.space,e.local))===(i=o+"")?null:l===s&&i===r?n:(r=i,n=t(s=l,o))}}:function(e,t,a){var s,r,n;return function(){var l,i,o=a(this);return null==o?void this.removeAttribute(e):(l=this.getAttribute(e))===(i=o+"")?null:l===s&&i===r?n:(r=i,n=t(s=l,o))}})(a,s,iV(this,"attr."+e,t)):null==t?(a.local?function(e){return function(){this.removeAttributeNS(e.space,e.local)}}:function(e){return function(){this.removeAttribute(e)}})(a):(a.local?function(e,t,a){var s,r,n=a+"";return function(){var l=this.getAttributeNS(e.space,e.local);return l===n?null:l===s?r:r=t(s=l,a)}}:function(e,t,a){var s,r,n=a+"";return function(){var l=this.getAttribute(e);return l===n?null:l===s?r:r=t(s=l,a)}})(a,s,t))},attrTween:function(e,t){var a="attr."+e;if(arguments.length<2)return(a=this.tween(a))&&a._value;if(null==t)return this.tween(a,null);if("function"!=typeof t)throw Error();var s=lO(e);return this.tween(a,(s.local?function(e,t){var a,s;function r(){var r=t.apply(this,arguments);return r!==s&&(a=(s=r)&&function(t){this.setAttributeNS(e.space,e.local,r.call(this,t))}),a}return r._value=t,r}:function(e,t){var a,s;function r(){var r=t.apply(this,arguments);return r!==s&&(a=(s=r)&&function(t){this.setAttribute(e,r.call(this,t))}),a}return r._value=t,r})(s,t))},style:function(e,t,a){var s,r,n,l,i,o,c,d,u,h,p,m,x,g,f,b,_,v,y,j,w,N="transform"==(e+="")?iH:ow;return null==t?this.styleTween(e,(s=e,function(){var e=lI(this,s),t=(this.style.removeProperty(s),lI(this,s));return e===t?null:e===r&&t===n?l:l=N(r=e,n=t)})).on("end.style."+e,ok(e)):"function"==typeof t?this.styleTween(e,(i=e,o=iV(this,"style."+e,t),function(){var e=lI(this,i),t=o(this),a=t+"";return null==t&&(this.style.removeProperty(i),a=t=lI(this,i)),e===a?null:e===c&&a===d?u:(d=a,u=N(c=e,t))})).each((h=this._id,_="end."+(b="style."+(p=e)),function(){var e=iO(this,h),t=e.on,a=null==e.value[b]?f||(f=ok(p)):void 0;(t!==m||g!==a)&&(x=(m=t).copy()).on(_,g=a),e.on=x})):this.styleTween(e,(v=e,w=t+"",function(){var e=lI(this,v);return e===w?null:e===y?j:j=N(y=e,t)}),a).on("end.style."+e,null)},styleTween:function(e,t,a){var s="style."+(e+="");if(arguments.length<2)return(s=this.tween(s))&&s._value;if(null==t)return this.tween(s,null);if("function"!=typeof t)throw Error();return this.tween(s,function(e,t,a){var s,r;function n(){var n=t.apply(this,arguments);return n!==r&&(s=(r=n)&&function(t){this.style.setProperty(e,n.call(this,t),a)}),s}return n._value=t,n}(e,t,null==a?"":a))},text:function(e){var t,a;return this.tween("text","function"==typeof e?(t=iV(this,"text",e),function(){var e=t(this);this.textContent=null==e?"":e}):(a=null==e?"":e+"",function(){this.textContent=a}))},textTween:function(e){var t="text";if(arguments.length<1)return(t=this.tween(t))&&t._value;if(null==e)return this.tween(t,null);if("function"!=typeof e)throw Error();return this.tween(t,function(e){var t,a;function s(){var s=e.apply(this,arguments);return s!==a&&(t=(a=s)&&function(e){this.textContent=s.call(this,e)}),t}return s._value=e,s}(e))},remove:function(){var e;return this.on("end.remove",(e=this._id,function(){var t=this.parentNode;for(var a in this.__transition)if(+a!==e)return;t&&t.removeChild(this)}))},tween:function(e,t){var a=this._id;if(e+="",arguments.length<2){for(var s,r=iL(this.node(),a).tween,n=0,l=r.length;n<l;++n)if((s=r[n]).name===e)return s.value;return null}return this.each((null==t?function(e,t){var a,s;return function(){var r=iO(this,e),n=r.tween;if(n!==a){s=a=n;for(var l=0,i=s.length;l<i;++l)if(s[l].name===t){(s=s.slice()).splice(l,1);break}}r.tween=s}}:function(e,t,a){var s,r;if("function"!=typeof a)throw Error();return function(){var n=iO(this,e),l=n.tween;if(l!==s){r=(s=l).slice();for(var i={name:t,value:a},o=0,c=r.length;o<c;++o)if(r[o].name===t){r[o]=i;break}o===c&&r.push(i)}n.tween=r}})(a,e,t))},delay:function(e){var t=this._id;return arguments.length?this.each(("function"==typeof e?function(e,t){return function(){iR(this,e).delay=+t.apply(this,arguments)}}:function(e,t){return t*=1,function(){iR(this,e).delay=t}})(t,e)):iL(this.node(),t).delay},duration:function(e){var t=this._id;return arguments.length?this.each(("function"==typeof e?function(e,t){return function(){iO(this,e).duration=+t.apply(this,arguments)}}:function(e,t){return t*=1,function(){iO(this,e).duration=t}})(t,e)):iL(this.node(),t).duration},ease:function(e){var t=this._id;return arguments.length?this.each(function(e,t){if("function"!=typeof t)throw Error();return function(){iO(this,e).ease=t}}(t,e)):iL(this.node(),t).ease},easeVarying:function(e){var t;if("function"!=typeof e)throw Error();return this.each((t=this._id,function(){var a=e.apply(this,arguments);if("function"!=typeof a)throw Error();iO(this,t).ease=a}))},end:function(){var e,t,a=this,s=a._id,r=a.size();return new Promise(function(n,l){var i={value:l},o={value:function(){0==--r&&n()}};a.each(function(){var a=iO(this,s),r=a.on;r!==e&&((t=(e=r).copy())._.cancel.push(i),t._.interrupt.push(i),t._.end.push(o)),a.on=t}),0===r&&n()})},[Symbol.iterator]:oC[Symbol.iterator]};var oM={time:null,delay:0,duration:250,ease:function(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}};l4.prototype.interrupt=function(e){return this.each(function(){iI(this,e)})},l4.prototype.transition=function(e){var t,a;e instanceof o$?(t=e._id,e=e._name):(t=++oS,(a=oM).time=iN(),e=null==e?null:e+"");for(var s=this._groups,r=s.length,n=0;n<r;++n)for(var l,i=s[n],o=i.length,c=0;c<o;++c)(l=i[c])&&iP(l,e,t,c,i,a||function(e,t){for(var a;!(a=e.__transition)||!(a=a[t]);)if(!(e=e.parentNode))throw Error(`transition ${t} not found`);return a}(l,t));return new o$(s,this._parents,e,t)};let oE=e=>()=>e;function oA(e,{sourceEvent:t,target:a,transform:s,dispatch:r}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},target:{value:a,enumerable:!0,configurable:!0},transform:{value:s,enumerable:!0,configurable:!0},_:{value:r}})}function oT(e,t,a){this.k=e,this.x=t,this.y=a}oT.prototype={constructor:oT,scale:function(e){return 1===e?this:new oT(this.k*e,this.x,this.y)},translate:function(e,t){return 0===e&0===t?this:new oT(this.k,this.x+this.k*e,this.y+this.k*t)},apply:function(e){return[e[0]*this.k+this.x,e[1]*this.k+this.y]},applyX:function(e){return e*this.k+this.x},applyY:function(e){return e*this.k+this.y},invert:function(e){return[(e[0]-this.x)/this.k,(e[1]-this.y)/this.k]},invertX:function(e){return(e-this.x)/this.k},invertY:function(e){return(e-this.y)/this.k},rescaleX:function(e){return e.copy().domain(e.range().map(this.invertX,this).map(e.invert,e))},rescaleY:function(e){return e.copy().domain(e.range().map(this.invertY,this).map(e.invert,e))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}};var oF=new oT(1,0,0);function oP(e){for(;!e.__zoom;)if(!(e=e.parentNode))return oF;return e.__zoom}function oR(e){e.stopImmediatePropagation()}function oO(e){e.preventDefault(),e.stopImmediatePropagation()}function oL(e){return(!e.ctrlKey||"wheel"===e.type)&&!e.button}function oI(){var e=this;return e instanceof SVGElement?(e=e.ownerSVGElement||e).hasAttribute("viewBox")?[[(e=e.viewBox.baseVal).x,e.y],[e.x+e.width,e.y+e.height]]:[[0,0],[e.width.baseVal.value,e.height.baseVal.value]]:[[0,0],[e.clientWidth,e.clientHeight]]}function oD(){return this.__zoom||oF}function oz(e){return-e.deltaY*(1===e.deltaMode?.05:e.deltaMode?
vendor: 5,851 bytes, line 10
101:.002)*(e.ctrlKey?10:1)}function oB(){return navigator.maxTouchPoints||"ontouchstart"in this}function oW(e,t,a){var s=e.invertX(t[0][0])-a[0][0],r=e.invertX(t[1][0])-a[1][0],n=e.invertY(t[0][1])-a[0][1],l=e.invertY(t[1][1])-a[1][1];return e.translate(r>s?(s+r)/2:Math.min(0,s)||Math.max(0,r),l>n?(n+l)/2:Math.min(0,n)||Math.max(0,l))}function oU(){var e,t,a,s=oL,r=oI,n=oW,l=oz,i=oB,o=[0,1/0],c=[[-1/0,-1/0],[1/0,1/0]],d=250,u=ih,h=lx("start","zoom","end"),p=0,m=10;function x(e){e.property("__zoom",oD).on("wheel.zoom",j,{passive:!1}).on("mousedown.zoom",w).on("dblclick.zoom",N).filter(i).on("touchstart.zoom",k).on("touchmove.zoom",S).on("touchend.zoom touchcancel.zoom",$).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function g(e,t){return(t=Math.max(o[0],Math.min(o[1],t)))===e.k?e:new oT(t,e.x,e.y)}function f(e,t,a){var s=t[0]-a[0]*e.k,r=t[1]-a[1]*e.k;return s===e.x&&r===e.y?e:new oT(e.k,s,r)}function b(e){return[(+e[0][0]+ +e[1][0])/2,(+e[0][1]+ +e[1][1])/2]}function _(e,t,a,s){e.on("start.zoom",function(){v(this,arguments).event(s).start()}).on("interrupt.zoom end.zoom",function(){v(this,arguments).event(s).end()}).tween("zoom",function(){var e=arguments,n=v(this,e).event(s),l=r.apply(this,e),i=null==a?b(l):"function"==typeof a?a.apply(this,e):a,o=Math.max(l[1][0]-l[0][0],l[1][1]-l[0][1]),c=this.__zoom,d="function"==typeof t?t.apply(this,e):t,h=u(c.invert(i).concat(o/c.k),d.invert(i).concat(o/d.k));return function(e){if(1===e)e=d;else{var t=h(e),a=o/t[2];e=new oT(a,i[0]-t[0]*a,i[1]-t[1]*a)}n.zoom(null,e)}})}function v(e,t,a){return!a&&e.__zooming||new y(e,t)}function y(e,t){this.that=e,this.args=t,this.active=0,this.sourceEvent=null,this.extent=r.apply(e,t),this.taps=0}function j(e,...t){if(s.apply(this,arguments)){var a=v(this,t).event(e),r=this.__zoom,i=Math.max(o[0],Math.min(o[1],r.k*Math.pow(2,l.apply(this,arguments)))),d=l6(e);if(a.wheel)(a.mouse[0][0]!==d[0]||a.mouse[0][1]!==d[1])&&(a.mouse[1]=r.invert(a.mouse[0]=d)),clearTimeout(a.wheel);else{if(r.k===i)return;a.mouse=[d,r.invert(d)],iI(this),a.start()}oO(e),a.wheel=setTimeout(function(){a.wheel=null,a.end()},150),a.zoom("mouse",n(f(g(r,i),a.mouse[0],a.mouse[1]),a.extent,c))}}function w(e,...t){if(!a&&s.apply(this,arguments)){var r=e.currentTarget,l=v(this,t,!0).event(e),i=l3(e.view).on("mousemove.zoom",function(e){if(oO(e),!l.moved){var t=e.clientX-d,a=e.clientY-u;l.moved=t*t+a*a>p}l.event(e).zoom("mouse",n(f(l.that.__zoom,l.mouse[0]=l6(e,r),l.mouse[1]),l.extent,c))},!0).on("mouseup.zoom",function(e){i.on("mousemove.zoom mouseup.zoom",null),ia(e.view,l.moved),oO(e),l.event(e).end()},!0),o=l6(e,r),d=e.clientX,u=e.clientY;it(e.view),oR(e),l.mouse=[o,this.__zoom.invert(o)],iI(this),l.start()}}function N(e,...t){if(s.apply(this,arguments)){var a=this.__zoom,l=l6(e.changedTouches?e.changedTouches[0]:e,this),i=a.invert(l),o=a.k*(e.shiftKey?.5:2),u=n(f(g(a,o),l,i),r.apply(this,t),c);oO(e),d>0?l3(this).transition().duration(d).call(_,u,l,e):l3(this).call(x.transform,u,l,e)}}function k(a,...r){if(s.apply(this,arguments)){var n,l,i,o,c=a.touches,d=c.length,u=v(this,r,a.changedTouches.length===d).event(a);for(oR(a),l=0;l<d;++l)o=[o=l6(i=c[l],this),this.__zoom.invert(o),i.identifier],u.touch0?u.touch1||u.touch0[2]===o[2]||(u.touch1=o,u.taps=0):(u.touch0=o,n=!0,u.taps=1+!!e);e&&(e=clearTimeout(e)),n&&(u.taps<2&&(t=o[0],e=setTimeout(function(){e=null},500)),iI(this),u.start())}}function S(e,...t){if(this.__zooming){var a,s,r,l,i=v(this,t).event(e),o=e.changedTouches,d=o.length;for(oO(e),a=0;a<d;++a)r=l6(s=o[a],this),i.touch0&&i.touch0[2]===s.identifier?i.touch0[0]=r:i.touch1&&i.touch1[2]===s.identifier&&(i.touch1[0]=r);if(s=i.that.__zoom,i.touch1){var u=i.touch0[0],h=i.touch0[1],p=i.touch1[0],m=i.touch1[1],x=(x=p[0]-u[0])*x+(x=p[1]-u[1])*x,b=(b=m[0]-h[0])*b+(b=m[1]-h[1])*b;s=g(s,Math.sqrt(x/b)),r=[(u[0]+p[0])/2,(u[1]+p[1])/2],l=[(h[0]+m[0])/2,(h[1]+m[1])/2]}else{if(!i.touch0)return;r=i.touch0[0],l=i.touch0[1]}i.zoom("touch",n(f(s,r,l),i.extent,c))}}function $(e,...s){if(this.__zooming){var r,n,l=v(this,s).event(e),i=e.changedTouches,o=i.length;for(oR(e),a&&clearTimeout(a),a=setTimeout(function(){a=null},500),r=0;r<o;++r)n=i[r],l.touch0&&l.touch0[2]===n.identifier?delete l.touch0:l.touch1&&l.touch1[2]===n.identifier&&delete l.touch1;if(l.touch1&&!l.touch0&&(l.touch0=l.touch1,delete l.touch1),l.touch0)l.touch0[1]=this.__zoom.invert(l.touch0[0]);else if(l.end(),2===l.taps&&(n=l6(n,this),Math.hypot(t[0]-n[0],t[1]-n[1])<m)){var c=l3(this).on("dblclick.zoom");c&&c.apply(this,arguments)}}}return x.transform=function(e,t,a,s){var r=e.selection?e.selection():e;r.property("__zoom",oD),e!==r?_(e,t,a,s):r.interrupt().each(function(){v(this,arguments).event(s).start().zoom(null,"function"==typeof t?t.apply(this,arguments):t).end()})},x.scaleBy=function(e,t,a,s){x.scaleTo(e,function(){var e=this.__zoom.k,a="function"==typeof t?t.apply(this,arguments):t;return e*a},a,s)},x.scaleTo=function(e,t,a,s){x.transform(e,function(){var e=r.apply(this,arguments),s=this.__zoom,l=null==a?b(e):"function"==typeof a?a.apply(this,arguments):a,i=s.invert(l),o="function"==typeof t?t.apply(this,arguments):t;return n(f(g(s,o),l,i),e,c)},a,s)},x.translateBy=function(e,t,a,s){x.transform(e,function(){return n(this.__zoom.translate("function"==typeof t?t.apply(this,arguments):t,"function"==typeof a?a.apply(this,arguments):a),r.apply(this,arguments),c)},null,s)},x.translateTo=function(e,t,a,s,l){x.transform(e,function(){var e=r.apply(this,arguments),l=this.__zoom,i=null==s?b(e):"function"==typeof s?s.apply(this,arguments):s;return n(oF.translate(i[0],i[1]).scale(l.k).translate("function"==typeof t?-t.apply(this,arguments):-t,"function"==typeof a?-a.apply(this,arguments):-a),e,c)},s,l)},y.prototype={event:function(e){return e&&(this.sourceEvent=e),this},start:function(){return 1==++this.active&&(this.that.__zooming=this,this.emit
10("start")),this},zoom:function(e,t){return this.mouse&&"mouse"!==e&&(this.mouse[1]=t.invert(this.mouse[0])),this.touch0&&"touch"!==e&&(this.touch0[1]=t.invert(this.touch0[0])),this.touch1&&"touch"!==e&&(this.touch1[1]=t.invert(this.touch1[0])),this.that.__zoom=t,this.emit("zoom"),this},end:function(){return 0==--this.active&&(delete this.that.__zooming,this.emit("end")),this},emit:function(e){var t=l3(this.that).datum();h.call(e,this.that,new oA(e,{sourceEvent:this.sourceEvent,target:x,type:e,transform:this.that.__zoom,dispatch:h}),t)}},x.wheelDelta=function(e){return arguments.length?(l="function"==typeof e?e:oE(+e),x):l},x.filter=function(e){return arguments.length?(s="function"==typeof e?e:oE(!!e),x):s},x.touchable=function(e){return arguments.length?(i="function"==typeof e?e:oE(!!e),x):i},x.extent=function(e){return arguments.length?(r="function"==typeof e?e:oE([[+e[0][0],+e[0][1]],[+e[1][0],+e[1][1]]]),x):r},x.scaleExtent=function(e){return arguments.length?(o[0]=+e[0],o[1]=+e[1],x):[o[0],o[1]]},x.translateExtent=function(e){return arguments.length?(c[0][0]=+e[0][0],c[1][0]=+e[1][0],c[0][1]=+e[0][1],c[1][1]=+e[1][1],x):[[c[0][0],c[0][1]],[c[1][0],c[1][1]]]},x.constrain=function(e){return arguments.length?(n=e,x):n},x.duration=function(e){return arguments.length?(d=+e,x):d},x.interpolate=function(e){return arguments.length?(u=e,x):u},x.on=function(){var e=h.on.apply(h,arguments);return e===h?x:e},x.clickDistance=function(e){return arguments.length?(p=(e*=1)*e,x):Math.sqrt(p)},x.tapDistance=function(e){return arguments.length?(m=+e,x):m},x}function oH(e,t){var a,s,r=typeof t;return null==t||"boolean"===r?og(t):("number"===r?iD:"string"===r?(s=i7(t))?(t=s,ob):oj:t instanceof i7?ob:t instanceof Date?function(e,t){var a=new Date;return e*=1,t*=1,function(s){return a.setTime(e*(1-s)+t*s),a}}:!ArrayBuffer.isView(a=t)||a instanceof DataView?Array.isArray(t)?function(e,t){var a,s=t?t.length:0,r=e?Math.min(s,e.length):0,n=Array(r),l=Array(s);for(a=0;a<r;++a)n[a]=oH(e[a],t[a]);for(;a<s;++a)l[a]=t[a];return function(e){for(a=0;a<r;++a)l[a]=n[a](e);return l}}:"function"!=typeof t.valueOf&&"function"!=typeof t.toString||isNaN(t)?function(e,t){var a,s={},r={};for(a in(null===e||"object"!=typeof e)&&(e={}),(null===t||"object"!=typeof t)&&(t={}),t)a in e?s[a]=oH(e[a],t[a]):r[a]=t[a];return function(e){for(a in s)r[a]=s[a](e);return r}}:iD:function(e,t){t||(t=[]);var a,s=e?Math.min(t.length,e.length):0,r=t.slice();return function(n){for(a=0;a<s;++a)r[a]=e[a]*(1-n)+t[a]*n;return r}})(e,t)}oP.prototype=oT.prototype;let oq=[[-1/0,-1/0],[1/0,1/0]],oV=["Enter"," ","Escape"],oG={"node.a11yDescription.default":"Press enter or space to select a node. Press delete to remove it and escape to cancel.","node.a11yDescription.keyboardDisabled":"Press enter or space to select a node. You can then use the arrow keys to move the node around. Press delete to remove it and escape to cancel.","node.a11yDescription.ariaLiveMessage":({direction:e,x:t,y:a})=>`Moved selected node ${e}. New position, x: ${t}, y: ${a}`,"edge.a11yDescription.default":"Press enter or space to select an edge. You can then press delete to remove it or escape to cancel.","controls.ariaLabel":"Control Panel","controls.zoomIn.ariaLabel":"Zoom In","controls.zoomOut.ariaLabel":"Zoom Out","controls.fitView.ariaLabel":"Fit View","controls.interactive.ariaLabel":"Toggle Interactivity","minimap.ariaLabel":"Mini Map","handle.ariaLabel":"Handle"};(t=d||(d={})).Strict="strict",t.Loose="loose",(a=u||(u={})).Free="free",a.Vertical="vertical",a.Horizontal="horizontal",(s=h||(h={}
10)).Partial="partial",s.Full="full";let oJ={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};(r=p||(p={})).Bezier="default",r.Straight="straight",r.Step="step",r.SmoothStep="smoothstep",r.SimpleBezier="simplebezier",(n=m||(m={})).Arrow="arrow",n.ArrowClosed="arrowclosed",(l=x||(x={})).Left="left",l.Top="top",l.Right="right",l.Bottom="bottom";let oY={[x.Left]:x.Right,[x.Right]:x.Left,[x.Top]:x.Bottom,[x.Bottom]:x.Top};function oK(e){return null===e?null:e?"valid":"invalid"}let oX=e=>"id"in e&&"source"in e&&"target"in e,oZ=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),oQ=(e,t=[0,0])=>{let{width:a,height:s}=cf(e),r=e.origin??t,n=a*r[0],l=s*r[1];return{x:e.position.x-n,y:e.position.y-l}},o0=(e,t={})=>{let a={x:1/0,y:1/0,x2:-1/0,y2:-1/0},s=!1;return e.forEach(e=>{(void 0===t.filter||t.filter(e))&&(a=ce(a,cr(e)),s=!0)}),s?ca(a):{x:0,y:0,width:0,height:0}},o1=(e,t,[a,s,r]=[0,0,1],n=!1,l=!1)=>{let i={...cu(t,[a,s,r]),width:t.width/r,height:t.height/r},o=[];for(let t of e.values()){let{measured:e,selectable:a=!0,hidden:s=!1}=t;if(l&&!a||s)continue;let r=e.width??t.width??t.initialWidth??null,c=e.height??t.height??t.initialHeight??null,d=cl(i,cs(t)),u=(r??0)*(c??0),h=n&&d>0;(!t.internals.handleBounds||h||d>=u||t.dragging)&&o.push(t)}return o};async function o2({nodes:e,width:t,height:a,panZoom:s,minZoom:r,maxZoom:n},l){let i,o;if(0===e.size)return!0;let c=cm(o0((i=new Map,o=l?.nodes?new Set(l.nodes.map(e=>e.id)):null,e.forEach(e=>{e.measured.width&&e.measured.height&&(l?.includeHiddenNodes||!e.hidden)&&(!o||o.has(e.id))&&i.set(e.id,e)}),i)),t,a,l?.minZoom??r,l?.maxZoom??n,l?.padding??.1);return await s.setViewport(c,{duration:l?.duration,ease:l?.ease,interpolate:l?.interpolate}),!0}function o5({nodeId:e,nextPosition:t,nodeLookup:a,nodeOrigin:s=[0,0],nodeExtent:r,onError:n}){let l=a.get(e),i=l.parentId?a.get(l.parentId):void 0,{x:o,y:c}=i?i.internals.positionAbsolute:{x:0,y:0},d=l.origin??s,u=l.extent||r;if("parent"!==l.extent||l.expandParent)i&&cg(l.extent)&&(u=[[l.extent[0][0]+o,l.extent[0][1]+c],[l.extent[1][0]+o,l.extent[1][1]+c]]);else if(i){let e=i.measured.width,t=i.measured.height;e&&t&&(u=[[o,c],[o+e,c+t]])}else n?.("005","Only child nodes can use a parent extent.");let h=cg(u)?o6(t,u,l.measured):t;return(void 0===l.measured.width||void 0===l.measured.height)&&n?.("015","It seems that you are trying to drag a node that is not initialized. Please use onNodesChange as explained in the docs."),{position:{x:h.x-o+(l.measured.width??0)*d[0],y:h.y-c+(l.measured.height??0)*d[1]},positionAbsolute:h}}async function o4({nodesToRemove:e=[],edgesToRemove:t=[],nodes:a,edges:s,onBeforeDelete:r}){let n,l=new Set(e.map(e=>e.id)),i=[];for(let e of a){if(!1===e.deletable)continue;let t=l.has(e.id),a=!t&&e.parentId&&i.find(t=>t.id===e.parentId);(t||a)&&i.push(e)}let o=new Set(t.map(e=>e.id)),c=s.filter(e=>!1!==e.deletable),d=(n=new Set,i.forEach(e=>{n.add(e.id)}),c.filter(e=>n.has(e.source)||n.has(e.target)));for(let e of c)o.has(e.id)&&!d.find(t=>t.id===e.id)&&d.push(e);if(!r)return{edges:d,nodes:i};let u=await r({nodes:i,edges:d});return"boolean"==typeof u?u?{edges:d,nodes:i}:{edges:[],nodes:[]}:u}let o3=(e,t=0,a=1)=>Math.min(Math.max(e,t),a),o6=(e={x:0,y:0},t,a)=>({x:o3(e.x,t[0][0],t[1][0]-(a?.width??0)),y:o3(e.y,t[0][1],t[1][1]-(a?.height??0))});function o8(e,t,a){let{width:s,height:r}=cf(a),{x:n,y:l}=a.internals.positionAbsolute;return o6(e,[[n,l],[n+s,l+r]],t)}let o9=(e,t,a)=>e<t?o3(Math.abs(e-t),1,t)/t:e>a?-o3(Math.abs(e-a),1,t)/t:0,o7=(e,t,a=15,s=40)=>[o9(e.x,s,t.width-s)*a,o9(e.y,s,t.height-s)*a],ce=(e,t)=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x2,t.x2),y2:Math.max(e.y2,t.y2)}),ct=({x:e,y:t,width:a,height:s})=>({x:e,y:t,x2:e+a,y2:t+s}),ca=({x:e,y:t,x2:a,y2:s})=>({x:e,y:t,width:a-e,height:s-t}),cs=(e,t=[0,0])=>{let{x:a,y:s}=oZ(e)?e.internals.positionAbsolute:oQ(e,t);return{x:a,y:s,width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}},cr=(e,t=[0,0])=>{let{x:a,y:s}=oZ(e)?e.internals.positionAbsolute:oQ(e,t);return{x:a,y:s,x2:a+(e.measured?.width??e.width??e.initialWidth??0),y2:s+(e.measured?.height??e.height??e.initialHeight??0)}},cn=(e,t)=>ca(ce(ct(e),ct(t))),cl=(e,t)=>Math.ceil(Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x))*Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y))),ci=e=>co(e.width)&&co(e.height)&&co(e.x)&&co(e.y),co=e=>!isNaN(e)&&isFinite(e),cc=(e,t)=>(e,t)=>{},cd=(e,t=[1,1])=>
10({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),cu=({x:e,y:t},[a,s,r],n=!1,l=[1,1])=>{let i={x:(e-a)/r,y:(t-s)/r};return n?cd(i,l):i},ch=({x:e,y:t},[a,s,r])=>({x:e*r+a,y:t*r+s});function cp(e,t){if("number"==typeof e)return Math.floor((t-t/(1+e))*.5);if("string"==typeof e&&e.endsWith("px")){let t=parseFloat(e);if(!Number.isNaN(t))return Math.floor(t)}if("string"==typeof e&&e.endsWith("%")){let a=parseFloat(e);if(!Number.isNaN(a))return Math.floor(t*a*.01)}return console.error(`The padding value "${e}" is invalid. Please provide a number or a string with a valid unit (px or %).`),0}let cm=(e,t,a,s,r,n)=>{let l=function(e,t,a){if("string"==typeof e||"number"==typeof e){let s=cp(e,a),r=cp(e,t);return{top:s,right:r,bottom:s,left:r,x:2*r,y:2*s}}if("object"==typeof e){let s=cp(e.top??e.y??0,a),r=cp(e.bottom??e.y??0,a),n=cp(e.left??e.x??0,t),l=cp(e.right??e.x??0,t);return{top:s,right:l,bottom:r,left:n,x:n+l,y:s+r}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}(n,t,a),i=o3(Math.min((t-l.x)/e.width,(a-l.y)/e.height),s,r),o=e.x+e.width/2,c=e.y+e.height/2,d=t/2-o*i,u=a/2-c*i,h=function(e,t,a,s,r,n){let{x:l,y:i}=ch(e,[t,a,s]),{x:o,y:c}=ch({x:e.x+e.width,y:e.y+e.height},[t,a,s]);return{left:Math.floor(l),top:Math.floor(i),right:Math.floor(r-o),bottom:Math.floor(n-c)}}(e,d,u,i,t,a),p={left:Math.min(h.left-l.left,0),top:Math.min(h.top-l.top,0),right:Math.min(h.right-l.right,0),bottom:Math.min(h.bottom-l.bottom,0)};return{x:d-p.left+p.right,y:u-p.top+p.bottom,zoom:i}},cx=()=>"u">typeof navigator&&navigator?.userAgent?.indexOf("Mac")>=0;function cg(e){return null!=e&&"parent"!==e}function cf(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function cb(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function c_(e,t={width:0,height:0},a,s,r){let n={...e},l=s.get(a);if(l){let e=l.origin||r;n.x+=l.internals.positionAbsolute.x-(t.width??0)*e[0],n.y+=l.internals.positionAbsolute.y-(t.height??0)*e[1]}return n}function cv(e,t){if(e.size!==t.size)return!1;for(let a of e)if(!t.has(a))return!1;return!0}function cy(e,{snapGrid:t=[0,0],snapToGrid:a=!1,transform:s,containerBounds:r}){let{x:n,y:l}=cS(e),i=cu({x:n-(r?.left??0),y:l-(r?.top??0)},s),{x:o,y:c}=a?cd(i,t):i;return{xSnapped:o,ySnapped:c,...i}}let cj=e=>({width:e.offsetWidth,height:e.offsetHeight}),cw=e=>e?.getRootNode?.()||window?.document,cN=["INPUT","SELECT","TEXTAREA"];function ck(e){let t=e.composedPath?.()?.[0]||e.target;return t?.nodeType===1&&(cN.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".
10nokey"))}let cS=(e,t)=>{let a="clientX"in e,s=a?e.clientX:e.touches?.[0].clientX,r=a?e.clientY:e.touches?.[0].clientY;return{x:s-(t?.left??0),y:r-(t?.top??0)}},c$=(e,t,a,s,r)=>{let n=t.querySelectorAll(`.${e}`);return n&&n.length?Array.from(n).map(t=>{let n=t.getBoundingClientRect();return{id:t.getAttribute("data-handleid"),type:e,nodeId:r,position:t.getAttribute("data-handlepos"),x:(n.left-a.left)/s,y:(n.top-a.top)/s,...cj(t)}}):null};function cC({sourceX:e,sourceY:t,targetX:a,targetY:s,sourceControlX:r,sourceControlY:n,targetControlX:l,targetControlY:i}){let o=.125*e+.375*r+.375*l+.125*a,c=.125*t+.375*n+.375*i+.125*s,d=Math.abs(o-e),u=Math.abs(c-t);return[o,c,d,u]}function cM(e,t){return e>=0?.5*e:25*t*Math.sqrt(-e)}function cE({pos:e,x1:t,y1:a,x2:s,y2:r,c:n}){switch(e){case x.Left:return[t-cM(t-s,n),a];case x.Right:return[t+cM(s-t,n),a];case x.Top:return[t,a-cM(a-r,n)];case x.Bottom:return[t,a+cM(r-a,n)]}}function cA({sourceX:e,sourceY:t,sourcePosition:a=x.Bottom,targetX:s,targetY:r,targetPosition:n=x.Top,curvature:l=.25}){let[i,o]=cE({pos:a,x1:e,y1:t,x2:s,y2:r,c:l}),[c,d]=cE({pos:n,x1:s,y1:r,x2:e,y2:t,c:l}),[u,h,p,m]=cC({sourceX:e,sourceY:t,targetX:s,targetY:r,sourceControlX:i,sourceControlY:o,targetControlX:c,targetControlY:d});return[`M${e},${t} C${i},${o} ${c},${d} ${s},${r}`,u,h,p,m]}function cT({sourceX:e,sourceY:t,targetX:a,targetY:s}){let r=Math.abs(a-e)/2,n=Math.abs(s-t)/2;return[a<e?a+r:a-r,s<t?s+n:s-n,r,n]}let cF=({source:e,sourceHandle:t,target:a,targetHandle:s})=>`xy-edge__${e}${t||""}-${a}${s||""}`;function cP({sourceX:e,sourceY:t,targetX:a,targetY:s}){let[r,n,l,i]=cT({sourceX:e,sourceY:t,targetX:a,targetY:s});return[`M ${e},${t}L ${a},${s}`,r,n,l,i]}let cR={[x.Left]:{x:-1,y:0},[x.Right]:{x:1,y:0},[x.Top]:{x:0,y:-1},[x.Bottom]:{x:0,y:1}},cO=({source:e,sourcePosition:t=x.Bottom,target:a})=>t===x.Left||t===x.Right?e.x<a.x?{x:1,y:0}:{x:-1,y:0}:e.y<a.y?{x:0,y:1}:{x:0,y:-1},cL=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function cI({sourceX:e,sourceY:t,sourcePosition:a=x.Bottom,targetX:s,targetY:r,targetPosition:n=x.Top,borderRadius:l=5,centerX:i,centerY:o,offset:c=20,stepPosition:d=.5}){let[u,h,p,m,g]=function({source:e,sourcePosition:t=x.Bottom,target:a,targetPosition:s=x.Top,center:r,offset:n,stepPosition:l}){let i,o,c=cR[t],d=cR[s],u={x:e.x+c.x*n,y:e.y+c.y*n},h={x:a.x+d.x*n,y:a.y+d.y*n},p=cO({source:u,sourcePosition:t,target:h}),m=0!==p.x?"x":"y",g=p[m],f=[],b={x:0,y:0},_={x:0,y:0},[,,v,y]=cT({sourceX:e.x,sourceY:e.y,targetX:a.x,targetY:a.y});if(c[m]*d[m]==-1){"x"===m?(i=r.x??u.x+(h.x-u.x)*l,o=r.y??(u.y+h.y)/2):(i=r.x??(u.x+h.x)/2,o=r.y??u.y+(h.y-u.y)*l);let e=[{x:i,y:u.y},{x:i,y:h.y}],t=[{x:u.x,y:o},{x:h.x,y:o}];f=c[m]===g?"x"===m?e:t:"x"===m?t:e}else{let r=[{x:u.x,y:h.y}],l=[{x:h.x,y:u.y}];if(f="x"===m?c.x===g?l:r:c.y===g?r:l,t===s){let t=Math.abs(e[m]-a[m]);if(t<=n){let s=Math.min(n-1,n-t);c[m]===g?b[m]=(u[m]>e[m]?-1:1)*s:_[m]=(h[m]>a[m]?-1:1)*s}}if(t!==s){let e="x"===m?"y":"x",t=c[m]===d[e],a=u[e]>h[e],s=u[e]<h[e];(1===c[m]&&(!t&&a||t&&s)||1!==c[m]&&(!t&&s||t&&a))&&(f="x"===m?r:l)}let p={x:u.x+b.x,y:u.y+b.y},x={x:h.x+_.x,y:h.y+_.y};Math.max(Math.abs(p.x-f[0].x),Math.abs(x.x-f[0].x))>=Math.max(Math.abs(p.y-f[0].y),Math.abs(x.y-f[0].y))?(i=(p.x+x.x)/2,o=f[0].y):(i=f[0].x,o=(p.y+x.y)/2)}let j={x:u.x+b.x,y:u.y+b.y},w={x:h.x+_.x,y:h.y+_.y};return[[e,...j.x!==f[0].x||j.y!==f[0].y?[j]:[],...f,...w.x!==f[f.length-1].x||w.y!==f[f.length-1].y?[w]:[],a],i,o,v,y]}({source:{x:e,y:t},sourcePosition:a,target:{x:s,y:r},targetPosition:n,center:{x:i,y:o},offset:c,stepPosition:d}),f=`M${u[0].x} ${u[0].y}`;for(let e=1;e<u.length-1;e++)f+=function(e,t,a,s){let r=Math.min(cL(e,t)/2,cL(t,a)/2,s),{x:n,y:l}=t;if(e.x===n&&n===a.x||e.y===l&&l===a.y)return`L${n} ${l}`;if(e.y===l){let t=e.x<a.x?-1:1,s=e.y<a.y?1:-1;return`L ${n+r*t},${l}Q ${n},${l} ${n},${l+r*s}`}let i=e.x<a.x?1:-1,o=e.y<a.y?-1:1;return`L ${n},${l+r*o}Q ${n},${l} ${n+r*i},${l}`}(u[e-1],u[e],u[e+1],l);return[f+=`L${u[u.length-1].x} ${u[u.length-1].y}`,h,p,m,g]}function cD(e){return e&&!!(e.internals.handleBounds||e.handles?.length)&&!!(e.measured.width||e.width||e.initialWidth)}function cz(e){if(!e)return null;let t=[],a=[];for(let s of e)s.width=s.width??1,s.height=s.height??1,"source"===s.type?t.push(s):"target"===s.type&&a.push(s);return{source:t,target:a}}function cB(e,t,a=x.Left,s=!1){let r=(t?.x??0)+e.internals.positionAbsolute.x,n=(t?.y??0)+e.internals.positionAbsolute.y,{width:l,height:i}=t??cf(e);
10if(s)return{x:r+l/2,y:n+i/2};switch(t?.position??a){case x.Top:return{x:r+l/2,y:n};case x.Right:return{x:r+l,y:n+i/2};case x.Bottom:return{x:r+l/2,y:n+i};case x.Left:return{x:r,y:n+i/2}}}function cW(e,t){return e&&(t?e.find(e=>e.id===t):e[0])||null}function cU(e,t){if(!e)return"";if("string"==typeof e)return e;let a=t?`${t}__`:"";return`${a}${Object.keys(e).sort().map(t=>`${t}=${e[t]}`).join("&")}`}let cH={nodeOrigin:[0,0],nodeExtent:oq,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},cq={...cH,checkEquality:!0};function cV(e,t){let a={...e};for(let e in t)void 0!==t[e]&&(a[e]=t[e]);return a}function cG(e){return"manual"===e}function cJ(e,t,a,s={}){let r=cV(cq,s),n={i:0},l=new Map(t),i=r?.elevateNodesOnSelect&&!cG(r.zIndexMode)?1e3:0,o=e.length>0,c=!1;for(let d of(t.clear(),a.clear(),e)){let e=l.get(d.id);if(r.checkEquality&&d===e?.internals.userNode)t.set(d.id,e);else{let a=o6(oQ(d,r.nodeOrigin),cg(d.extent)?d.extent:r.nodeExtent,cf(d));e={...r.defaults,...d,measured:{width:d.measured?.width,height:d.measured?.height},internals:{positionAbsolute:a,handleBounds:function(e,t){if(!e.handles)return e.measured?t?.internals.handleBounds:void 0;let a=[],s=[];for(let t of e.handles){let r={id:t.id,width:t.width??1,height:t.height??1,nodeId:e.id,x:t.x,y:t.y,position:t.position,type:t.type};"source"===t.type?a.push(r):"target"===t.type&&s.push(r)}return{source:a,target:s}}(d,e),z:cK(d,i,r.zIndexMode),userNode:d}},t.set(d.id,e)}void 0!==e.measured&&void 0!==e.measured.width&&void 0!==e.measured.height||e.hidden||(o=!1),d.parentId&&cY(e,t,a,s,n),c||=d.selected??!1}return{nodesInitialized:o,hasSelectedNodes:c}}function cY(e,t,a,s,r){let{elevateNodesOnSelect:n,nodeOrigin:l,nodeExtent:i,zIndexMode:o}=cV(cH,s),c=e.parentId,d=t.get(c);if(!d)return void console.warn(`Parent node ${c} not found. Please make sure that parent nodes are in front of their child nodes in the nodes array.`);!function(e,t){if(!e.parentId)return;let a=t.get(e.parentId);a?a.set(e.id,e):t.set(e.parentId,new Map([[e.id,e]]))}(e,a),r&&!d.parentId&&void 0===d.internals.rootParentIndex&&"auto"===o&&(d.internals.rootParentIndex=++r.i,d.internals.z=d.internals.z+10*r.i),r&&void 0!==d.internals.rootParentIndex&&(r.i=d.internals.rootParentIndex);let{x:u,y:h,z:p}=function(e,t,a,s,r,n){let{x:l,y:i}=t.internals.positionAbsolute,o=cf(e),c=oQ(e,a),d=cg(e.extent)?o6(c,e.extent,o):c,u=o6({x:l+d.x,y:i+d.y},s,o);"parent"===e.extent&&(u=o8(u,o,t));let h=cK(e,r,n),p=t.internals.z??0;return{x:u.x,y:u.y,z:p>=h?p+1:h}}(e,d,l,i,n&&!cG(o)?1e3:0,o),{positionAbsolute:m}=e.internals,x=u!==m.x||h!==m.y;(x||p!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:x?{x:u,y:h}:m,z:p}})}function cK(e,t,a){let s=co(e.zIndex)?e.zIndex:0;return cG(a)?s:s+(e.selected?t:0)}function cX(e,t,a,s=[0,0]){let r=[],n=new Map;for(let a of e){let e=t.get(a.parentId);if(!e)continue;let s=cn(n.get(a.parentId)?.expandedRect??cs(e),a.rect);n.set(a.parentId,{expandedRect:s,parent:e})}return n.size>0&&n.forEach(({expandedRect:t,parent:n},l)=>{let i=n.internals.positionAbsolute,o=cf(n),c=n.origin??s,d=t.x<i.x?Math.round(Math.abs(i.x-t.x)):0,u=t.y<i.y?Math.round(Math.abs(i.y-t.y)):0,h=Math.max(o.width,Math.round(t.width)),p=Math.max(o.height,Math.round(t.height)),m=(h-o.width)*c[0],x=(p-o.height)*c[1];(d>0||u>0||m||x)&&(r.push({id:l,type:"position",position:{x:n.position.x-d+m,y:n.position.y-u+x}}),a.get(l)?.forEach(t=>{e.some(e=>e.id===t.id)||r.push({id:t.id,type:"position",position:{x:t.position.x+d,y:t.position.y+u}})})),(o.width<t.width||o.height<t.height||d||u)&&r.push({id:l,type:"dimensions",setAttributes:!0,dimensions:{width:h+(d?c[0]*d-m:0),height:p+(u?c[1]*u-x:0)}})}),r}async function cZ({delta:e,panZoom:t,transform:a,translateExtent:s,width:r,height:n}){if(!t||!e.x&&!e.y)return!1;let l=await t.setViewportConstrained({x:a[0]+e.x,y:a[1]+e.y,zoom:
10a[2]},[[0,0],[r,n]],s);return!!l&&(l.x!==a[0]||l.y!==a[1]||l.k!==a[2])}function cQ(e,t,a,s,r,n){let l=r,i=s.get(l)||new Map;s.set(l,i.set(a,t)),l=`${r}-${e}`;let o=s.get(l)||new Map;if(s.set(l,o.set(a,t)),n){l=`${r}-${e}-${n}`;let i=s.get(l)||new Map;s.set(l,i.set(a,t))}}function c0(e,t,a){for(let s of(e.clear(),t.clear(),a)){let{source:a,target:r,sourceHandle:n=null,targetHandle:l=null}=s,i={edgeId:s.id,source:a,target:r,sourceHandle:n,targetHandle:l},o=`${a}-${n}--${r}-${l}`;cQ("source",i,`${r}-${l}--${a}-${n}`,e,a,n),cQ("target",i,o,e,r,l),t.set(s.id,s)}}function c1(e,t,a){let s=e;do{if(s?.matches?.(t))return!0;if(s===a)break;s=s?.parentElement}while(s)return!1}function c2({nodeId:e,dragItems:t,nodeLookup:a,dragging:s=!0}){let r=[];for(let[e,n]of t){let t=a.get(e)?.internals.userNode;t&&r.push({...t,position:n.position,dragging:s})}if(!e)return[r[0],r];let n=a.get(e)?.internals.userNode;return[n?{...n,position:t.get(e)?.position||n.position,dragging:s}:r[0],r]}function c5(e,t,a,s,r,n=!1){let l=s.get(e);if(!l)return null;let i="strict"===r?l.internals.handleBounds?.[t]:[...l.internals.handleBounds?.source??[],...l.internals.handleBounds?.target??[]],o=(a?i?.find(e=>e.id===a):i?.[0])??null;return o&&n?{...o,...cB(l,o,o.position,!0)}:o}function c4(e,t){return e?e:t?.classList.contains("target")?"target":t?.classList.contains("source")?"source":null}let c3=()=>!0;function c6(e,{handle:t,connectionMode:a,fromNodeId:s,fromHandleId:r,fromType:n,doc:l,lib:i,flowId:o,isValidConnection:c=c3,nodeLookup:u}){let h="target"===n,p=t?l.querySelector(`.${i}-flow__handle[data-id="${o}-${t?.nodeId}-${t?.id}-${t?.type}"]`):null,{x:m,y:x}=cS(e),g=l.elementFromPoint(m,x),f=g?.classList.contains(`${i}-flow__handle`)?g:p,b={handleDomNode:f,isValid:!1,connection:null,toHandle:null};if(f){let e=c4(void 0,f),t=f.getAttribute("data-nodeid"),n=f.getAttribute("data-handleid"),l=f.classList.contains("connectable"),i=f.classList.contains("connectableend");if(!t||!e)return b;let o={source:h?t:s,sourceHandle:h?n:r,target:h?s:t,targetHandle:h?r:n};b.connection=o,b.isValid=l&&i&&(a===d.Strict?h&&"source"===e||!h&&"target"===e:t!==s||n!==r)&&c(o),b.toHandle=c5(t,e,n,u,a,!0)}return b}let c8=function(e,{connectionMode:t,connectionRadius:a,handleId:s,nodeId:r,edgeUpdaterType:n,isTarget:l,domNode:i,nodeLookup:o,lib:c,autoPanOnConnect:d,flowId:u,panBy:h,cancelConnection:p,onConnectStart:m,onConnect:g,onConnectEnd:f,isValidConnection:b=c3,onReconnectEnd:_,updateConnection:v,getTransform:y,getFromHandle:j,autoPanSpeed:w,dragThreshold:N=1,handleDomNode:k}){let S,$=cw(e.target),C=0,{x:M,y:E}=cS(e),A=c4(n,k),T=i?.getBoundingClientRect(),F=!1;if(!T||!A)return;let P=c5(r,A,s,o,t);if(!P)return;let R=cS(e,T),O=!1,L=null,I=!1,D=null,z={...P,nodeId:r,type:A,position:P.position},B=o.get(r),W={inProgress:!0,isValid:null,from:cB(B,z,x.Left,!0),fromHandle:z,fromPosition:z.position,fromNode:B,to:R,toHandle:null,toPosition:oY[z.position],toNode:null,pointer:R};function U(){F=!0,v(W),m?.(e,{nodeId:r,handleId:s,handleType:A})}function H(e){var n,i;let p;if(!F){let{x:t,y:a}=cS(e),s=t-M,r=a-E;if(!(s*s+r*r>N*N))return;U()}if(!j()||!z)return void q(e);let m=y();S=function(e,t,a,s){let r=[],n=1/0;for(let l of function(e,t,a){let s=[],r={x:e.x-a,y:e.y-a,width:2*a,height:2*a};for(let e of t.values())cl(r,cs(e))>0&&s.push(e);return s}(e,a,t+250))for(let a of[...l.internals.handleBounds?.source??[],...l.internals.handleBounds?.target??[]]){if(s.nodeId===a.nodeId&&s.type===a.type&&s.id===a.id)continue;let{x:i,y:o}=cB(l,a,a.position,!0),c=Math.sqrt(Math.pow(i-e.x,2)+Math.pow(o-e.y,2));c>t||(c<n?(r=[{...a,x:i,y:o}],n=c):c===n&&r.push({...a,x:i,y:o}))}if(!r.length)return null;if(r.length>1){let e="source"===s.type?"target":"source";return r.find(t=>t.type===e)??r[0]}return r[0]}(cu(R=cS(e,T),m,!1,[1,1]),a,o,z),O||(!function e(){if(!d||!T)return;let[t,a]=o7(R,T,w);h({x:t,y:a}),C=requestAnimationFrame(e)}(),O=!0);let g=c6(e,{handle:S,connectionMode:t,fromNodeId:r,fromHandleId:s,fromType:l?"target":"source",isValidConnection:b,doc:$,lib:c,flowId:u,nodeLookup:o});D=g.handleDomNode,L=g.connection,n=!!S,i=g.isValid,p=null,i?p=!0:n&&!i&&(p=!1),I=p;let f=o.get(r),_=f?cB(f,z,x.Left,!0):W.from,k={...W,from:_,isValid:I,to:g.toHandle&&I?ch({x:g.toHandle.x,y:g.toHandle.y},m):R,toHandle:g.toHandle,toPosition:I&&g.toHandle?g.toHandle.position:oY[z.position],toNode:g.toHandle?o.get(g.toHandle.nodeId):null,pointer:R};v(k),W=k}function q(e){if(!("touches"in e)||!(e.touches.length>0)){if(F){(S||D)&&L&&I&&g?.(L);let{inProgress:t,...a}
10=W,s={...a,toPosition:W.toHandle?W.toPosition:null};f?.(e,s),n&&_?.(e,s)}p(),cancelAnimationFrame(C),O=!1,I=!1,L=null,D=null,$.removeEventListener("mousemove",H),$.removeEventListener("mouseup",q),$.removeEventListener("touchmove",H),$.removeEventListener("touchend",q)}}0===N&&U(),$.addEventListener("mousemove",H),$.addEventListener("mouseup",q),$.addEventListener("touchmove",H),$.addEventListener("touchend",q)},c9=e=>({x:e.x,y:e.y,zoom:e.k}),c7=({x:e,y:t,zoom:a})=>oF.translate(e,t).scale(a),de=(e,t)=>e.target.closest(`.${t}`),dt=(e,t)=>2===t&&Array.isArray(e)&&e.includes(2),da=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,ds=(e,t=0,a=da,s=()=>{})=>{let r="number"==typeof t&&t>0;return r||s(),r?e.transition().duration(t).ease(a).on("end",s):e},dr=e=>{let t=e.ctrlKey&&cx()?10:1;return-e.deltaY*(1===e.deltaMode?.05:e.deltaMode?1:.002)*t};function dn(e){let t=e.includes("right")||e.includes("left"),a=e.includes("bottom")||e.includes("top");return{isHorizontal:t,isVertical:a,affectsX:e.includes("left"),affectsY:e.includes("top")}}function dl(e,t){return Math.max(0,t-e)}function di(e,t){return Math.max(0,e-t)}function dc(e,t,a){return Math.max(0,t-e,e-a)}(i=g||(g={})).Line="line",i.Handle="handle";let dd={width:0,height:0,x:0,y:0},du={...dd,pointerX:0,pointerY:0,aspectRatio:1};var dh=e.i(35686);let dp={get url(){return`file://${e.P("frontend/node_modules/@xyflow/react/node_modules/zustand/esm/vanilla.mjs")}`}},dm=e=>{let t,a=new Set,s=(e,s)=>{let r="function"==typeof e?e(t):e;if(!Object.is(r,t)){let e=t;t=(null!=s?s:"object"!=typeof r||null===r)?r:Object.assign({},t,r),a.forEach(a=>a(t,e))}},r=()=>t,n={setState:s,getState:r,getInitialState:()=>l,subscribe:e=>(a.add(e),()=>a.delete(e)),destroy:()=>{(dp.env?dp.env.MODE:void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),a.clear()}},l=t=e(s,r,n);return n},{useDebugValue:dx}=_.default,{useSyncExternalStoreWithSelector:dg}=dh.default,df=e=>e;function db(e,t=df,a){let s=dg(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,a);return dx(s),s}let d_=(e,t)=>{let a=e?dm(e):dm,s=(e,s=t)=>db(a,e,s);return Object.assign(s,a),s};function dv(e,t){if(Object.is(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(let[a,s]of e)if(!Object.is(s,t.get(a)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(let a of e)if(!t.has(a))return!1;return!0}let a=Object.keys(e);if(a.length!==Object.keys(t).length)return!1;for(let s of a)if(!Object.prototype.hasOwnProperty.call(t,s)||!Object.is(e[s],t[s]))return!1;return!0}let dy=(0,_.createContext)(null),dj=dy.Provider,dw=((e="react")=>`Seems like you have not used zustand provider as an ancestor. Help: https://${e}flow.dev/error#001`)("react");function dN(e,t){let a=(0,_.useContext)(dy);if(null===a)throw Error(dw);return db(a,e,t)}function dk(){let e=(0,_.useContext)(dy);if(null===e)throw Error(dw);return(0,_.useMemo)(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}let dS={display:"none"},d$={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},dC="react-flow__node-desc",dM="react-flow__edge-desc",dE=e=>e.ariaLiveMessage,dA=e=>e.ariaLabelConfig;function dT({rfId:e}){let t=dN(dE);return(0,b.jsx)("div",{id:`react-flow__aria-live-${e}`,"aria-live":"assertive","aria-atomic":"true",style:d$,children:t})}function dF({rfId:e,disableKeyboardA11y:t}){let a=dN(dA);return(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)("div",{id:`${dC}-${e}`,style:dS,children:t?a["node.a11yDescription.default"]:a["node.a11yDescription.keyboardDisabled"]}),(0,b.jsx)("div",{id:`${dM}-${e}`,style:dS,children:a["edge.a11yDescription.default"]}),!t&&(0,b.jsx)(dT,{rfId:e})]})}let dP=(0,_.forwardRef)(({position:e="top-left",children:t,className:a,style:s,...r},n)=>{let l=`${e}`.split("-");return(0,b.jsx)("div",{className:lp(["react-flow__panel",a,...l]),style:s,ref:n,...r,children:t})});function dR({proOptions:e,position:t="bottom-right"}){return e?.hideAttribution?null:(0,b.jsx)(dP,{position:t,className:"react-flow__attribution","data-message":"Please only hide this attribution when you are subscribed to React Flow Pro: https://pro.reactflow.dev",children:(0,b.jsx)("a",{href:"https://reactflow.dev",target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution",children:"React Flow"})})}dP.displayName="Panel";let dO=e=>{let t=[],a=[];for(let[,a]of e.nodeLookup)a.selected&&t.push(a.internals.userNode);for(let[,t]of e.edgeLookup)t.selected&&a.push(t);return{selectedNodes:t,selectedEdges:a}},dL=e=>e.id;function dI(e,t){return dv(e.selectedNodes.map(dL),t.selectedNodes.map(dL))&&dv(e.selectedEdges.map(dL),t.selectedEdges.map(dL))}function dD({onSelectionChange:e}){let t=dk(),{selectedNodes:a,selectedEdges:s}=dN(dO,dI);return(0,_.useEffect)(()=>{let r={nodes:a,edges:s};
10e?.(r),t.getState().onSelectionChangeHandlers.forEach(e=>e(r))},[a,s,e]),null}let dz=e=>!!e.onSelectionChangeHandlers;function dB({onSelectionChange:e}){let t=dN(dz);return e||t?(0,b.jsx)(dD,{onSelectionChange:e}):null}let dW=[0,0],dU={x:0,y:0,zoom:1},dH=["nodes","edges","defaultNodes","defaultEdges","onConnect","onConnectStart","onConnectEnd","onClickConnectStart","onClickConnectEnd","nodesDraggable","autoPanOnNodeFocus","nodesConnectable","nodesFocusable","edgesFocusable","edgesReconnectable","elevateNodesOnSelect","elevateEdgesOnSelect","minZoom","maxZoom","nodeExtent","onNodesChange","onEdgesChange","elementsSelectable","connectionMode","snapGrid","snapToGrid","translateExtent","connectOnClick","defaultEdgeOptions","fitView","fitViewOptions","onNodesDelete","onEdgesDelete","onDelete","onNodeDrag","onNodeDragStart","onNodeDragStop","onSelectionDrag","onSelectionDragStart","onSelectionDragStop","onMoveStart","onMove","onMoveEnd","noPanClassName","nodeOrigin","autoPanOnConnect","autoPanOnNodeDrag","onError","connectionRadius","isValidConnection","selectNodesOnDrag","nodeDragThreshold","connectionDragThreshold","onBeforeDelete","debug","autoPanSpeed","ariaLabelConfig","zIndexMode","rfId"],dq=e=>({setNodes:e.setNodes,setEdges:e.setEdges,setMinZoom:e.setMinZoom,setMaxZoom:e.setMaxZoom,setTranslateExtent:e.setTranslateExtent,setNodeExtent:e.setNodeExtent,reset:e.reset,setDefaultNodesAndEdges:e.setDefaultNodesAndEdges}),dV={translateExtent:oq,nodeOrigin:dW,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function dG(e){let{setNodes:t,setEdges:a,setMinZoom:s,setMaxZoom:r,setTranslateExtent:n,setNodeExtent:l,reset:i,setDefaultNodesAndEdges:o}=dN(dq,dv),c=dk();(0,_.useEffect)(()=>(o(e.defaultNodes,e.defaultEdges),()=>{d.current=dV,i()}),[]);let d=(0,_.useRef)(dV);return(0,_.useEffect)(()=>{for(let i of dH){let o=e[i];if(o!==d.current[i]&&void 0!==e[i])if("nodes"===i)t(o);else if("edges"===i)a(o);else if("minZoom"===i)s(o);else if("maxZoom"===i)r(o);else if("translateExtent"===i)n(o);else if("nodeExtent"===i)l(o);else if("ariaLabelConfig"===i)c.setState({ariaLabelConfig:{...oG,...o||{}}});else"fitView"===i?c.setState({fitViewQueued:o}):"fitViewOptions"===i?c.setState({fitViewOptions:o}):c.setState({[i]:o})}d.current=e},dH.map(t=>e[t])),null}function dJ(){return"u"<typeof window||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}let dY="u">typeof document?document:null;function dK(e=null,t={target:dY,actInsideInputWithModifier:!0}){let[a,s]=(0,_.useState)(!1),r=(0,_.useRef)(!1),n=(0,_.useRef)(new Set([])),[l,i]=(0,_.useMemo)(()=>{if(null!==e){let t=(Array.isArray(e)?e:[e]).filter(e=>"string"==typeof e).map(e=>e.replace("+","\n").replace("\n\n","\n+").split("\n")),a=t.reduce((e,t)=>e.concat(...t),[]);return[t,a]}return[[],[]]},[e]);return(0,_.useEffect)(()=>{let a=t?.target??dY,o=t?.actInsideInputWithModifier??!0;if(null!==e){let e=e=>{if(r.current=e.ctrlKey||e.metaKey||e.shiftKey||e.altKey,(!r.current||r.current&&!o)&&ck(e))return!1;let a=dZ(e.code,i);if(n.current.add(e[a]),dX(l,n.current,!1)){let a=e.composedPath?.()?.[0]||e.target,n=a?.nodeName==="BUTTON"||a?.nodeName==="A";!1!==t.preventDefault&&(r.current||!n)&&e.preventDefault(),s(!0)}},c=e=>{let t=dZ(e.code,i);dX(l,n.current,!0)?(s(!1),n.current.clear()):n.current.delete(e[t]),"Meta"===e.key&&n.current.clear(),r.current=!1},d=()=>{n.current.clear(),s(!1)};return a?.addEventListener("keydown",e),a?.addEventListener("keyup",c),window.addEventListener("blur",d),window.addEventListener("contextmenu",d),()=>{a?.removeEventListener("keydown",e),a?.removeEventListener("keyup",c),window.removeEventListener("blur",d),window.removeEventListener("contextmenu",d)}}},[e,s]),a}function dX(e,t,a){return e.filter(e=>a||e.length===t.size).some(e=>e.every(e=>t.has(e)))}function dZ(e,t){return t.includes(e)?"code":"key"}function dQ(e,t){let a=[],s=new Map,r=[];for(let t of e)if("add"===t.type){r.push(t);continue}else if("remove"===t.type||"replace"===t.type)s.set(t.id,[t]);else{let e=s.get(t.id);e?e.push(t):s.set(t.id,[t])}for(let e of t){let t=s.get(e.id);if(!t){a.push(e);continue}if("remove"===t[0].type)continue;if("replace"===t[0].type){a.push({...t[0].item});continue}let r={...e};for(let e of t){var n=e,l=r;switch(n.type){case"select":l.selected=n.selected;break;case"position":void 0!==n.position&&(l.position=n.position),void 0!==n.dragging&&(l.dragging=n.dragging);break;case"dimensions":void 0!==n.dimensions&&(l.measured={...n.dimensions},n.setAttributes&&((!0===n.setAttributes||"width"===n.setAttributes)&&(l.width=n.dimensions.width),(!0===n.setAttributes||"height"===n.setAttributes)&&(l.height=n.dimensions.height))),"boolean"==typeof n.resizing&&(l.resizing=n.resizing)}}a.push(r)}
10return r.length&&r.forEach(e=>{void 0!==e.index?a.splice(e.index,0,{...e.item}):a.push({...e.item})}),a}function d0(e,t){return{id:e,type:"select",selected:t}}function d1(e,t=new Set,a=!1){let s=[];for(let[r,n]of e){let e=t.has(r);(void 0!==n.selected||e)&&n.selected!==e&&(a&&(n.selected=e),s.push(d0(n.id,e)))}return s}function d2({items:e=[],lookup:t}){let a=[],s=new Map(e.map(e=>[e.id,e]));for(let[s,r]of e.entries()){let e=t.get(r.id),n=e?.internals?.userNode??e;void 0!==n&&n!==r&&a.push({id:r.id,item:r,type:"replace"}),void 0===n&&a.push({item:r,type:"add",index:s})}for(let[e]of t)void 0===s.get(e)&&a.push({id:e,type:"remove"});return a}function d5(e){return{id:e.id,type:"remove"}}let d4=cc("React Flow","https://reactflow.dev/");function d3(e,t,a={}){return((e,t,a={})=>{let s,r;if(!e.source||!e.target)return a.onError?.("006","Can't create edge. An edge needs a source and a target."),t;let n=a.getEdgeId||cF;return(r=s=oX(e)?{...e}:{...e,id:n(e)},t.some(e=>e.source===r.source&&e.target===r.target&&(e.sourceHandle===r.sourceHandle||!e.sourceHandle&&!r.sourceHandle)&&(e.targetHandle===r.targetHandle||!e.targetHandle&&!r.targetHandle)))?t:(null===s.sourceHandle&&delete s.sourceHandle,null===s.targetHandle&&delete s.targetHandle,t.concat(s))})(e,t,{...a,onError:a.onError??d4})}let d6=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e);function d8(e){return(0,_.forwardRef)(e)}let d9="u">typeof window?_.useLayoutEffect:_.useEffect;function d7(e){let[t,a]=(0,_.useState)(BigInt(0)),[s]=(0,_.useState)(()=>{var e;let t;return e=()=>a(e=>e+BigInt(1)),t=[],{get:()=>t,reset:()=>{t=[]},push:a=>{t.push(a),e()}}});return d9(()=>{let t=s.get();t.length&&(e(t),s.reset())},[t]),s}let ue=(0,_.createContext)(null);function ut({children:e}){let t=dk(),a=d7((0,_.useCallback)(e=>{let{nodes:a=[],setNodes:s,hasDefaultNodes:r,onNodesChange:n,nodeLookup:l,fitViewQueued:i,onNodesChangeMiddlewareMap:o}=t.getState(),c=a;for(let t of e)c="function"==typeof t?t(c):t;let d=d2({items:c,lookup:l});for(let e of o.values())d=e(d);r&&s(c),d.length>
100?n?.(d):i&&window.requestAnimationFrame(()=>{let{fitViewQueued:e,nodes:a,setNodes:s}=t.getState();e&&s(a)})},[])),s=d7((0,_.useCallback)(e=>{let{edges:a=[],setEdges:s,hasDefaultEdges:r,onEdgesChange:n,edgeLookup:l}=t.getState(),i=a;for(let t of e)i="function"==typeof t?t(i):t;r?s(i):n&&n(d2({items:i,lookup:l}))},[])),r=(0,_.useMemo)(()=>({nodeQueue:a,edgeQueue:s}),[]);return(0,b.jsx)(ue.Provider,{value:r,children:e})}let ua=e=>!!e.panZoom;function us(){let e,t=(e=dk(),(0,_.useMemo)(()=>({zoomIn:async t=>{let{panZoom:a}=e.getState();return!!a&&a.scaleBy(1.2,t)},zoomOut:async t=>{let{panZoom:a}=e.getState();return!!a&&a.scaleBy(1/1.2,t)},zoomTo:async(t,a)=>{let{panZoom:s}=e.getState();return!!s&&s.scaleTo(t,a)},getZoom:()=>e.getState().transform[2],setViewport:async(t,a)=>{let{transform:[s,r,n],panZoom:l}=e.getState();return!!l&&(await l.setViewport({x:t.x??s,y:t.y??r,zoom:t.zoom??n},a),!0)},getViewport:()=>{let[t,a,s]=e.getState().transform;return{x:t,y:a,zoom:s}},setCenter:async(t,a,s)=>e.getState().setCenter(t,a,s),fitBounds:async(t,a)=>{let{width:s,height:r,minZoom:n,maxZoom:l,panZoom:i}=e.getState(),o=cm(t,s,r,n,l,a?.padding??.1);return!!i&&(await i.setViewport(o,{duration:a?.duration,ease:a?.ease,interpolate:a?.interpolate}),!0)},screenToFlowPosition:(t,a={})=>{let{transform:s,snapGrid:r,snapToGrid:n,domNode:l}=e.getState();if(!l)return t;let{x:i,y:o}=l.getBoundingClientRect(),c={x:t.x-i,y:t.y-o},d=a.snapGrid??r;
10return cu(c,s,a.snapToGrid??n,d)},flowToScreenPosition:t=>{let{transform:a,domNode:s}=e.getState();if(!s)return t;let{x:r,y:n}=s.getBoundingClientRect(),l=ch(t,a);return{x:l.x+r,y:l.y+n}}}),[])),a=dk(),s=function(){let e=(0,_.useContext)(ue);if(!e)throw Error("useBatchContext must be used within a BatchProvider");return e}(),r=dN(ua),n=(0,_.useMemo)(()=>{let e=e=>a.getState().nodeLookup.get(e),t=e=>{s.nodeQueue.push(e)},r=e=>{s.edgeQueue.push(e)},n=e=>{let{nodeLookup:t,nodeOrigin:s}=a.getState(),r=d6(e)?e:t.get(e.id),n=r.parentId?c_(r.position,r.measured,r.parentId,t,s):r.position;return cs({...r,position:n,width:r.measured?.width??r.width,height:r.measured?.height??r.height})},l=(e,a,s={replace:!1})=>{t(t=>t.map(t=>{if(t.id===e){let e="function"==typeof a?a(t):a;return s.replace&&d6(e)?e:{...t,...e}}return t}))},i=(e,t,a={replace:!1})=>{r(s=>s.map(s=>{if(s.id===e){let e="function"==typeof t?t(s):t;return a.replace&&oX(e)?e:{...s,...e}}return s}))};return{getNodes:()=>a.getState().nodes.map(e=>({...e})),getNode:t=>e(t)?.internals.userNode,getInternalNode:e,getEdges:()=>{let{edges:e=[]}=a.getState();return e.map(e=>({...e}))},getEdge:e=>a.getState().edgeLookup.get(e),setNodes:t,setEdges:r,addNodes:e=>{let t=Array.isArray(e)?e:[e];s.nodeQueue.push(e=>[...e,...t])},addEdges:e=>{let t=Array.isArray(e)?e:[e];s.edgeQueue.push(e=>[...e,...t])},toObject:()=>{let{nodes:e=[],edges:t=[],transform:s}=a.getState(),[r,n,l]=s;return{nodes:e.map(e=>({...e})),edges:t.map(e=>({...e})),viewport:{x:r,y:n,zoom:l}}},deleteElements:async({nodes:e=[],edges:t=[]})=>{let{nodes:s,edges:r,onNodesDelete:n,onEdgesDelete:l,triggerNodeChanges:i,triggerEdgeChanges:o,onDelete:c,onBeforeDelete:d}=a.getState(),{nodes:u,edges:h}=await o4({nodesToRemove:e,edgesToRemove:t,nodes:s,edges:r,onBeforeDelete:d}),p=h.length>0,m=u.length>0;if(p){let e=h.map(d5);l?.(h),o(e)}if(m){let e=u.map(d5);n?.(u),i(e)}return(m||p)&&c?.({nodes:u,edges:h}),{deletedNodes:u,deletedEdges:h}},getIntersectingNodes:(e,t=!0,s)=>{let r=ci(e),l=r?e:n(e),i=void 0!==s;return l?(s||a.getState().nodes).filter(s=>{let n=a.getState().nodeLookup.get(s.id);if(n&&!r&&(s.id===e.id||!n.internals.positionAbsolute))return!1;let o=cs(i?s:n),c=cl(o,l);return t&&c>0||c>=o.width*o.height||c>=l.width*l.height}):[]},isNodeIntersecting:(e,t,a=!0)=>{let s=ci(e)?e:n(e);if(!s)return!1;let r=cl(s,t);return a&&r>0||r>=t.width*t.height||r>=s.width*s.height},updateNode:l,updateNodeData:(e,t,a={replace:!1})=>{l(e,e=>{let s="function"==typeof t?t(e):t;return a.replace?{...e,data:s}:{...e,data:{...e.data,...s}}},a)},updateEdge:i,updateEdgeData:(e,t,a={replace:!1})=>{i(e,e=>{let s="function"==typeof t?t(e):t;return a.replace?{...e,data:s}:{...e,data:{...e.data,...s}}},a)},getNodesBounds:e=>{let{nodeLookup:t,nodeOrigin:s}=a.getState();return((e,t={nodeOrigin:[0,0]})=>0===e.length?{x:0,y:0,width:0,height:0}:ca(e.reduce((e,a)=>{let s="string"==typeof a,r=t.nodeLookup||s?void 0:a;return t.nodeLookup&&(r=s?t.nodeLookup.get(a):oZ(a)?a:t.nodeLookup.get(a.id)),ce(e,r?cr(r,t.nodeOrigin):{x:0,y:0,x2:0,y2:0})},{x:1/0,y:1/0,x2:-1/0,y2:-1/0})))(e,{nodeLookup:t,nodeOrigin:s})},getHandleConnections:({type:e,id:t,nodeId:s})=>Array.from(a.getState().connectionLookup.get(`${s}-${e}${t?`-${t}`:""}`)?.values()??[]),getNodeConnections:({type:e,handleId:t,nodeId:s})=>Array.from(a.getState().connectionLookup.get(`${s}${e?t?`-${e}-${t}`:`-${e}`:""}`)?.values()??[]),fitView:async e=>{let t,r,n=a.getState().fitViewResolver??{promise:new Promise((e,a)=>{t=e,r=a}),resolve:t,reject:r};return a.setState({fitViewQueued:!0,fitViewOptions:e,fitViewResolver:n}),s.nodeQueue.push(e=>[...e]),n.promise}}},[]);return(0,_.useMemo)(()=>({...n,...t,viewportInitialized:r}),[r])}let ur=e=>e.selected,un="u">typeof window?window:void 0,ul={position:"absolute",width:"100%",height:"100%",top:0,left:0},ui=e=>({userSelectionActive:e.userSelectionActive,lib:e.lib,connectionInProgress:e.connection.inProgress});function uo({onPaneContextMenu:e,zoomOnScroll:t=!0,zoomOnPinch:a=!0,panOnScroll:s=!1,panOnScrollSpeed:r=.5,panOnScrollMode:n=u.Free,zoomOnDoubleClick:l=!0,panOnDrag:i=!0,defaultViewport:o,translateExtent:c,minZoom:d,maxZoom:h,zoomActivationKeyCode:p,preventScrolling:m=!0,children:x,noWheelClassName:g,noPanClassName:f,onViewportChange:v,isControlledViewport:y,paneClickDistance:j,selectionOnDrag:w}){let N,k=dk(),S=(0,_.useRef)(null),{userSelectionActive:$,lib:C,connectionInProgress:M}=dN(ui,dv),E=dK(p),A=(0,_.useRef)();N=dk(),(0,_.useEffect)(()=>{let e=()=>
10{if(!S.current||!(S.current.checkVisibility?.()??!0))return!1;let e=cj(S.current);(0===e.height||0===e.width)&&N.getState().onError?.("004","The parent container needs a width and a height to render the graph."),N.setState({width:e.width||500,height:e.height||500})};if(S.current){e(),window.addEventListener("resize",e);let t=new ResizeObserver(()=>e());return t.observe(S.current),()=>{window.removeEventListener("resize",e),t&&S.current&&t.unobserve(S.current)}}},[]);let T=(0,_.useCallback)(e=>{v?.({x:e[0],y:e[1],zoom:e[2]}),y||k.setState({transform:e})},[v,y]);return(0,_.useEffect)(()=>{if(S.current){A.current=function({domNode:e,minZoom:t,maxZoom:a,translateExtent:s,viewport:r,onPanZoom:n,onPanZoomStart:l,onPanZoomEnd:i,onDraggingChange:o}){let c={isZoomingOrPanning:!1,usedRightMouseButton:!1,prevViewport:{},mouseButton:0,timerId:void 0,panScrollTimeout:void 0,isPanScrolling:!1},d=e.getBoundingClientRect(),h=oU().scaleExtent([t,a]).translateExtent(s),p=l3(e).call(h);b({x:r.x,y:r.y,zoom:o3(r.zoom,t,a)},[[0,0],[d.width,d.height]],s);let m=p.on("wheel.zoom"),x=p.on("dblclick.zoom");async function g(e,t){return!!p&&new Promise(a=>{h?.interpolate(t?.interpolate==="linear"?oH:ih).transform(ds(p,t?.duration,t?.ease,()=>a(!0)),e)})}function f(){h.on("zoom",null)}async function b(e,t,a){let s=c7(e),r=h?.constrain()(s,t,a);return r&&await g(r),r}return h.wheelDelta(dr),{update:function({noWheelClassName:e,noPanClassName:t,onPaneContextMenu:a,userSelectionActive:s,panOnScroll:r,panOnDrag:d,panOnScrollMode:g,panOnScrollSpeed:b,preventScrolling:_,zoomOnPinch:v,zoomOnScroll:y,zoomOnDoubleClick:j,zoomActivationKeyPressed:w,lib:N,onTransformChange:k,connectionInProgress:S,paneClickDistance:$,selectionOnDrag:C}){s&&!c.isZoomingOrPanning&&f();let M=r&&!w&&!s;h.clickDistance(C?1/0:!co($)||$<0?0:$);let E=M?function({zoomPanValues:e,noWheelClassName:t,d3Selection:a,d3Zoom:s,panOnScrollMode:r,panOnScrollSpeed:n,zoomOnPinch:l,onPanZoomStart:i,onPanZoom:o,onPanZoomEnd:c}){return d=>{if(de(d,t))return d.ctrlKey&&d.preventDefault(),!1;d.preventDefault(),d.stopImmediatePropagation();let h=a.property("__zoom").k||1;if(d.ctrlKey&&l){let e=l6(d),t=h*Math.pow(2,dr(d));s.scaleTo(a,t,e,d);return}let p=1===d.deltaMode?20:1,m=r===u.Vertical?0:d.deltaX*p,x=r===u.Horizontal?0:d.deltaY*p;!cx()&&d.shiftKey&&r!==u.Vertical&&(m=d.deltaY*p,x=0),s.translateBy(a,-(m/h)*n,-(x/h)*n,{internal:!0});let g=c9(a.property("__zoom"));clearTimeout(e.panScrollTimeout),e.isPanScrolling?(o?.(d,g),e.panScrollTimeout=setTimeout(()=>{c?.(d,g),e.isPanScrolling=!1},150)):(e.isPanScrolling=!0,i?.(d,g))}}({zoomPanValues:c,noWheelClassName:e,d3Selection:p,d3Zoom:h,panOnScrollMode:g,panOnScrollSpeed:b,zoomOnPinch:v,onPanZoomStart:l,onPanZoom:n,onPanZoomEnd:i}):function({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:a}){return function(s,r){let n="wheel"===s.type,l=!t&&n&&!s.ctrlKey,i=de(s,e);if(s.ctrlKey&&n&&i&&s.preventDefault(),l||i)return null;s.preventDefault(),a.call(this,s,r)}}({noWheelClassName:e,preventScrolling:_,d3ZoomHandler:m});p.on("wheel.zoom",E,{passive:!1});let A=function({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:a}){return s=>{if(s.sourceEvent?.internal)return;let r=c9(s.transform);e.mouseButton=s.sourceEvent?.button||0,e.isZoomingOrPanning=!0,e.prevViewport=r,s.sourceEvent?.type==="mousedown"&&t(!0),a&&a?.(s.sourceEvent,r)}}({zoomPanValues:c,onDraggingChange:o,onPanZoomStart:l});h.on("start",A);let T=function({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:a,onTransformChange:s,onPanZoom:r}){return n=>{e.usedRightMouseButton=!!(a&&dt(t,e.mouseButton??0)),n.sourceEvent?.sync||s([n.transform.x,n.transform.y,n.transform.k]),r&&!n.sourceEvent?.internal&&r?.(n.sourceEvent,c9(n.transform))}}({zoomPanValues:c,panOnDrag:d,onPaneContextMenu:!!a,onPanZoom:n,onTransformChange:k});h.on("zoom",T);let F=function({zoomPanValues:e,panOnDrag:t,panOnScroll:a,onDraggingChange:s,onPanZoomEnd:r,onPaneContextMenu:n}){return l=>{if(!l.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,n&&dt(t,e.mouseButton??0)&&!e.usedRightMouseButton&&l.sourceEvent&&n(l.sourceEvent),e.usedRightMouseButton=!1,s(!1),r)){let t=c9(l.transform);e.prevViewport=t,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{r?.(l.sourceEvent,t)},150*!!a)}}}({zoomPanValues:c,panOnDrag:d,panOnScroll:r,onPaneContextMenu:a,onPanZoomEnd:i,onDraggingChange:o});h.on("end",F);let P=function({zoomActivationKeyPressed:e,zoomOnScroll:t,zoomOnPinch:a,panOnDrag:s,panOnScroll:r,zoomOnDoubleClick:n,userSelectionActive:l,noWheelClassName:i,noPanClassName:o,lib:c,connectionInProgress:d}){return u=>{let h=e||t,p=a&&u.ctrlKey,m="wheel"===u.type;if(1===u.button&&"mousedown"===u.type&&(de(u,`${c}-flow__node`)||de(u,`${c}-flow__edge`)))return!0;
10if(!s&&!h&&!r&&!n&&!a||l||d&&!m||de(u,i)&&m||de(u,o)&&(!m||r&&m&&!e)||!a&&u.ctrlKey&&m)return!1;if(!a&&"touchstart"===u.type&&u.touches?.length>1)return u.preventDefault(),!1;if(!h&&!r&&!p&&m||!s&&("mousedown"===u.type||"touchstart"===u.type)||Array.isArray(s)&&!s.includes(u.button)&&"mousedown"===u.type)return!1;let x=Array.isArray(s)&&s.includes(u.button)||!u.button||u.button<=1;return(!u.ctrlKey||m)&&x}}({zoomActivationKeyPressed:w,panOnDrag:d,zoomOnScroll:y,panOnScroll:r,zoomOnDoubleClick:j,zoomOnPinch:v,userSelectionActive:s,noPanClassName:t,noWheelClassName:e,lib:N,connectionInProgress:S});h.filter(P),j?p.on("dblclick.zoom",x):p.on("dblclick.zoom",null)},destroy:f,setViewport:async function e(e,t){let a=c7(e);return await g(a,t),a},setViewportConstrained:b,getViewport:function(){let e=p?oP(p.node()):{x:0,y:0,k:1};return{x:e.x,y:e.y,zoom:e.k}},scaleTo:async function e(e,t){return!!p&&new Promise(a=>{h?.interpolate(t?.interpolate==="linear"?oH:ih).scaleTo(ds(p,t?.duration,t?.ease,()=>a(!0)),e)})},scaleBy:async function e(e,t){return!!p&&new Promise(a=>{h?.interpolate(t?.interpolate==="linear"?oH:ih).scaleBy(ds(p,t?.duration,t?.ease,()=>a(!0)),e)})},setScaleExtent:function(e){h?.scaleExtent(e)},setTranslateExtent:function(e){h?.translateExtent(e)},syncViewport:function(e){if(p){let t=c7(e),a=p.property("__zoom");(a.k!==e.zoom||a.x!==e.x||a.y!==e.y)&&h?.transform(p,t,null,{sync:!0})}},setClickDistance:function(e){let t=!co(e)||e<0?0:e;h?.clickDistance(t)}}}({domNode:S.current,minZoom:d,maxZoom:h,translateExtent:c,viewport:o,onDraggingChange:e=>k.setState(t=>t.paneDragging===e?t:{paneDragging:e}),onPanZoomStart:(e,t)=>{let{onViewportChangeStart:a,onMoveStart:s}=k.getState();s?.(e,t),a?.(t)},onPanZoom:(e,t)=>{let{onViewportChange:a,onMove:s}=k.getState();s?.(e,t),a?.(t)},onPanZoomEnd:(e,t)=>{let{onViewportChangeEnd:a,onMoveEnd:s}=k.getState();s?.(e,t),a?.(t)}});let{x:e,y:t,zoom:a}=A.current.getViewport();
10return k.setState({panZoom:A.current,transform:[e,t,a],domNode:S.current.closest(".react-flow")}),()=>{A.current?.destroy()}}},[]),(0,_.useEffect)(()=>{A.current?.update({onPaneContextMenu:e,zoomOnScroll:t,zoomOnPinch:a,panOnScroll:s,panOnScrollSpeed:r,panOnScrollMode:n,zoomOnDoubleClick:l,panOnDrag:i,zoomActivationKeyPressed:E,preventScrolling:m,noPanClassName:f,userSelectionActive:$,noWheelClassName:g,lib:C,onTransformChange:T,connectionInProgress:M,selectionOnDrag:w,paneClickDistance:j})},[e,t,a,s,r,n,l,i,E,m,f,$,g,C,T,M,w,j]),(0,b.jsx)("div",{className:"react-flow__renderer",ref:S,style:ul,children:x})}let uc=e=>({userSelectionActive:e.userSelectionActive,userSelectionRect:e.userSelectionRect});function ud(){let{userSelectionActive:e,userSelectionRect:t}=dN(uc,dv);return e&&t?(0,b.jsx)("div",{className:"react-flow__selection react-flow__container",style:{width:t.width,height:t.height,transform:`translate(${t.x}px, ${t.y}px)`}}):null}let uu=(e,t)=>a=>{a.target===t.current&&e?.(a)},uh=e=>({userSelectionActive:e.userSelectionActive,elementsSelectable:e.elementsSelectable,connectionInProgress:e.connection.inProgress,dragging:e.paneDragging,panBy:e.panBy,autoPanSpeed:e.autoPanSpeed});function up({isSelecting:e,selectionKeyPressed:t,selectionMode:a=h.Full,panOnDrag:s,autoPanOnSelection:r,paneClickDistance:n,selectionOnDrag:l,onSelectionStart:i,onSelectionEnd:o,onPaneClick:c,onPaneContextMenu:d,onPaneScroll:u,onPaneMouseEnter:p,onPaneMouseMove:m,onPaneMouseLeave:x,children:g}){let f=(0,_.useRef)(0),v=dk(),{userSelectionActive:y,elementsSelectable:j,dragging:w,connectionInProgress:N,panBy:k,autoPanSpeed:S}=dN(uh,dv),$=j&&(e||y),C=(0,_.useRef)(null),M=(0,_.useRef)(),E=(0,_.useRef)(new Set),A=(0,_.useRef)(new Set),T=(0,_.useRef)(!1),F=(0,_.useRef)({x:0,y:0}),P=(0,_.useRef)(!1),R=e=>{if(T.current||N){T.current=!1;return}c?.(e),v.getState().resetSelectedElements(),v.setState({nodesSelectionActive:!1})};function O(e,t){let{userSelectionRect:s}=v.getState();if(!s)return;let{transform:r,nodeLookup:n,edgeLookup:l,connectionLookup:i,triggerNodeChanges:o,triggerEdgeChanges:c,defaultEdgeOptions:d}=v.getState(),u={x:s.startX,y:s.startY},{x:p,y:m}=ch(u,r),x={startX:u.x,startY:u.y,x:e<p?e:p,y:t<m?t:m,width:Math.abs(e-p),height:Math.abs(t-m)},g=E.current,f=A.current;E.current=new Set(o1(n,x,r,a===h.Partial,!0).map(e=>e.id)),A.current=new Set;let b=d?.selectable??!0;for(let e of E.current){let t=i.get(e);if(t)for(let{edgeId:e}of t.values()){let t=l.get(e);t&&(t.selectable??b)&&A.current.add(e)}}cv(g,E.current)||o(d1(n,E.current,!0)),cv(f,A.current)||c(d1(l,A.current)),v.setState({userSelectionRect:x,userSelectionActive:!0,nodesSelectionActive:!1})}let L=()=>{cancelAnimationFrame(f.current),f.current=0,P.current=!1};(0,_.useEffect)(()=>()=>L(),[]);let I=!0===s||Array.isArray(s)&&s.includes(0);return(0,b.jsxs)("div",{className:lp(["react-flow__pane",{draggable:I,dragging:w,selection:e}]),onClick:$?void 0:uu(R,C),onContextMenu:uu(e=>{Array.isArray(s)&&s?.includes(2)?e.preventDefault():d?.(e)},C),onWheel:uu(u?e=>u(e):void 0,C),onPointerEnter:$?void 0:p,onPointerMove:$?e=>{let{userSelectionRect:a,transform:s,resetSelectedElements:l}=v.getState();if(!M.current||!a)return;let{x:o,y:c}=cS(e.nativeEvent,M.current);F.current={x:o,y:c};let d=ch({x:a.startX,y:a.startY},s);if(!T.current){if(Math.hypot(o-d.x,c-d.y)<=(t?0:n))return;l(),i?.(e)}T.current=!0,P.current||(!function e(){if(!r||!M.current)return;let[t,a]=o7(F.current,M.current,S);k({x:t,y:a}).then(t=>{if(!T.current||!t){f.current=requestAnimationFrame(e);return}let{x:a,y:s}=F.current;O(a,s),f.current=requestAnimationFrame(e)})}(),P.current=!0),O(o,c)}:m,onPointerUp:$?e=>{0===e.button&&(e.target?.releasePointerCapture?.(e.pointerId),!y&&e.target===C.current&&v.getState().userSelectionRect&&R?.(e),v.setState({userSelectionActive:!1,userSelectionRect:null}),T.current&&(o?.(e),v.setState({nodesSelectionActive:E.current.size>0})),L())}:void 0,onPointerCancel:$?e=>{e.target?.releasePointerCapture?.(e.pointerId),L()}:void 0,onPointerDownCapture:$?a=>{let{domNode:s,transform:r}=v.getState();if(M.current=s?.getBoundingClientRect(),!M.current)return;let n=a.target===C.current;
10if(!n&&a.target.closest(".nokey")||!e||!(l&&n||t)||0!==a.button||!a.isPrimary)return;a.target?.setPointerCapture?.(a.pointerId),T.current=!1;let{x:i,y:o}=cS(a.nativeEvent,M.current),c=cu({x:i,y:o},r);v.setState({userSelectionRect:{width:0,height:0,startX:c.x,startY:c.y,x:i,y:o}}),n||(a.stopPropagation(),a.preventDefault())}:void 0,onClickCapture:$?e=>{T.current&&(e.stopPropagation(),T.current=!1)}:void 0,onPointerLeave:x,ref:C,style:ul,children:[g,(0,b.jsx)(ud,{})]})}function um({id:e,store:t,unselect:a=!1,nodeRef:s}){let r,{addSelectedNodes:n,unselectNodesAndEdges:l,multiSelectionActive:i,nodeLookup:o,onError:c}=t.getState(),d=o.get(e);d?(t.setState({nodesSelectionActive:!1}),d.selected?(a||d.selected&&i)&&(l({nodes:[d],edges:[]}),requestAnimationFrame(()=>s?.current?.blur())):n([e])):c?.("012",(r=e,`Node with id "${r}" does not exist, it may have been removed. This can happen when a node is deleted before the "onNodeClick" handler is called.`))}function ux({nodeRef:e,disabled:t=!1,noDragClassName:a,handleSelector:s,nodeId:r,isSelectable:n,nodeClickDistance:l}){let i=dk(),[o,c]=(0,_.useState)(!1),d=(0,_.useRef)();return(0,_.useEffect)(()=>{d.current=function({onNodeMouseDown:e,getStoreItems:t,onDragStart:a,onDrag:s,onDragStop:r}){let n={x:null,y:null},l=0,i=new Map,o=!1,c={x:0,y:0},d=null,u=!1,h=null,p=!1,m=!1,x=null;return{update:function({noDragClassName:g,handleSelector:f,domNode:b,isSelectable:_,nodeId:v,nodeClickDistance:y=0}){function j({x:e,y:a}){let{nodeLookup:r,nodeExtent:l,snapGrid:o,snapToGrid:c,nodeOrigin:d,onNodeDrag:u,onSelectionDrag:h,onError:p,updateNodePositions:g}=t();n={x:e,y:a};let f=!1,b=i.size>1,_=b&&l?ct(o0(i)):null,y=b&&c?function({dragItems:e,snapGrid:t,x:a,y:s}){let r=e.values().next().value;if(!r)return null;let n={x:a-r.distance.x,y:s-r.distance.y},l=cd(n,t);return{x:l.x-n.x,y:l.y-n.y}}({dragItems:i,snapGrid:o,x:e,y:a}):null;for(let[t,s]of i){if(!r.has(t))continue;let n={x:e-s.distance.x,y:a-s.distance.y};c&&(n=y?{x:Math.round(n.x+y.x),y:Math.round(n.y+y.y)}:cd(n,o));let i=null;if(b&&l&&!s.extent&&_){let{positionAbsolute:e}=s.internals,t=e.x-_.x+l[0][0],a=e.x+s.measured.width-_.x2+l[1][0];i=[[t,e.y-_.y+l[0][1]],[a,e.y+s.measured.height-_.y2+l[1][1]]]}let{position:u,positionAbsolute:h}=o5({nodeId:t,nextPosition:n,nodeLookup:r,nodeExtent:i||l,nodeOrigin:d,onError:p});f=f||s.position.x!==u.x||s.position.y!==u.y,s.position=u,s.internals.positionAbsolute=h}if(m=m||f,f&&(g(i,!0),x&&(s||u||!v&&h))){let[e,t]=c2({nodeId:v,dragItems:i,nodeLookup:r});s?.(x,i,e,t),u?.(x,e,t),v||h?.(x,t)}}async function w(){if(!d)return;let{transform:e,panBy:a,autoPanSpeed:s,autoPanOnNodeDrag:r}=t();if(!r){o=!1,cancelAnimationFrame(l);return}let[i,u]=o7(c,d,s);(0!==i||0!==u)&&(n.x=(n.x??0)-i/e[2],n.y=(n.y??0)-u/e[2],await a({x:i,y:u})&&j(n)),l=requestAnimationFrame(w)}function N(s){let{nodeLookup:r,multiSelectionActive:l,nodesDraggable:o,transform:c,snapGrid:h,snapToGrid:p,selectNodesOnDrag:m,onNodeDragStart:x,onSelectionDragStart:g,unselectNodesAndEdges:f}=t();u=!0,m&&_||l||!v||r.get(v)?.selected||f(),_&&m&&v&&e?.(v);let b=cy(s.sourceEvent,{transform:c,snapGrid:h,snapToGrid:p,containerBounds:d});if(n=b,(i=function(e,t,a,s){let r=new Map;for(let[n,l]of e)if((l.selected||l.id===s)&&(!l.parentId||!function e(t,a){if(!t.parentId)return!1;let s=a.get(t.parentId);return!!s&&(!!s.selected||e(s,a))}(l,e))&&(l.draggable||t&&void 0===l.draggable)){let t=e.get(n);t&&r.set(n,{id:n,position:t.position||{x:0,y:0},distance:{x:a.x-t.internals.positionAbsolute.x,y:a.y-t.internals.positionAbsolute.y},extent:t.extent,parentId:t.parentId,origin:t.origin,expandParent:t.expandParent,internals:{positionAbsolute:t.internals.positionAbsolute||{x:0,y:0}},measured:{width:t.measured.width??0,height:t.measured.height??0}})}return r}(r,o,b,v)).size>0&&(a||x||!v&&g)){let[e,t]=c2({nodeId:v,dragItems:i,nodeLookup:r});a?.(s.sourceEvent,i,e,t),x?.(s.sourceEvent,e,t),v||g?.(s.sourceEvent,t)}}h=l3(b);let k=id().clickDistance(y).on("start",e=>{let{domNode:a,nodeDragThreshold:s,transform:r,snapGrid:l,snapToGrid:i}=t();d=a?.getBoundingClientRect()||null,p=!1,m=!1,x=e.sourceEvent,0===s&&N(e),n=cy(e.sourceEvent,{transform:r,snapGrid:l,snapToGri
10d:i,containerBounds:d}),c=cS(e.sourceEvent,d)}).on("drag",e=>{let{autoPanOnNodeDrag:a,transform:s,snapGrid:r,snapToGrid:l,nodeDragThreshold:h,nodeLookup:m}=t(),g=cy(e.sourceEvent,{transform:s,snapGrid:r,snapToGrid:l,containerBounds:d});if(x=e.sourceEvent,("touchmove"===e.sourceEvent.type&&e.sourceEvent.touches.length>1||v&&!m.has(v))&&(p=!0),!p){if(!o&&a&&u&&(o=!0,w()),!u){let t=cS(e.sourceEvent,d),a=t.x-c.x,s=t.y-c.y;Math.sqrt(a*a+s*s)>h&&N(e)}(n.x!==g.xSnapped||n.y!==g.ySnapped)&&i&&u&&(c=cS(e.sourceEvent,d),j(g))}}).on("end",e=>{if(!u||p){p&&i.size>0&&t().updateNodePositions(i,!1);return}if(o=!1,u=!1,cancelAnimationFrame(l),i.size>0){let{nodeLookup:a,updateNodePositions:s,onNodeDragStop:n,onSelectionDragStop:l}=t();if(m&&(s(i,!1),m=!1),r||n||!v&&l){let[t,s]=c2({nodeId:v,dragItems:i,nodeLookup:a,dragging:!1});r?.(e.sourceEvent,i,t,s),n?.(e.sourceEvent,t,s),v||l?.(e.sourceEvent,s)}}}).filter(e=>{let t=e.target;return!e.button&&(!g||!c1(t,`.${g}`,b))&&(!f||c1(t,f,b))});h.call(k)},destroy:function(){h?.on(".drag",null)}}}({getStoreItems:()=>i.getState(),onNodeMouseDown:t=>{um({id:t,store:i,nodeRef:e})},onDragStart:()=>{c(!0)},onDragStop:()=>{c(!1)}})},[]),(0,_.useEffect)(()=>{if(!t&&e.current&&d.current)return d.current.update({noDragClassName:a,handleSelector:s,domNode:e.current,isSelectable:n,nodeId:r,nodeClickDistance:l}),()=>{d.current?.destroy()}},[a,s,t,n,e,r,l]),o}function ug(){let e=dk();return(0,_.useCallback)(t=>{let{nodeExtent:a,snapToGrid:s,snapGrid:r,nodesDraggable:n,onError:l,updateNodePositions:i,nodeLookup:o,nodeOrigin:c}=e.getState(),d=new Map,u=e=>e.selected&&(e.draggable||n&&void 0===e.draggable),h=s?r[0]:5,p=s?r[1]:5,m=t.direction.x*h*t.factor,x=t.direction.y*p*t.factor;for(let[,e]of o){if(!u(e))continue;let t={x:e.internals.positionAbsolute.x+m,y:e.internals.positionAbsolute.y+x};s&&(t=cd(t,r));let{position:n,positionAbsolute:i}=o5({nodeId:e.id,nextPosition:t,nodeLookup:o,nodeExtent:a,nodeOrigin:c,onError:l});e.position=n,e.internals.positionAbsolute=i,d.set(e.id,e)}i(d)},[])}let uf=(0,_.createContext)(null),ub=uf.Provider;uf.Consumer;let u_=()=>(0,_.useContext)(uf),uv=e=>({connectOnClick:e.connectOnClick,noPanClassName:e.noPanClassName,rfId:e.rfId}),uy=(0,_.memo)(d8(function({type:e="source",position:t=x.Top,isValidConnection:a,isConnectable:s=!0,isConnectableStart:r=!0,isConnectableEnd:n=!0,id:l,onConnect:i,children:o,className:c,onMouseDown:u,onTouchStart:h,...p},m){let g=l||null,f="target"===e,_=dk(),v=u_(),{connectOnClick:y,noPanClassName:j,rfId:w}=dN(uv,dv),{connectingFrom:N,connectingTo:k,clickConnecting:S,isPossibleEndHandle:$,connectionInProcess:C,clickConnectionInProcess:M,valid:E}=dN(t=>{let{connectionClickStartHandle:a,connectionMode:s,connection:r}=t,{fromHandle:n,toHandle:l,isValid:i}=r,o=l?.nodeId===v&&l?.id===g&&l?.type===e;return{connectingFrom:n?.nodeId===v&&n?.id===g&&n?.type===e,connectingTo:o,clickConnecting:a?.nodeId===v&&a?.id===g&&a?.type===e,isPossibleEndHandle:s===d.Strict?n?.type!==e:v!==n?.nodeId||g!==n?.id,connectionInProcess:!!n,clickConnectionInProcess:!!a,valid:o&&i}},dv);v||_.getState().onError?.("010","Handle: No node id found. Make sure to only use a Handle inside a custom Node.");let A=e=>{let{defaultEdgeOptions:t,onConnect:a,hasDefaultEdges:s}=_.getState(),r={...t,...e};if(s){let{edges:e,setEdges:t,onError:a}=_.getState();t(d3(r,e,{onError:a}))}a?.(r),i?.(r)},T=e=>{if(!v)return;let t="clientX"in e.nativeEvent;if(r&&(t&&0===e.button||!t)){let t=_.getState();c8(e.nativeEvent,{handleDomNode:e.currentTarget,autoPanOnConnect:t.autoPanOnConnect,connectionMode:t.connectionMode,connectionRadius:t.connectionRadius,domNode:t.domNode,nodeLookup:t.nodeLookup,lib:t.lib,isTarget:f,handleId:g,nodeId:v,flowId:t.rfId,panBy:t.panBy,cancelConnection:t.cancelConnection,onConnectStart:t.onConnectStart,onConnectEnd:(...e)=>_.getState().onConnectEnd?.(...e),updateConnection:t.updateConnection,onConnect:A,isValidConnection:a||((...e)=>_.getState().isValidConnection?.(...e)??!0),getTransform:()=>_.getState().transform,getFromHandle:()=>_.getState().connection.fromHandle,autoPanSpeed:t.autoPanSpeed,dragThreshold:t.connectionDragThreshold})}t?u?.(e):h?.(e)};return(0,b.jsx)("div",{"data-handleid":g,"data-nodeid":v,"data-handlepos":t,"data-id":`${w}-${v}-${g}-${e}`,className:lp(["react-flow__handle",`react-flow__handle-${t}`,"nodrag",j,c,{source:!f,target:f,connectable:s,connectablestart:r,connectableend:n,clickconnecting:S,connectingfrom:N,connectingto:k,valid:E,connectionindicator:s&&(!C||$)&&(C||M?n:r)}]),onMouseDown:T,onTouchStart:T,onClick:y?t=>{let{onClickConnectStart:s,onClickConnectEnd:n,connectionClickStartHandle:l,connectionMode:i,isValidConnection:o,lib:c,rfId:d,nodeLookup:u,connection:h}=_.getState();if(!v||!l&&!r)return;if(!l){s?.(t.nativeEvent,{nodeId:v,handleId:g,handleType:e}),_.setState({connectionClickStartHandle:{nodeId:v,type:e,id:g}});return}let p=cw(t.target),m=a||o,{connection:x,isValid:f}=c6(t.nativeEvent,{handle:{nodeId:v,id:g,type:e},connectionMode:i,fromNodeId:l.nodeId,fromHandleId:l.id||null,fromType:l.type,isValidConnection:m,flowId:d,doc:p,lib:c,nodeLookup:u});f&&x&&A(x);let b=structuredClone(h);delete b.inProgress,b.toPosition=b.toHandle?b.toHandle.position:null,n?.(t,b),_.setState({connectionClickStartHandle:null})}:void 0,ref:m,...p,children:o})})),uj={ArrowUp:{x:0,y:-1},ArrowDown:{x:0,y:1},ArrowLeft:{x:-1,y:0},ArrowRight:{x:1,y:0}},uw={input:function({data:e,isConnectable:t,sourcePosition:a=x.Bottom}){return(0,b.jsxs)(b.Fragment,{children:[e?.label,(0,b.jsx)(uy,{type:"source",position:a,isConnectable:t})]})},default:function({data:e,isConnectable:t,targetPosition:a=x.Top,sourcePosition:s=x.Bottom}){return(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(uy,{type:"target",position:a,isConnectable:t}),e?.label,(0,b.jsx)(uy,{type:"source",position:s,isConnectable:t})]})},output:function({data:e,isConnectable:t,targetPosition:a=x.Top}){return(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(uy,{type:"target",position:a,isConnectable:t}),e?.label]})},group:function(){return null}},uN=e=>{let{width:t,height:a,x:s,y:r}=o0(e.nodeLookup,{filter:e=>!!e.selected});return{width:co(t)?t:null,height:co(a)?a:null,userSelectionActive:e.userSelectionActive,transformString:`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]}) translate(${s}px,${r}px)`}};function uk({onSelectionContextMenu:e,noPanClassName:t,disableKeyboardA11y:a}){let s=dk(),{width:r,height:n,transformString:l,userSelectionActive:i}=dN(uN,dv),o=ug(),c=(0,_.useRef)(null);(0,_.useEffect)(()=>{a||c.current?.focus({preventScroll:!0})},[a]);let d=!i&&null!==r&&null!==n;if(ux({nodeRef:c,disabled:!d}),!d)return null;let u=e?t=>{e(t,s.getState().nodes.filter(e=>e.selected))}:void 0;return(0,b.jsx)("div",{className:lp(["react-flow__nodesselection","react-flow__container",t]),style:{transform:l},children:(0,b.jsx)("div",{ref:c,className:"react-flow__nodesselection-rect",onContextMenu:u,tabIndex:a?void 0:-1,onKeyDown:a?void 0:e=>{Object.prototype.hasOwnProperty.call(uj,e.key)&&(e.preventDefault(),o({direction:uj[e.key],factor:e.shiftKey?4:1}))},style:{width:r,height:n}})})}let uS="u">typeof window?window:void 0,u$=e=>({nodesSelectionActive:e.nodesSelectionActive,userSelectionActive:e.userSelectionActive});function uC({children:e,onPaneClick:t,onPaneMouseEnter:a,onPaneMouseMove:s,onPaneMouseLeave:r,onPaneContextMenu:n,onPaneScroll:l,paneClickDistance:i,deleteKeyCode:o,selectionKeyCode:c,selectionOnDrag:d,selectionMode:u,onSelectionStart:h,onSelectionEnd:p,multiSelectionKeyCode:m,panActivationKeyCode:x,zoomActivationKeyCode:g,elementsSelectable:f,zoomOnScroll:v,zoomOnPinch:y,panOnScroll:j,panOnScrollSpeed:w,panOnScrollMode:N,zoomOnDoubleClick:k,panOnDrag:S,autoPanOnSelection:$,defaultViewport:C,translateExtent:M,minZoom:E,maxZoom:A,preventScrolling:T,onSelectionContextMenu:F,noWheelClassName:P,noPanClassName:R,disableKeyboardA11y:O,onViewportChange:L,isControlledViewport:I}){let{nodesSelectionActive:D,userSelectionActive:z}=dN(u$,dv),B=dK(c,{target:uS}),W=dK(x,{target:uS}),U=W||S,H=W||j,q=d&&!0!==U,V=B||z||q;return!function({deleteKeyCode:e,multiSelectionKeyCode:t}){let a=dk(),{deleteElements:s}=us(),r=dK(e,{actInsideInputWithModifier:!1}),n=dK(t,{target:un});(0,_.useEffect)(()=>
10{if(r){let{edges:e,nodes:t}=a.getState();s({nodes:t.filter(ur),edges:e.filter(ur)}),a.setState({nodesSelectionActive:!1})}},[r]),(0,_.useEffect)(()=>{a.setState({multiSelectionActive:n})},[n])}({deleteKeyCode:o,multiSelectionKeyCode:m}),(0,b.jsx)(uo,{onPaneContextMenu:n,elementsSelectable:f,zoomOnScroll:v,zoomOnPinch:y,panOnScroll:H,panOnScrollSpeed:w,panOnScrollMode:N,zoomOnDoubleClick:k,panOnDrag:!B&&U,defaultViewport:C,translateExtent:M,minZoom:E,maxZoom:A,zoomActivationKeyCode:g,preventScrolling:T,noWheelClassName:P,noPanClassName:R,onViewportChange:L,isControlledViewport:I,paneClickDistance:i,selectionOnDrag:q,children:(0,b.jsxs)(up,{onSelectionStart:h,onSelectionEnd:p,onPaneClick:t,onPaneMouseEnter:a,onPaneMouseMove:s,onPaneMouseLeave:r,onPaneContextMenu:n,onPaneScroll:l,panOnDrag:U,autoPanOnSelection:$,isSelecting:!!V,selectionMode:u,selectionKeyPressed:B,paneClickDistance:i,selectionOnDrag:q,children:[e,D&&(0,b.jsx)(uk,{onSelectionContextMenu:F,noPanClassName:R,disableKeyboardA11y:O})]})})}uC.displayName="FlowRenderer";let uM=(0,_.memo)(uC),uE=e=>e.updateNodeInternals;var uA=(0,_.memo)(function({id:e,onClick:t,onMouseEnter:a,onMouseMove:s,onMouseLeave:r,onContextMenu:n,onDoubleClick:l,nodesDraggable:i,elementsSelectable:o,nodesConnectable:c,nodesFocusable:d,resizeObserver:u,noDragClassName:h,noPanClassName:p,disableKeyboardA11y:m,rfId:x,nodeTypes:g,nodeClickDistance:f,onError:v}){let y,{node:j,internals:w,isParent:N}=dN(t=>{let a=t.nodeLookup.get(e),s=t.parentLookup.has(e);return{node:a,internals:a.internals,isParent:s}},dv),k=j.type||"default",S=g?.[k]||uw[k];void 0===S&&(v?.("003",(y=k,`Node type "${y}" not found. Using fallback type "default".`)),k="default",S=g?.default||uw.default);let $=!!(j.draggable||i&&void 0===j.draggable),C=!!(j.selectable||o&&void 0===j.selectable),M=!!(j.
10connectable||c&&void 0===j.connectable),E=!!(j.focusable||d&&void 0===j.focusable),A=dk(),T=cb(j),F=function({node:e,nodeType:t,hasDimensions:a,resizeObserver:s}){let r=dk(),n=(0,_.useRef)(null),l=(0,_.useRef)(null),i=(0,_.useRef)(e.sourcePosition),o=(0,_.useRef)(e.targetPosition),c=(0,_.useRef)(t),d=a&&!!e.internals.handleBounds;return(0,_.useEffect)(()=>{!n.current||e.hidden||d&&l.current===n.current||(l.current&&s?.unobserve(l.current),s?.observe(n.current),l.current=n.current)},[d,e.hidden]),(0,_.useEffect)(()=>()=>{l.current&&(s?.unobserve(l.current),l.current=null)},[]),(0,_.useEffect)(()=>{if(n.current){let a=c.current!==t,s=i.current!==e.sourcePosition,l=o.current!==e.targetPosition;(a||s||l)&&(c.current=t,i.current=e.sourcePosition,o.current=e.targetPosition,r.getState().updateNodeInternals(new Map([[e.id,{id:e.id,nodeElement:n.current,force:!0}]])))}},[e.id,t,e.sourcePosition,e.targetPosition]),n}({node:j,nodeType:k,hasDimensions:T,resizeObserver:u}),P=ux({nodeRef:F,disabled:j.hidden||!$,noDragClassName:h,handleSelector:j.dragHandle,nodeId:e,isSelectable:C,nodeClickDistance:f}),R=ug();if(j.hidden)return null;let O=cf(j),L=void 0===j.internals.handleBounds?{width:j.width??j.initialWidth??j.style?.width,height:j.height??j.initialHeight??j.style?.height}:{width:j.width??j.style?.width,height:j.height??j.style?.height},I=C||$||t||a||s||r,D=a?e=>a(e,{...w.userNode}):void 0,z=s?e=>s(e,{...w.userNode}):void 0,B=r?e=>r(e,{...w.userNode}):void 0,W=n?e=>n(e,{...w.userNode}):void 0,U=l?e=>l(e,{...w.userNode}):void 0;return(0,b.jsx)("div",{className:lp(["react-flow__node",`react-flow__node-${k}`,{[p]:$},j.className,{selected:j.selected,selectable:C,parent:N,draggable:$,dragging:P}]),ref:F,style:{zIndex:w.z,transform:`translate(${w.positionAbsolute.x}px,${w.positionAbsolute.y}px)`,pointerEvents:I?"all":"none",visibility:T?"visible":"hidden",...j.style,...L},"data-id":e,"data-testid":`rf__node-${e}`,onMouseEnter:D,onMouseMove:z,onMouseLeave:B,onContextMenu:W,onClick:a=>{let{selectNodesOnDrag:s,nodeDragThreshold:r}=A.getState();C&&(!s||!$||r>0)&&um({id:e,store:A,nodeRef:F}),t&&t(a,{...w.userNode})},onDoubleClick:U,onKeyDown:E?t=>{if(!ck(t.nativeEvent)&&!m){if(oV.includes(t.key)&&C)um({id:e,store:A,unselect:"Escape"===t.key,nodeRef:F});else if($&&j.selected&&Object.prototype.hasOwnProperty.call(uj,t.key)){t.preventDefault();let{ariaLabelConfig:e}=A.getState();A.setState({ariaLiveMessage:e["node.a11yDescription.ariaLiveMessage"]({direction:t.key.replace("Arrow","").toLowerCase(),x:~~w.positionAbsolute.x,y:~~w.positionAbsolute.y})}),R({direction:uj[t.key],factor:t.shiftKey?4:1})}}}:void 0,tabIndex:E?0:void 0,onFocus:E?()=>{if(m||!F.current?.matches(":focus-visible"))return;let{transform:t,width:a,height:s,autoPanOnNodeFocus:r,setCenter:n}=A.getState();!r||o1(new Map([[e,j]]),{x:0,y:0,width:a,height:s},t,!0).length>0||n(j.position.x+O.width/2,j.position.y+O.height/2,{zoom:t[2]})}:void 0,role:j.ariaRole??(E?"group":void 0),"aria-roledescription":"node","aria-describedby":m?void 0:`${dC}-${x}`,"aria-label":j.ariaLabel,...j.domAttributes,children:(0,b.jsx)(ub,{value:e,children:(0,b.jsx)(S,{id:e,data:j.data,type:k,positionAbsoluteX:w.positionAbsolute.x,positionAbsoluteY:w.positionAbsolute.y,selected:j.selected??!1,selectable:C,draggable:$,deletable:j.deletable??!0,isConnectable:M,sourcePosition:j.sourcePosition,targetPosition:j.targetPosition,dragging:P,dragHandle:j.dragHandle,zIndex:w.z,parentId:j.parentId,...O})})})});let uT=e=>({nodesDraggable:e.nodesDraggable,nodesConnectable:e.nodesConnectable,nodesFocusable:e.nodesFocusable,elementsSelectable:e.elementsSelectable,onError:e.onError});function uF(e){var t;let{nodesDraggable:a,nodesConnectable:s,nodesFocusable:r,elementsSelectable:n,onError:l}=dN(uT,dv),i=(t=e.onlyRenderVisibleElements,dN((0,_.useCallback)(e=>t?o1(e.nodeLookup,{x:0,y:0,width:e.width,height:e.height},e.transform,!0).map(e=>e.id):Array.from(e.nodeLookup.keys()),[t]),dv)),o=function(){let e=dN(uE),[t]=(0,_.useState)(()=>"u"<typeof ResizeObserver?null:new ResizeObserver(t=>{let a=new Map;t.forEach(e=>{let t=e.target.getAttribute("data-id");a.set(t,{id:t,nodeElement:e.target,force:!0})}),e(a)}));return(0,_.useEffect)(()=>()=>{t?.disconnect()},[t]),t}();return(0,b.jsx)("div",{className:"react-flow__nodes",style:ul,children:i.map(t=>(0,b.jsx)(uA,{id:t,nodeTypes:e.nodeTypes,nodeExtent:e.nodeExtent,onClick:e.onNodeClick,onMouseEnter:e.onNodeMouseEnter,onMouseMove:e.onNodeMouseMove,onMouseLeave:e.onNodeMouseLeave,onContextMenu:e.onNodeContextMenu,onDoubleClick:e.onNodeDoubleClick,noDragClassName:e.noDragClassName,noPanClassName:e.noPanClassName,rfId:e.rfId,disableKeyboardA11y:e.disableKeyboardA11y,resizeObserver:o,nodesDraggable:a,nodesConnectable:s,nodesFocusable:r,elementsSelectable:n,nodeClickDistance:e.nodeClickDistance,onError:l},t))})}uF.displayName="NodeRenderer";let uP=(0,_.memo)(uF),uR={[m.Arrow]:({color:e="none",strokeWidth:t=1})=>{let a={strokeWidth:t,...e&&{stroke:e}};return(0,b.jsx)("polyline",{className:"arrow",style:a,strokeLinecap:"round",fill:"none",strokeLinejoin:"round",points:"-5,-4 0,0 -5,4"})},[m.ArrowClosed]:({color:e="none",strokeWidth:t=1})=>{let a={strokeWidth:t,...e&&{stroke:e,fill:e}};return(0,b.jsx)("polyline",{className:"arrowclosed",style:a,strokeLinecap:"round",strokeLinejoin:"round",points:"-5,-4 0,0 -5,4 -5,-4"})}},uO=({id:e,type:t,color:a,width:s=12.5,height:r=12.5,markerUnits:n="strokeWidth",strokeWidth:l,orient:i="auto-start-reverse"})=>{let o,c=(o=dk(),(0,_.useMemo)(()=>{let e;return Object.prototype.hasOwnProperty.call(uR,t)?uR[t]:(o.getState().onError?.("009",(e=t,`Marker type "${e}" doesn't exist.`)),null)},[t]));return c?(0,b.jsx)("marker",{className:"react-flow__arrowhead",id:e,markerWidth:`${s}`,markerHeight:`${r}`,viewBox:"-10 -10 20 20",markerUnits:n,orient:i,refX:"0",refY:"0",children:(0,b.jsx)(c,{color:a,strokeWidth:l})}):null},uL=({defaultColor:e,rfId:t})=>{let a=dN(e=>e.edges),s=dN(e=>e.defaultEdgeOptions),r=(0,_.useMemo)(()=>(function(e,{id:t,defaultColor:a,defaultMarkerStart:s,defaultMarkerEnd:r}){let n=new Set;return e.reduce((e,l)=>([l.markerStart||s,l.markerEnd||r].forEach(s=>{if(s&&"object"==typeof s){let r=cU(s,t);n.has(r)||(e.push({id:r,color:s.color||a,...s}),n.add(r))}}),e),[]).sort((e,t)=>
10e.id.localeCompare(t.id))})(a,{id:t,defaultColor:e,defaultMarkerStart:s?.markerStart,defaultMarkerEnd:s?.markerEnd}),[a,s,t,e]);return r.length?(0,b.jsx)("svg",{className:"react-flow__marker","aria-hidden":"true",children:(0,b.jsx)("defs",{children:r.map(e=>(0,b.jsx)(uO,{id:e.id,type:e.type,color:e.color,width:e.width,height:e.height,markerUnits:e.markerUnits,strokeWidth:e.strokeWidth,orient:e.orient},e.id))})}):null};uL.displayName="MarkerDefinitions";var uI=(0,_.memo)(uL);function uD({x:e,y:t,label:a,labelStyle:s,labelShowBg:r=!0,labelBgStyle:n,labelBgPadding:l=[2,4],labelBgBorderRadius:i=2,children:o,className:c,...d}){let[u,h]=(0,_.useState)({x:1,y:0,width:0,height:0}),p=lp(["react-flow__edge-textwrapper",c]),m=(0,_.useRef)(null);return((0,_.useEffect)(()=>{if(m.current){let e=m.current.getBBox();h({x:e.x,y:e.y,width:e.width,height:e.height})}},[a]),a)?(0,b.jsxs)("g",{transform:`translate(${e-u.width/2} ${t-u.height/2})`,className:p,visibility:u.width?"visible":"hidden",...d,children:[r&&(0,b.jsx)("rect",{width:u.width+2*l[0],x:-l[0],y:-l[1],height:u.height+2*l[1],className:"react-flow__edge-textbg",style:n,rx:i,ry:i}),(0,b.jsx)("text",{className:"react-flow__edge-text",y:u.height/2,dy:"0.3em",ref:m,style:s,children:a}),o]}):null}uD.displayName="EdgeText";let uz=(0,_.memo)(uD);function uB({path:e,labelX:t,labelY:a,label:s,labelStyle:r,labelShowBg:n,labelBgStyle:l,labelBgPadding:i,labelBgBorderRadius:o,interactionWidth:c=20,...d}){return(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)("path",{...d,d:e,fill:"none",className:lp(["react-flow__edge-path",d.className])}),c?(0,b.jsx)("path",{d:e,fill:"none",strokeOpacity:0,strokeWidth:c,className:"react-flow__edge-interaction"}):null,s&&co(t)&&co(a)?(0,b.jsx)(uz,{x:t,y:a,label:s,labelStyle:r,labelShowBg:n,labelBgStyle:l,labelBgPadding:i,labelBgBorderRadius:o}):null]})}function uW({pos:e,x1:t,y1:a,x2:s,y2:r}){return e===x.Left||e===x.Right?[.5*(t+s),a]:[t,.5*(a+r)]}function uU({sourceX:e,sourceY:t,sourcePosition:a=x.Bottom,targetX:s,targetY:r,targetPosition:n=x.Top}){let[l,i]=uW({pos:a,x1:e,y1:t,x2:s,y2:r}),[o,c]=uW({pos:n,x1:s,y1:r,x2:e,y2:t}),[d,u,h,p]=cC({sourceX:e,sourceY:t,targetX:s,targetY:r,sourceControlX:l,sourceControlY:i,targetControlX:o,targetControlY:c});return[`M${e},${t} C${l},${i} ${o},${c} ${s},${r}`,d,u,h,p]}function uH(e){return(0,_.memo)(({id:t,sourceX:a,sourceY:s,targetX:r,targetY:n,sourcePosition:l,targetPosition:i,label:o,labelStyle:c,labelShowBg:d,labelBgStyle:u,labelBgPadding:h,labelBgBorderRadius:p,style:m,markerEnd:x,markerStart:g,interactionWidth:f})=>{let[_,v,y]=uU({sourceX:a,sourceY:s,sourcePosition:l,targetX:r,targetY:n,targetPosition:i}),j=e.isInternal?void 0:t;return(0,b.jsx)(uB,{id:j,path:_,labelX:v,labelY:y,label:o,labelStyle:c,labelShowBg:d,labelBgStyle:u,labelBgPadding:h,labelBgBorderRadius:p,style:m,markerEnd:x,markerStart:g,interactionWidth:f})})}let uq=uH({isInternal:!1}),uV=uH({isInternal:!0});function uG(e){return(0,_.memo)(({id:t,sourceX:a,sourceY:s,targetX:r,targetY:n,label:l,labelStyle:i,labelShowBg:o,labelBgStyle:c,labelBgPadding:d,labelBgBorderRadius:u,style:h,sourcePosition:p=x.Bottom,targetPosition:m=x.Top,markerEnd:g,markerStart:f,pathOptions:_,interactionWidth:v})=>{let[y,j,w]=cI({sourceX:a,sourceY:s,sourcePosition:p,targetX:r,targetY:n,targetPosition:m,borderRadius:_?.borderRadius,offset:_?.offset,stepPosition:_?.stepPosition}),N=e.isInternal?void 0:t;return(0,b.jsx)(uB,{id:N,path:y,labelX:j,labelY:w,label:l,labelStyle:i,labelShowBg:o,labelBgStyle:c,labelBgPadding:d,labelBgBorderRadius:u,style:h,markerEnd:g,markerStart:f,interactionWidth:v})})}uq.displayName="SimpleBezierEdge",uV.displayName="SimpleBezierEdgeInternal";let uJ=uG({isInternal:!1}),uY=uG({isInternal:!0});function uK(e){return(0,_.memo)(({id:t,...a})=>{let s=e.isInternal?void 0:t;return(0,b.jsx)(uJ,{...a,id:s,pathOptions:(0,_.useMemo)(()=>({borderRadius:0,offset:a.pathOptions?.offset}),[a.pathOptions?.offset])})})}uJ.displayName="SmoothStepEdge",uY.displayName="SmoothStepEdgeInternal";let uX=uK({isInternal:!1}),uZ=uK({isInternal:!0});function uQ(e){return(0,_.memo)(({id:t,sourceX:a,sourceY:s,targetX:r,targetY:n,label:l,labelStyle:i,labelShowBg:o,labelBgStyle:c,labelBgPadding:d,labelBgBorderRadius:u,style:h,markerEnd:p,markerStart:m,interactionWidth:x})=>{let[g,f,_]=cP({sourceX:a,sourceY:s,targetX:r,targetY:n}),v=e.isInternal?void 0:t;return(0,b.jsx)(uB,{id:v,path:g,labelX:f,labelY:_,label:l,labelStyle:i,labelShowBg:o,labelBgStyle:c,labelBgPadding:d,labelBgBorderRadius:u,style:h,markerEnd:p,markerStart:m,interactionWidth:x})})}uX.displayName="StepEdge",uZ.displayName="StepEdgeInternal";let u0=uQ({isInternal:!1}),u1=uQ({isInternal:!0});function u2(e){return(0,_.memo)(({id:t,sourceX:a,sourceY:s,targetX:r,targetY:n,sourcePosition:l=x.Bottom,targetPosition:i=x.Top,label:o,labelStyle:c,labelShowBg:d,labelBgStyle:u,labelBgPadding:h,labelBgBorderRadius:p,style:m,markerEnd:g,markerStart:f,pathOptions:_,interactionWidth:v})=>{let[y,j,w]=cA({sourceX:a,sourceY:s,sourcePosition:l,targetX:r,targetY:n,targetPosition:i,curvature:_?.curvature}),N=e.isInternal?void 0:t;return(0,b.jsx)(uB,{id:N,path:y,labelX:j,labelY:w,label:o,labelStyle:c,labelShowBg:d,labelBgStyle:u,labelBgPadding:h,labelBgBorderRadius:p,style:m,markerEnd:g,markerStart:f,interactionWidth:v})})}u0.displayName="StraightEdge",u1.displayName="StraightEdgeInternal";let u5=u2({isInternal:!1}),u4=u2({isInternal:!0});u5.displayName="BezierEdge",u4.displayName="BezierEdgeInternal";let u3={default:u4,straight:u1,step:uZ,smoothstep:uY,simplebezier:uV},u6={sourceX:null,sourceY:null,targetX:null,targetY:null,sourcePosition:null,targetPosition:null},u8="react-flow__edgeupdater";function u9({position:e,centerX:t,centerY:a,radius:s=10,onMouseDown:r,onMouseEnter:n,onMouseOut:l,type:i}){return(0,b.jsx)("circle",{onMouseDown:r,onMouseEnter:n,onMouseOut:l,className:lp([u8,`${u8}-${i}`]),cx:e===x.Left?t-s:e===x.Right?t+s:t,cy:e===x.Top?a-s:e===x.Bottom?a+s:a,r:s,stroke:"transparent",fill:"transparent"})}function u7({isReconnectable:e,reconnectRadius:t,edge:a,sourceX:s,sourceY:r,targetX:n,targetY:l,sourcePosition:i,targetPosition:o,onReconnect:c,onReconnectStart:d,onReconnectEnd:u,setReconnecting:h,setUpdateHover:p}){let m=dk(),x=(e,t)=>{if(0!==e.button)return;let{autoPanOnConnect:s,domNode:r,connectionMode:n,connectionRadius:l,lib:i,onConnectStart:o,cancelConnection:p,nodeLookup:x,rfId:g,panBy:f,updateConnection:b}=m.getState(),_="target"===t.type;c8(e.nativeEvent,{autoPanOnConnect:s,connectionMode:n,connectionRadius:l,domNode:r,handleId:t.id,nodeId:t.nodeId,nodeLookup:x,isTarget:_,edgeUpdaterType:t.type,lib:i,flowId:g,cancelConnection:p,panBy:f,isValidConnection:(...e)=>
10m.getState().isValidConnection?.(...e)??!0,onConnect:e=>c?.(a,e),onConnectStart:(s,r)=>{h(!0),d?.(e,a,t.type),o?.(s,r)},onConnectEnd:(...e)=>m.getState().onConnectEnd?.(...e),onReconnectEnd:(e,s)=>{h(!1),u?.(e,a,t.type,s)},updateConnection:b,getTransform:()=>m.getState().transform,getFromHandle:()=>m.getState().connection.fromHandle,dragThreshold:m.getState().connectionDragThreshold,handleDomNode:e.currentTarget})},g=()=>p(!0),f=()=>p(!1);return(0,b.jsxs)(b.Fragment,{children:[(!0===e||"source"===e)&&(0,b.jsx)(u9,{position:i,centerX:s,centerY:r,radius:t,onMouseDown:e=>x(e,{nodeId:a.target,id:a.targetHandle??null,type:"target"}),onMouseEnter:g,onMouseOut:f,type:"source"}),(!0===e||"target"===e)&&(0,b.jsx)(u9,{position:o,centerX:n,centerY:l,radius:t,onMouseDown:e=>x(e,{nodeId:a.source,id:a.sourceHandle??null,type:"source"}),onMouseEnter:g,onMouseOut:f,type:"target"})]})}var he=(0,_.memo)(function({id:e,edgesFocusable:t,edgesReconnectable:a,elementsSelectable:s,onClick:r,onDoubleClick:n,onContextMenu:l,onMouseEnter:i,onMouseMove:o,onMouseLeave:c,reconnectRadius:u,onReconnect:h,onReconnectStart:p,onReconnectEnd:m,rfId:g,edgeTypes:f,noPanClassName:v,onError:y,disableKeyboardA11y:j}){let w,N=dN(t=>t.edgeLookup.get(e)),k=dN(e=>e.defaultEdgeOptions),S=(N=k?{...k,...N}:N).type||"default",$=f?.[S]||u3[S];void 0===$&&(y?.("011",(w=S,`Edge type "${w}" not found. Using fallback type "default".`)),S="default",$=f?.default||u3.default);let C=!!(N.focusable||t&&void 0===N.focusable),M=void 0!==h&&(N.reconnectable||a&&void 0===N.reconnectable),E=!!(N.selectable||s&&void 0===N.selectable),A=(0,_.useRef)(null),[T,F]=(0,_.useState)(!1),[P,R]=(0,_.useState)(!1),O=dk(),{zIndex:L,sourceX:I,sourceY:D,targetX:z,targetY:B,sourcePosition:W,targetPosition:U}=dN((0,_.useCallback)(t=>{let a=t.nodeLookup.get(N.source),s=t.nodeLookup.get(N.target);if(!a||!s)return{zIndex:N.zIndex,...u6};let r=function(e){let{sourceNode:t,targetNode:a}=e;if(!cD(t)||!cD(a))return null;let s=t.internals.handleBounds||cz(t.handles),r=a.internals.handleBounds||cz(a.handles),n=cW(s?.source??[],e.sourceHandle),l=cW(e.connectionMode===d.Strict?r?.target??[]:(r?.target??[]).concat(r?.source??[]),e.targetHandle);if(!n||!l)return e.onError?.("008",((e,{id:t,sourceHandle:a,targetHandle:s})=>`Couldn't create edge for ${e} handle id: "${"source"===e?a:s}", edge id: ${t}.`)(!n?"source":"target",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;let i=n?.position||x.Bottom,o=l?.position||x.Top,c=cB(t,n,i),u=cB(a,l,o);return{sourceX:c.x,sourceY:c.y,targetX:u.x,targetY:u.y,sourcePosition:i,targetPosition:o}}({id:e,sourceNode:a,targetNode:s,sourceHandle:N.sourceHandle||null,targetHandle:N.targetHandle||null,connectionMode:t.connectionMode,onError:y});return{zIndex:function({sourceNode:e,targetNode:t,selected:a=!1,zIndex:s=0,elevateOnSelect:r=!1,zIndexMode:n="basic"}){if("manual"===n)return s;let l=Math.max(e.parentId||r&&e.selected?e.internals.z:0,t.parentId||r&&t.selected?t.internals.z:0);return(r&&a?s+1e3:s)+l}({selected:N.selected,zIndex:N.zIndex,sourceNode:a,targetNode:s,elevateOnSelect:t.elevateEdgesOnSelect,zIndexMode:t.zIndexMode}),...r||u6}},[N.source,N.target,N.sourceHandle,N.targetHandle,N.selected,N.zIndex]),dv),H=(0,_.useMemo)(()=>N.markerStart?`url('#${cU(N.markerStart,g)}')`:void 0,[N.markerStart,g]),q=(0,_.useMemo)(()=>N.markerEnd?`url('#${cU(N.markerEnd,g)}')`:void 0,[N.markerEnd,g]);if(N.hidden||null===I||null===D||null===z||null===B)return null;let V=n?e=>{n(e,{...N})}:void 0,G=l?e=>{l(e,{...N})}:void 0,J=i?e=>{i(e,{...N})}:void 0,Y=o?e=>{o(e,{...N})}:void 0,K=c?e=>{c(e,{...N})}:void 0;return(0,b.jsx)("svg",{style:{zIndex:L},children:(0,b.jsxs)("g",{className:lp(["react-flow__edge",`react-flow__edge-${S}`,N.className,v,{selected:N.selected,animated:N.animated,inactive:!E&&!r,updating:T,selectable:E}]),onClick:t=>{let{addSelectedEdges:a,unselectNodesAndEdges:s,multiSelectionActive:n}=O.getState();E&&(O.setState({nodesSelectionActive:!1}),N.selected&&n?(s({nodes:[],edges:[N]}),A.current?.blur()):a([e])),r&&r(t,N)},onDoubleClick:V,onContextMenu:G,onMouseEnter:J,onMouseMove:Y,onMouseLeave:K,onKeyDown:C?t=>{if(!j&&oV.includes(t.key)&&E){let{unselectNodesAndEdges:a,addSelectedEdges:s}=O.getState();"Escape"===t.key?(A.current?.blur(),a({edges:[N]})):s([e])}}:void 0,tabIndex:C?0:void 0,role:N.ariaRole??(C?"group":"img"),"aria-roledescription":"edge","data-id":e,"data-testid":`rf__edge-${e}`,"aria-label":null===N.ariaLabel?void 0:N.ariaLabel||`Edge from ${N.source} to ${N.target}`,"aria-describedby":C?`${dM}-${g}`:void 0,ref:A,...N.domAttributes,children:[!P&&(0,b.jsx)($,{id:e,source:N.source,target:N.target,type:N.type,selected:N.selected,animated:N.animated,selectable:E,deletable:N.deletable??!0,label:N.label,labelStyle:N.labelStyle,labelShowBg:N.labelShowBg,labelBgStyle:N.labelBgStyle,labelBgPadding:N.labelBgPadding,labelBgBorderRadius:N.labelBgBorderRadius,sourceX:I,sourceY:D,targetX:z,targetY:B,sourcePosition:W,targetPosition:U,data:N.data,style:N.style,sourceHandleId:N.sourceHandle,targetHandleId:N.targetHandle,markerStart:H,markerEnd:q,pathOptions:"pathOptions"in N?N.pathOptions:void 0,interactionWidth:N.interactionWidth}),M&&(0,b.jsx)(u7,{edge:N,isReconnectable:M,reconnectRadius:u,onReconnect:h,onReconnectStart:p,onReconnectEnd:m,sourceX:I,sourceY:D,targetX:z,targetY:B,sourcePosition:W,targetPosition:U,setUpdateHover:F,setReconnecting:R})]})})});let ht=e=>({edgesFocusable:e.edgesFocusable,edgesReconnectable:e.edgesReconnectable,elementsSelectable:e.elementsSelectable,connectionMode:e.connectionMode,onError:e.onError});function ha({defaultMarkerColor:e,onlyRenderVisibleElements:t,rfId:a,edgeTypes:s,noPanClassName:r,onReconnect:n,onEdgeContextMenu:l,onEdgeMouseEnter:i,onEdgeMouseMove:o,onEdgeMouseLeave:c,onEdgeClick:d,reconnectRadius:u,onEdgeDoubleClick:h,onReconnectStart:p,onReconnectEnd:m,disableKeyboardA11y:x}){let{edgesFocusable:g,edgesReconnectable:f,elementsSelectable:v,onError:y}=dN(ht,dv),j=dN((0,_.useCallback)(e=>{if(!t)return e.edges.map(e=>e.id);let a=[];if(e.width&&e.height)for(let t of e.edges){let s=e.nodeLookup.get(t.source),r=e.nodeLookup.get(t.target);s&&r&&function({sourceNode:e,targetNode:t,width:a,height:s,transform:r}){let n=ce(cr(e),cr(t));return n.x===n.x2&&(n.x2+=1),n.y===n.y2&&(n.y2+=1),cl({x:-r[0]/r[2],y:-r[1]/r[2],width:a/r[2],height:s/r[2]},ca(n))>0}({sourceNode:s,targetNode:r,width:e.width,height:e.height,transform:e.transform})&&a.push(t.id)}return a},[t]),dv);return(0,b.jsxs)("div",{className:"react-flow__edges",children:[(0,b.jsx)(uI,{defaultColor:e,rfId:a}),j.map(e=>(0,b.jsx)(he,{id:e,edgesFocusable:g,edgesReconnectable:f,elementsSelectable:v,noPanClassName:r,onReconnect:n,onContextMenu:l,onMouseEnter:i,onMouseMove:o,onMouseLeave:c,onClick:d,reconnectRadius:u,onDoubleClick:h,onReconnectStart:p,onReconnectEnd:m,rfId:a,onError:y,edgeTypes:s,disableKeyboardA11y:x},e))]})}ha.displayName="EdgeRenderer";let hs=(0,_.memo)(ha),hr=e=>`translate(${e.transform[0]}px,${e.transform[1]}px) scale(${e.transform[2]})`;function hn({children:e}){let t=dN(hr);return(0,b.jsx)("div",{className:"react-flow__viewport xyflow__viewport react-flow__container",style:{transform:t},children:e})}let hl=e=>e.panZoom?.syncViewport;function hi(e){return e.connection.inProgress?{...e.connection,to:cu(e.connection.to,e.transform)}:{...e.connection}}let ho=e=>({nodesConnectable:e.nodesConnectable,isValid:e.connection.isValid,inProgress:e.connection.inProgress,width:e.width,height:e.height});function hc({containerStyle:e,style:t,type:a,component:s}){let{nodesConnectable:r,width:n,height:l,isValid:i,inProgress:o}=dN(ho,dv);return n&&r&&o?(0,b.jsx)("svg",{style:e,width:n,height:l,className:"react-flow__connectionline react-flow__container",children:(0,b.jsx)("g",{className:lp(["react-flow__connection",oK(i)]),children:(0,b.jsx)(hd,{style:t,type:a,CustomComponent:s,isValid:i})})}):null}let hd=({style:e,type:t=p.Bezier,CustomComponent:a,isValid:s})=>{let{inProgress:r,from:n,fromNode:l,fromHandle:i,fromPosition:o,to:c,toNode:d,toHandle:u,toPosition:h,pointer:m}=dN(hi,dv);if(!r)return;if(a)return(0,b.jsx)(a,{connectionLineType:t,connectionLineStyle:e,fromNode:l,fromHandle:i,fromX:n.x,fromY:n.y,toX:c.x,toY:c.y,fromPosition:o,toPosition:h,connectionStatus:oK(s),toNode:d,toHandle:u,pointer:m});let x="",g={sourceX:n.x,sourceY:n.y,sourcePosition:o,targetX:c.x,targetY:c.y,targetPosition:h};switch(t){case p.Bezier:[x]=cA(g);break;case p.SimpleBezier:[x]=uU(g);break;case p.Step:[x]=cI({...g,borderRadius:0});break;case p.SmoothStep:[x]=cI(g);break;default:[x]=cP(g)}return(0,b.jsx)("path",{d:x,fill:"none",className:"react-flow__connection-path",style:e})};hd.displayName="ConnectionLine";let hu={};function hh(e=hu){(0,_.useRef)(e),dk(),(0,_.useEffect)(()=>{},[e])}function hp({nodeTypes:e,edgeTypes:t,onInit:a,onNodeClick:s,onEdgeClick:r,onNodeDoubleClick:n,onEdgeDoubleClick:l,onNodeMouseEnter:i,onNodeMouseMove:o,onNodeMouseLeave:c,onNodeContextMenu:d,onSelectionContextMenu:u,onSelectionStart:h,onSelectionEnd:p,connectionLineType:m,connectionLineStyle:x,connectionLineComponent:g,connectionLineContainerStyle:f,selectionKeyCode:v,selectionOnDrag:y,selectionMode:j,multiSelectionKeyCode:w,panActivationKeyCode:N,zoomActivationKeyCode:k,deleteKeyCode:S,onlyRenderVisibleElements:$,elementsSelectable:C,defaultViewport:M,translateExtent:E,minZoom:A,maxZoom:T,preventScrolling:F,defaultMarkerColor:P,zoomOnScroll:R,zoomOnPinch:O,panOnScroll:L,panOnScrollSpeed:I,panOnScrollMode:D,zoomOnDoubleClick:z,panOnDrag:B,autoPanOnSelection:W,onPaneClick:U,onPaneMouseEnter:H,onPaneMouseMove:q,onPaneMouseLeave:V,onPaneScroll:G,onPaneContextMenu:J,paneClickDistance:Y,nodeClickDistance:K,onEdgeContextMenu:X,onEdgeMouseEnter:Z,onEdgeMouseMove:Q,onEdgeMouseLeave:ee,reconnectRadius:et,onReconnect:ea,onReconnectStart:es,onReconnectEnd:er,noDragClassName:en,noWheelClassName:el,noPanClassName:ei,disableKeyboardA11y:eo,nodeExtent:ec,rfId:ed,viewport:eu,onViewportChange:eh}){let ep,em,ex,eg;return hh(e),hh(t),dk(),(0,_.useRef)(!1),(0,_.useEffect)(()=>{},[]),ep=us(),em=(0,_.useRef)(!1),(0,_.useEffect)(()=>{!em.current&&ep.viewportInitialized&&a&&(setTimeout(()=>a(ep),1),em.current=!0)}
10,[a,ep.viewportInitialized]),ex=dN(hl),eg=dk(),(0,_.useEffect)(()=>{eu&&(ex?.(eu),eg.setState({transform:[eu.x,eu.y,eu.zoom]}))},[eu,ex]),(0,b.jsx)(uM,{onPaneClick:U,onPaneMouseEnter:H,onPaneMouseMove:q,onPaneMouseLeave:V,onPaneContextMenu:J,onPaneScroll:G,paneClickDistance:Y,deleteKeyCode:S,selectionKeyCode:v,selectionOnDrag:y,selectionMode:j,onSelectionStart:h,onSelectionEnd:p,multiSelectionKeyCode:w,panActivationKeyCode:N,zoomActivationKeyCode:k,elementsSelectable:C,zoomOnScroll:R,zoomOnPinch:O,zoomOnDoubleClick:z,panOnScroll:L,panOnScrollSpeed:I,panOnScrollMode:D,panOnDrag:B,autoPanOnSelection:W,defaultViewport:M,translateExtent:E,minZoom:A,maxZoom:T,onSelectionContextMenu:u,preventScrolling:F,noDragClassName:en,noWheelClassName:el,noPanClassName:ei,disableKeyboardA11y:eo,onViewportChange:eh,isControlledViewport:!!eu,children:(0,b.jsxs)(hn,{children:[(0,b.jsx)(hs,{edgeTypes:t,onEdgeClick:r,onEdgeDoubleClick:l,onReconnect:ea,onReconnectStart:es,onReconnectEnd:er,onlyRenderVisibleElements:$,onEdgeContextMenu:X,onEdgeMouseEnter:Z,onEdgeMouseMove:Q,onEdgeMouseLeave:ee,reconnectRadius:et,defaultMarkerColor:P,noPanClassName:ei,disableKeyboardA11y:eo,rfId:ed}),(0,b.jsx)(hc,{style:x,type:m,component:g,containerStyle:f}),(0,b.jsx)("div",{className:"react-flow__edgelabel-renderer"}),(0,b.jsx)(uP,{nodeTypes:e,onNodeClick:s,onNodeDoubleClick:n,onNodeMouseEnter:i,onNodeMouseMove:o,onNodeMouseLeave:c,onNodeContextMenu:d,nodeClickDistance:K,onlyRenderVisibleElements:$,noPanClassName:ei,noDragClassName:en,disableKeyboardA11y:eo,nodeExtent:ec,rfId:ed}),(0,b.jsx)("div",{className:"react-flow__viewport-portal"})]})})}hp.displayName="GraphView";let hm=(0,_.memo)(hp),hx=cc("React Flow","https://reactflow.dev/"),hg=({nodes:e,edges:t,defaultNodes:a,defaultEdges:s,width:r,height:n,fitView:l,fitViewOptions:i,minZoom:o=.5,maxZoom:c=2,nodeOrigin:u,nodeExtent:h,zIndexMode:p="basic"}={})=>{let m=new Map,x=new Map,g=new Map,f=new Map,b=s??t??[],_=a??e??[],v=u??[0,0],y=h??oq;c0(g,f,b);let{nodesInitialized:j}=cJ(_,m,x,{nodeOrigin:v,nodeExtent:y,zIndexMode:p}),w=[0,0,1];if(l&&r&&n){let{x:e,y:t,zoom:a}=cm(o0(m,{filter:e=>!!((e.width||e.initialWidth)&&(e.height||e.initialHeight))}),r,n,o,c,i?.padding??.1);w=[e,t,a]}return{rfId:"1",width:r??0,height:n??0,transform:w,nodes:_,nodesInitialized:j,nodeLookup:m,parentLookup:x,edges:b,edgeLookup:f,connectionLookup:g,onNodesChange:null,onEdgesChange:null,hasDefaultNodes:void 0!==a,hasDefaultEdges:void 0!==s,panZoom:null,minZoom:o,maxZoom:c,translateExtent:oq,nodeExtent:y,nodesSelectionActive:!1,userSelectionActive:!1,userSelectionRect:null,connectionMode:d.Strict,domNode:null,paneDragging:!1,noPanClassName:"nopan",nodeOrigin:v,nodeDragThreshold:1,connectionDragThreshold:1,snapGrid:[15,15],snapToGrid:!1,nodesDraggable:!0,nodesConnectable:!0,nodesFocusable:!0,edgesFocusable:!0,edgesReconnectable:!0,elementsSelectable:!0,elevateNodesOnSelect:!0,elevateEdgesOnSelect:!0,selectNodesOnDrag:!0,multiSelectionActive:!1,fitViewQueued:l??!1,fitViewOptions:i,fitViewResolver:null,connection:{...oJ},connectionClickStartHandle:null,connectOnClick:!0,ariaLiveMessage:"",autoPanOnConnect:!0,autoPanOnNodeDrag:!0,autoPanOnNodeFocus:!0,autoPanSpeed:15,connectionRadius:20,onError:hx,isValidConnection:void 0,onSelectionChangeHandlers:[],lib:"react",debug:!1,ariaLabelConfig:oG,zIndexMode:p,onNodesChangeMiddlewareMap:new Map,onEdgesChangeMiddlewareMap:new Map}};function hf({initialNodes:e,initialEdges:t,defaultNodes:a,defaultEdges:s,initialWidth:r,initialHeight:n,initialMinZoom:l,initialMaxZoom:i,initialFitViewOptions:o,fitView:c,nodeOrigin:d,nodeExtent:u,zIndexMode:h,children:p}){let[m]=(0,_.useState)(()=>(({nodes:e,edges:t,defaultNodes:a,defaultEdges:s,width:r,height:n,fitView:l,fitViewOptions:i,minZoom:o,maxZoom:c,nodeOrigin:d,nodeExtent:u,zIndexMode:h})=>{let p,m;return p=(p,m)=>{async function g(){let{nodeLookup:e,panZoom:t,fitViewOptions:a,fitViewResolver:s,width:r,height:n,minZoom:l,maxZoom:i}=m();
10t&&(await o2({nodes:e,width:r,height:n,panZoom:t,minZoom:l,maxZoom:i},a),s?.resolve(!0),p({fitViewResolver:null}))}return{...hg({nodes:e,edges:t,width:r,height:n,fitView:l,fitViewOptions:i,minZoom:o,maxZoom:c,nodeOrigin:d,nodeExtent:u,defaultNodes:a,defaultEdges:s,zIndexMode:h}),setNodes:e=>{let{nodeLookup:t,parentLookup:a,nodeOrigin:s,elevateNodesOnSelect:r,fitViewQueued:n,zIndexMode:l,nodesSelectionActive:i}=m(),{nodesInitialized:o,hasSelectedNodes:c}=cJ(e,t,a,{nodeOrigin:s,nodeExtent:u,elevateNodesOnSelect:r,checkEquality:!0,zIndexMode:l}),d=i&&c;n&&o?(g(),p({nodes:e,nodesInitialized:o,fitViewQueued:!1,fitViewOptions:void 0,nodesSelectionActive:d})):p({nodes:e,nodesInitialized:o,nodesSelectionActive:d})},setEdges:e=>{let{connectionLookup:t,edgeLookup:a}=m();c0(t,a,e),p({edges:e})},setDefaultNodesAndEdges:(e,t)=>{if(e){let{setNodes:t}=m();t(e),p({hasDefaultNodes:!0})}if(t){let{setEdges:e}=m();e(t),p({hasDefaultEdges:!0})}},updateNodeInternals:e=>{let{triggerNodeChanges:t,nodeLookup:a,parentLookup:s,domNode:r,nodeOrigin:n,nodeExtent:l,debug:i,fitViewQueued:o,zIndexMode:c}=m(),{changes:d,updatedInternals:u}=function(e,t,a,s,r,n,l){let i=s?.querySelector(".xyflow__viewport"),o=!1;if(!i)return{changes:[],updatedInternals:o};let c=[],d=window.getComputedStyle(i),{m22:u}=new window.DOMMatrixReadOnly(d.transform),h=[];for(let s of e.values()){let e=t.get(s.id);if(!e)continue;if(e.hidden){t.set(e.id,{...e,internals:{...e.internals,handleBounds:void 0}}),o=!0;continue}let i=cj(s.nodeElement),d=e.measured.width!==i.width||e.measured.height!==i.height;if(i.width&&i.height&&(d||!e.internals.handleBounds||s.force)){let p=s.nodeElement.getBoundingClientRect(),m=cg(e.extent)?e.extent:n,{positionAbsolute:x}=e.internals;e.parentId&&"parent"===e.extent?x=o8(x,i,t.get(e.parentId)):m&&(x=o6(x,m,i));let g={...e,measured:i,internals:{...e.internals,positionAbsolute:x,handleBounds:{source:c$("source",s.nodeElement,p,u,e.id),target:c$("target",s.nodeElement,p,u,e.id)}}};t.set(e.id,g),e.parentId&&cY(g,t,a,{nodeOrigin:r,zIndexMode:l}),o=!0,d&&(c.push({id:e.id,type:"dimensions",dimensions:i}),e.expandParent&&e.parentId&&h.push({id:e.id,parentId:e.parentId,rect:cs(g,r)}))}}if(h.length>0){let e=cX(h,t,a,r);c.push(...e)}return{changes:c,updatedInternals:o}}(e,a,s,r,n,l,c);u&&(!function(e,t,a){let s=cV(cH,a);for(let a of e.values())if(a.parentId)cY(a,e,t,s);else{let e=o6(oQ(a,s.nodeOrigin),cg(a.extent)?a.extent:s.nodeExtent,cf(a));a.internals.positionAbsolute=e}}(a,s,{nodeOrigin:n,nodeExtent:l,zIndexMode:c}),o?(g(),p({fitViewQueued:!1,fitViewOptions:void 0})):p({}),d?.length>0&&(i&&console.log("React Flow: trigger node changes",d),t?.(d)))},updateNodePositions:(e,t=!1)=>{let a=[],s=[],{nodeLookup:r,triggerNodeChanges:n,connection:l,updateConnection:i,onNodesChangeMiddlewareMap:o}=m();for(let[n,o]of e){let e=r.get(n),c=!!(e?.expandParent&&e?.parentId&&o?.position),d={id:n,type:"position",position:c?{x:Math.max(0,o.position.x),y:Math.max(0,o.position.y)}:o.position,dragging:t};if(e&&l.inProgress&&l.fromNode.id===e.id){let t=cB(e,l.fromHandle,x.Left,!0);i({...l,from:t})}c&&e.parentId&&a.push({id:n,parentId:e.parentId,rect:{...o.internals.positionAbsolute,width:o.measured.width??0,height:o.measured.height??0}}),s.push(d)}if(a.length>0){let{parentLookup:e,nodeOrigin:t}=m(),n=cX(a,r,e,t);s.push(...n)}for(let e of o.values())s=e(s);n(s)},triggerNodeChanges:e=>{let{onNodesChange:t,setNodes:a,nodes:s,hasDefaultNodes:r,debug:n}=m();e?.length&&(r&&a(dQ(e,s)),n&&console.log("React Flow: trigger node changes",e),t?.(e))},triggerEdgeChanges:e=>{let{onEdgesChange:t,setEdges:a,edges:s,hasDefaultEdges:r,debug:n}=m();e?.length&&(r&&a(dQ(e,s)),n&&console.log("React Flow: trigger edge changes",e),t?.(e))},addSelectedNodes:e=>{let{multiSelectionActive:t,edgeLookup:a,nodeLookup:s,triggerNodeChanges:r,triggerEdgeChanges:n}=m();t?r(e.map(e=>d0(e,!0))):(r(d1(s,new Set([...e]),!0)),n(d1(a)))},addSelectedEdges:e=>{let{multiSelectionActive:t,edgeLookup:a,nodeLookup:s,triggerNodeChanges:r,triggerEdgeChanges:n}=m();t?n(e.map(e=>
10d0(e,!0))):(n(d1(a,new Set([...e]))),r(d1(s,new Set,!0)))},unselectNodesAndEdges:({nodes:e,edges:t}={})=>{let{edges:a,nodes:s,nodeLookup:r,triggerNodeChanges:n,triggerEdgeChanges:l}=m(),i=[];for(let t of e||s){if(!t.selected)continue;let e=r.get(t.id);e&&(e.selected=!1),i.push(d0(t.id,!1))}let o=[];for(let e of t||a)e.selected&&o.push(d0(e.id,!1));n(i),l(o)},setMinZoom:e=>{let{panZoom:t,maxZoom:a}=m();t?.setScaleExtent([e,a]),p({minZoom:e})},setMaxZoom:e=>{let{panZoom:t,minZoom:a}=m();t?.setScaleExtent([a,e]),p({maxZoom:e})},setTranslateExtent:e=>{m().panZoom?.setTranslateExtent(e),p({translateExtent:e})},resetSelectedElements:()=>{let{edges:e,nodes:t,triggerNodeChanges:a,triggerEdgeChanges:s,elementsSelectable:r}=m();if(!r)return;let n=t.reduce((e,t)=>t.selected?[...e,d0(t.id,!1)]:e,[]),l=e.reduce((e,t)=>t.selected?[...e,d0(t.id,!1)]:e,[]);a(n),s(l)},setNodeExtent:e=>{let{nodes:t,nodeLookup:a,parentLookup:s,nodeOrigin:r,elevateNodesOnSelect:n,nodeExtent:l,zIndexMode:i}=m();(e[0][0]!==l[0][0]||e[0][1]!==l[0][1]||e[1][0]!==l[1][0]||e[1][1]!==l[1][1])&&(cJ(t,a,s,{nodeOrigin:r,nodeExtent:e,elevateNodesOnSelect:n,checkEquality:!1,zIndexMode:i}),p({nodeExtent:e}))},panBy:e=>{let{transform:t,width:a,height:s,panZoom:r,translateExtent:n}=m();return cZ({delta:e,panZoom:r,transform:t,translateExtent:n,width:a,height:s})},setCenter:async(e,t,a)=>{let{width:s,height:r,maxZoom:n,panZoom:l}=m();if(!l)return!1;let i=void 0!==a?.zoom?a.zoom:n;return await l.setViewport({x:s/2-e*i,y:r/2-t*i,zoom:i},{duration:a?.duration,ease:a?.ease,interpolate:a?.interpolate}),!0},cancelConnection:()=>{p({connection:{...oJ}})},updateConnection:e=>{p({connection:e})},reset:()=>p({...hg()})}},m=Object.is,p?d_(p,m):d_})({nodes:e,edges:t,defaultNodes:a,defaultEdges:s,width:r,height:n,fitView:c,minZoom:l,maxZoom:i,fitViewOptions:o,nodeOrigin:d,nodeExtent:u,zIndexMode:h}));return(0,b.jsx)(dj,{value:m,children:(0,b.jsx)(ut,{children:p})})}function hb({children:e,nodes:t,edges:a,defaultNodes:s,defaultEdges:r,width:n,height:l,fitView:i,fitViewOptions:o,minZoom:c,maxZoom:d,nodeOrigin:u,nodeExtent:h,zIndexMode:p}){return(0,_.useContext)(dy)?(0,b.jsx)(b.Fragment,{children:e}):(0,b.jsx)(hf,{initialNodes:t,initialEdges:a,defaultNodes:s,defaultEdges:r,initialWidth:n,initialHeight:l,fitView:i,initialFitViewOptions:o,initialMinZoom:c,initialMaxZoom:d,nodeOrigin:u,nodeExtent:h,zIndexMode:p,children:e})}let h_={width:"100%",height:"100%",overflow:"hidden",position:"relative",zIndex:0};var hv=d8(function({nodes:e,edges:t,defaultNodes:a,defaultEdges:s,className:r,nodeTypes:n,edgeTypes:l,onNodeClick:i,onEdgeClick:o,onInit:c,onMove:d,onMoveStart:m,onMoveEnd:x,onConnect:g,onConnectStart:f,onConnectEnd:v,onClickConnectStart:y,onClickConnectEnd:j,onNodeMouseEnter:w,onNodeMouseMove:N,onNodeMouseLeave:k,onNodeContextMenu:S,onNodeDoubleClick:$,onNodeDragStart:C,onNodeDrag:M,onNodeDragStop:E,onNodesDelete:A,onEdgesDelete:T,onDelete:F,onSelectionChange:P,onSelectionDragStart:R,onSelectionDrag:O,onSelectionDragStop:L,onSelectionContextMenu:I,onSelectionStart:D,onSelectionEnd:z,onBeforeDelete:B,connectionMode:W,connectionLineType:U=p.Bezier,connectionLineStyle:H,connectionLineComponent:q,connectionLineContainerStyle:V,deleteKeyCode:G="Backspace",selectionKeyCode:J="Shift",selectionOnDrag:Y=!1,selectionMode:K=h.Full,panActivationKeyCode:X="Space",multiSelectionKeyCode:Z=cx()?"Meta":"Control",zoomActivationKeyCode:Q=cx()?"Meta":"Control",snapToGrid:ee,snapGrid:et,onlyRenderVisibleElements:ea=!1,selectNodesOnDrag:es,nodesDraggable:er,autoPanOnNodeFocus:en,nodesConnectable:el,nodesFocusable:ei,nodeOrigin:eo=dW,edgesFocusable:ec,edgesReconnectable:ed,elementsSelectable:eu=!0,defaultViewport:eh=dU,minZoom:ep=.5,maxZoom:em=2,translateExtent:ex=oq,preventScrolling:eg=!0,nodeExtent:ef,defaultMarkerColor:eb="#b1b1b7",zoomOnScroll:e_=!0,zoomOnPinch:ev=!0,panOnScroll:ey=!1,panOnScrollSpeed:ej=.5,panOnScrollMode:ew=u.Free,zoomOnDoubleClick:eN=!0,panOnDrag:ek=!0,onPaneClick:eS,onPaneMouseEnter:e$,onPaneMouseMove:eC,onPaneMouseLeave:eM,onPaneScroll:eE,onPaneContextMenu:eA,paneClickDistance:eT=1,nodeClickDistance:eF=0,children:eP,onReconnect:eR,onReconnectStart:eO,onReconnectEnd:eL,onEdgeContextMenu:eI,onEdgeDoubleClick:eD,onEdgeMouseEnter:ez,onEdgeMouseMove:eB,onEdgeMouseLeave:eW,reconnectRadius:eU=10,onNodesChange:eH,onEdgesChange:eq,noDragClassName:eV="nodrag",noWheelClassName:eG="nowheel",noPanClassName:eJ="nopan",fitView:eY,fitViewOptions:eK,connectOnClick:eX,attributionPosition:eZ,proOptions:eQ,defaultEdgeOptions:e0,elevateNodesOnSelect:e1=!0,elevateEdgesOnSelect:e2=!1,disableKeyboardA11y:e5=!1,autoPanOnConnect:e4,autoPanOnNodeDrag:e3,autoPanOnSelection:e6=!0,autoPanSpeed:e8,connectionRadius:e9,isValidConnection:e7,onError:te,style:tt,id:ta,nodeDragThreshold:ts,connectionDragThreshold:tr,viewport:tn,onViewportChange:tl,width:ti,height:to,colorMode:tc="light",debug:td,onScroll:tu,ariaLabelConfig:th,zIndexMode:tp="basic",...tm}
10,tx){let tg=ta||"1",tf=function(e){let[t,a]=(0,_.useState)("system"===e?null:e);return(0,_.useEffect)(()=>{if("system"!==e)return void a(e);let t=dJ(),s=()=>a(t?.matches?"dark":"light");return s(),t?.addEventListener("change",s),()=>{t?.removeEventListener("change",s)}},[e]),null!==t?t:dJ()?.matches?"dark":"light"}(tc),tb=(0,_.useCallback)(e=>{e.currentTarget.scrollTo({top:0,left:0,behavior:"instant"}),tu?.(e)},[tu]);return(0,b.jsx)("div",{"data-testid":"rf__wrapper",...tm,onScroll:tb,style:{...tt,...h_},ref:tx,className:lp(["react-flow",r,tf]),id:ta,role:"application",children:(0,b.jsxs)(hb,{nodes:e,edges:t,width:ti,height:to,fitView:eY,fitViewOptions:eK,minZoom:ep,maxZoom:em,nodeOrigin:eo,nodeExtent:ef,zIndexMode:tp,children:[(0,b.jsx)(dG,{nodes:e,edges:t,defaultNodes:a,defaultEdges:s,onConnect:g,onConnectStart:f,onConnectEnd:v,onClickConnectStart:y,onClickConnectEnd:j,nodesDraggable:er,autoPanOnNodeFocus:en,nodesConnectable:el,nodesFocusable:ei,edgesFocusable:ec,edgesReconnectable:ed,elementsSelectable:eu,elevateNodesOnSelect:e1,elevateEdgesOnSelect:e2,minZoom:ep,maxZoom:em,nodeExtent:ef,onNodesChange:eH,onEdgesChange:eq,snapToGrid:ee,snapGrid:et,connectionMode:W,translateExtent:ex,connectOnClick:eX,defaultEdgeOptions:e0,fitView:eY,fitViewOptions:eK,onNodesDelete:A,onEdgesDelete:T,onDelete:F,onNodeDragStart:C,onNodeDrag:M,onNodeDragStop:E,onSelectionDrag:O,onSelectionDragStart:R,onSelectionDragStop:L,onMove:d,onMoveStart:m,onMoveEnd:x,noPanClassName:eJ,nodeOrigin:eo,rfId:tg,autoPanOnConnect:e4,autoPanOnNodeDrag:e3,autoPanSpeed:e8,onError:te,connectionRadius:e9,isValidConnection:e7,selectNodesOnDrag:es,nodeDragThreshold:ts,connectionDragThreshold:tr,onBeforeDelete:B,debug:td,ariaLabelConfig:th,zIndexMode:tp}),(0,b.jsx)(hm,{onInit:c,onNodeClick:i,onEdgeClick:o,onNodeMouseEnter:w,onNodeMouseMove:N,onNodeMouseLeave:k,onNodeContextMenu:S,onNodeDoubleClick:$,nodeTypes:n,edgeTypes:l,connectionLineType:U,connectionLineStyle:H,connectionLineComponent:q,connectionLineContainerStyle:V,selectionKeyCode:J,selectionOnDrag:Y,selectionMode:K,deleteKeyCode:G,multiSelectionKeyCode:Z,panActivationKeyCode:X,zoomActivationKeyCode:Q,onlyRenderVisibleElements:ea,defaultViewport:eh,translateExtent:ex,minZoom:ep,maxZoom:em,preventScrolling:eg,zoomOnScroll:e_,zoomOnPinch:ev,zoomOnDoubleClick:eN,panOnScroll:ey,panOnScrollSpeed:ej,panOnScrollMode:ew,panOnDrag:ek,autoPanOnSelection:e6,onPaneClick:eS,onPaneMouseEnter:e$,onPaneMouseMove:eC,onPaneMouseLeave:eM,onPaneScroll:eE,onPaneContextMenu:eA,paneClickDistance:eT,nodeClickDistance:eF,onSelectionContextMenu:I,onSelectionStart:D,onSelectionEnd:z,onReconnect:eR,onReconnectStart:eO,onReconnectEnd:eL,onEdgeContextMenu:eI,onEdgeDoubleClick:eD,onEdgeMouseEnter:ez,onEdgeMouseMove:eB,onEdgeMouseLeave:eW,reconnectRadius:eU,defaultMarkerColor:eb,noDragClassName:eV,noWheelClassName:eG,noPanClassName:eJ,rfId:tg,disableKeyboardA11y:e5,nodeExtent:ef,viewport:tn,onViewportChange:tl}),(0,b.jsx)(dB,{onSelectionChange:P}),eP,(0,b.jsx)(dR,{proOptions:eQ,position:eZ}),(0,b.jsx)(dF,{rfId:tg,disableKeyboardA11y:e5})]})})});function hy({dimensions:e,lineWidth:t,variant:a,className:s}){return(0,b.jsx)("path",{strokeWidth:t,d:`M${e[0]/2} 0 V${e[1]} M0 ${e[1]/2} H${e[0]}`,className:lp(["react-flow__background-pattern",a,s])})}function hj({radius:e,className:t}){return(0,b.jsx)("circle",{cx:e,cy:e,r:e,className:lp(["react-flow__background-pattern","dots",t])})}(o=f||(f={})).Lines="lines",o.Dots="dots",o.Cross="cross";let hw={[f.Dots]:1,[f.Lines]:1,[f.Cross]:6},hN=e=>({transform:e.transform,patternId:`pattern-${e.rfId}`});function hk({id:e,variant:t=f.Dots,gap:a=20,size:s,lineWidth:r=1,offset:n=0,color:l,bgColor:i,style:o,className:c,patternClassName:d}){let u=(0,_.useRef)(null),{transform:h,patternId:p}=dN(hN,dv),m=s||hw[t],x=t===f.Dots,g=t===f.Cross,v=Array.isArray(a)?a:[a,a],y=[v[0]*h[2]||1,v[1]*h[2]||1],j=m*h[2],w=Array.isArray(n)?n:[n,n],N=g?[j,j]:y,k=[w[0]*h[2]||1+N[0]/2,w[1]*h[2]||1+N[1]/2],S=`${p}${e||""}`;return(0,b.jsxs)("svg",{className:lp(["react-flow__background",c]),style:{...o,...ul,"--xy-background-color-props":i,"--xy-background-pattern-color-props":l},ref:u,"data-testid":"rf__background",children:[(0,b.jsx)("pattern",{id:S,x:h[0]%y[0],y:h[1]%y[1],width:y[0],height:y[1],patternUnits:"userSpaceOnUse",patternTransform:`translate(-${k[0]}
10,-${k[1]})`,children:x?(0,b.jsx)(hj,{radius:j/2,className:d}):(0,b.jsx)(hy,{dimensions:N,lineWidth:r,variant:t,className:d})}),(0,b.jsx)("rect",{x:"0",y:"0",width:"100%",height:"100%",fill:`url(#${S})`})]})}hk.displayName="Background";let hS=(0,_.memo)(hk);function h$(){return(0,b.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 32",children:(0,b.jsx)("path",{d:"M32 18.133H18.133V32h-4.266V18.133H0v-4.266h13.867V0h4.266v13.867H32z"})})}function hC(){return(0,b.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 5",children:(0,b.jsx)("path",{d:"M0 0h32v4.2H0z"})})}function hM(){return(0,b.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 32 30",children:(0,b.jsx)("path",{d:"M3.692 4.63c0-.53.4-.938.939-.938h5.215V0H4.708C2.13 0 0 2.054 0 4.63v5.216h3.692V4.631zM27.354 0h-5.2v3.692h5.17c.53 0 .984.4.984.939v5.215H32V4.631A4.624 4.624 0 0027.354 0zm.954 24.83c0 .532-.4.94-.939.94h-5.215v3.768h5.215c2.577 0 4.631-2.13 4.631-4.707v-5.139h-3.692v5.139zm-23.677.94c-.531 0-.939-.4-.939-.94v-5.138H0v5.139c0 2.577 2.13 4.707 4.708 4.707h5.138V25.77H4.631z"})})}function hE(){return(0,b.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32",children:(0,b.jsx)("path",{d:"M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0 8 0 4.571 3.429 4.571 7.619v3.048H3.048A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047zm4.724-13.866H7.467V7.619c0-2.59 2.133-4.724 4.723-4.724 2.591 0 4.724 2.133 4.724 4.724v3.048z"})})}function hA(){return(0,b.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 25 32",children:(0,b.jsx)("path",{d:"M21.333 10.667H19.81V7.619C19.81 3.429 16.38 0 12.19 0c-4.114 1.828-1.37 2.133.305 2.438 1.676.305 4.42 2.59 4.42 5.181v3.048H3.047A3.056 3.056 0 000 13.714v15.238A3.056 3.056 0 003.048 32h18.285a3.056 3.056 0 003.048-3.048V13.714a3.056 3.056 0 00-3.048-3.047zM12.19 24.533a3.056 3.056 0 01-3.047-3.047 3.056 3.056 0 013.047-3.048 3.056 3.056 0 013.048 3.048 3.056 3.056 0 01-3.048 3.047z"})})}function hT({children:e,className:t,...a}){return(0,b.jsx)("button",{type:"button",className:lp(["react-flow__controls-button",t]),...a,children:e})}let hF=e=>({isInteractive:e.nodesDraggable||e.nodesConnectable||e.elementsSelectable,minZoomReached:e.transform[2]<=e.minZoom,maxZoomReached:e.transform[2]>=e.maxZoom,ariaLabelConfig:e.ariaLabelConfig});function hP({style:e,showZoom:t=!0,showFitView:a=!0,showInteractive:s=!0,fitViewOptions:r,onZoomIn:n,onZoomOut:l,onFitView:i,onInteractiveChange:o,className:c,children:d,position:u="bottom-left",orientation:h="vertical","aria-label":p}){let m=dk(),{isInteractive:x,minZoomReached:g,maxZoomReached:f,ariaLabelConfig:_}=dN(hF,dv),{zoomIn:v,zoomOut:y,fitView:j}=us();return(0,b.jsxs)(dP,{className:lp(["react-flow__controls","horizontal"===h?"horizontal":"vertical",c]),position:u,style:e,"data-testid":"rf__controls","aria-label":p??_["controls.ariaLabel"],children:[t&&(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)(hT,{onClick:()=>{v(),n?.()},className:"react-flow__controls-zoomin",title:_["controls.zoomIn.ariaLabel"],"aria-label":_["controls.zoomIn.ariaLabel"],disabled:f,children:(0,b.jsx)(h$,{})}),(0,b.jsx)(hT,{onClick:()=>{y(),l?.()},className:"react-flow__controls-zoomout",title:_["controls.zoomOut.ariaLabel"],"aria-label":_["controls.zoomOut.ariaLabel"],disabled:g,children:(0,b.jsx)(hC,{})})]}),a&&(0,b.jsx)(hT,{className:"react-flow__controls-fitview",onClick:()=>{j(r),i?.()},title:_["controls.fitView.ariaLabel"],"aria-label":_["controls.fitView.ariaLabel"],children:(0,b.jsx)(hM,{})}),s&&(0,b.jsx)(hT,{className:"react-flow__controls-interactive",onClick:()=>{m.setState({nodesDraggable:!x,nodesConnectable:!x,elementsSelectable:!x}),o?.(!x)},title:_["controls.interactive.ariaLabel"],"aria-label":_["controls.interactive.ariaLabel"],children:x?(0,b.jsx)(hA,{}):(0,b.jsx)(hE,{})}),d]})}hP.displayName="Controls";let hR=(0,_.memo)(hP),hO=(0,_.memo)(function({id:e,x:t,y:a,width:s,height:r,style:n,color:l,strokeColor:i,strokeWidth:o,className:c,borderRadius:d,shapeRendering:u,selected:h,onClick:p}){let{background:m,backgroundColor:x}=n||{};return(0,b.jsx)("rect",{className:lp(["react-flow__minimap-node",{selected:h},c]),x:t,y:a,rx:d,ry:d,width:s,height:r,style:{fill:l||m||x,stroke:i,strokeWidth:o},shapeRendering:u,onClick:p?t=>p(t,e):void 0})}),hL=e=>e.nodes.map(e=>e.id),hI=e=>e instanceof Function?e:()=>e,hD=(0,_.memo)(function({id:e,nodeColorFunc:t,nodeStrokeColorFunc:a,nodeClassNameFunc:s,nodeBorderRadius:r,nodeStrokeWidth:n,shapeRendering:l,NodeComponent:i,onClick:o}){let{node:c,x:d,y:u,width:h,height:p}=dN(t=>{let a=t.nodeLookup.get(e);if(!a)return{node:void 0,x:0,y:0,width:0,height:0};let s=a.internals.userNode,{x:r,y:n}=a.internals.positionAbsolute,{width:l,height:i}=cf(s);return{node:s,x:r,y:n,width:l,height:i}},dv);return c&&!c.hidden&&cb(c)?(0,b.jsx)(i,{x:d,y:u,width:h,height:p,style:c.style,selected:!!c.selected,className:s(c),color:t(c),borderRadius:r,strokeColor:a(c),strokeWidth:n,shapeRendering:l,onClick:o,id:c.id}):null});var hz=(0,_.memo)(function({nodeStrokeColor:e,nodeColor:t,nodeClassName:a="",nodeBorderRadius:s=5,nodeStrokeWidth:r,nodeComponent:n=hO,onClick:l}){let i=dN(hL,dv),o=hI(t),c=hI(e),d=hI(a),u="u"<typeof window||window.chrome?"crispEdges":"geometricPrecision";return(0,b.jsx)(b.Fragment,{children:i.map(e=>(0,b.jsx)(hD,{id:e,nodeColorFunc:o,nodeStrokeColorFunc:c,nodeClassNameFunc:d,nodeBorderRadius:s,nodeStrokeWidth:r,NodeComponent:n,onClick:l,shapeRendering:u},e))})});let hB=e=>!e.hidden,hW=e=>{let t={x:-e.transform[0]/e.transform[2],y:-e.transform[1]/e.transform[2],width:e.width/e.transform[2],height:e.height/e.transform[2]};
10return{viewBB:t,boundingRect:e.nodeLookup.size>0?cn(o0(e.nodeLookup,{filter:hB}),t):t,rfId:e.rfId,panZoom:e.panZoom,translateExtent:e.translateExtent,flowWidth:e.width,flowHeight:e.height,ariaLabelConfig:e.ariaLabelConfig}};function hU({style:e,className:t,nodeStrokeColor:a,nodeColor:s,nodeClassName:r="",nodeBorderRadius:n=5,nodeStrokeWidth:l,nodeComponent:i,bgColor:o,maskColor:c,maskStrokeColor:d,maskStrokeWidth:u,position:h="bottom-right",onClick:p,onNodeClick:m,pannable:x=!1,zoomable:g=!1,ariaLabel:f,inversePan:v,zoomStep:y=1,offsetScale:j=5}){let w=dk(),N=(0,_.useRef)(null),{boundingRect:k,viewBB:S,rfId:$,panZoom:C,translateExtent:M,flowWidth:E,flowHeight:A,ariaLabelConfig:T}=dN(hW,dv),F=e?.width??200,P=e?.height??150,R=Math.max(k.width/F,k.height/P),O=R*F,L=R*P,I=j*R,D=k.x-(O-k.width)/2-I,z=k.y-(L-k.height)/2-I,B=O+2*I,W=L+2*I,U=`react-flow__minimap-desc-${$}`,H=(0,_.useRef)(0),q=(0,_.useRef)();H.current=R,(0,_.useEffect)(()=>{if(N.current&&C)return q.current=function({domNode:e,panZoom:t,getTransform:a,getViewScale:s}){let r=l3(e);return{update:function({translateExtent:e,width:n,height:l,zoomStep:i=1,pannable:o=!0,zoomable:c=!0,inversePan:d=!1}){let u=[0,0],h=oU().on("start",e=>{("mousedown"===e.sourceEvent.type||"touchstart"===e.sourceEvent.type)&&(u=[e.sourceEvent.clientX??e.sourceEvent.touches[0].clientX,e.sourceEvent.clientY??e.sourceEvent.touches[0].clientY])}).on("zoom",o?r=>{let i=a();if("mousemove"!==r.sourceEvent.type&&"touchmove"!==r.sourceEvent.type||!t)return;let o=[r.sourceEvent.clientX??r.sourceEvent.touches[0].clientX,r.sourceEvent.clientY??r.sourceEvent.touches[0].clientY],c=[o[0]-u[0],o[1]-u[1]];u=o;let h=s()*Math.max(i[2],Math.log(i[2]))*(d?-1:1),p={x:i[0]-c[0]*h,y:i[1]-c[1]*h};t.setViewportConstrained({x:p.x,y:p.y,zoom:i[2]},[[0,0],[n,l]],e)}:null).on("zoom.wheel",c?e=>{if("wheel"!==e.sourceEvent.type||!t)return;let s=a(),r=e.sourceEvent.ctrlKey&&cx()?10:1,n=-e.sourceEvent.deltaY*(1===e.sourceEvent.deltaMode?.05:e.sourceEvent.deltaMode?1:.002)*i,l=s[2]*Math.pow(2,n*r);t.scaleTo(l)}:null);r.call(h,{})},destroy:function(){r.on("zoom",null)},pointer:l6}}({domNode:N.current,panZoom:C,getTransform:()=>w.getState().transform,getViewScale:()=>H.current}),()=>{q.current?.destroy()}},[C]),(0,_.useEffect)(()=>{q.current?.update({translateExtent:M,width:E,height:A,inversePan:v,pannable:x,zoomStep:y,zoomable:g})},[x,g,v,y,M,E,A]);let V=p?e=>{let[t,a]=q.current?.pointer(e)||[0,0];p(e,{x:t,y:a})}:void 0,G=m?(0,_.useCallback)((e,t)=>{m(e,w.getState().nodeLookup.get(t).internals.userNode)},[]):void 0,J=f??T["minimap.ariaLabel"];return(0,b.jsx)(dP,{position:h,style:{...e,"--xy-minimap-background-color-props":"string"==typeof o?o:void 0,"--xy-minimap-mask-background-color-props":"string"==typeof c?c:void 0,"--xy-minimap-mask-stroke-color-props":"string"==typeof d?d:void 0,"--xy-minimap-mask-stroke-width-props":"number"==typeof u?u*R:void 0,"--xy-minimap-node-background-color-props":"string"==typeof s?s:void 0,"--xy-minimap-node-stroke-color-props":"string"==typeof a?a:void 0,"--xy-minimap-node-stroke-width-props":"number"==typeof l?l:void 0},className:lp(["react-flow__minimap",t]),"data-testid":"rf__minimap",children:(0,b.jsxs)("svg",{width:F,height:P,viewBox:`${D} ${z} ${B} ${W}`,className:"react-flow__minimap-svg",role:"img","aria-labelledby":U,ref:N,onClick:V,children:[J&&(0,b.jsx)("title",{id:U,children:J}),(0,b.jsx)(hz,{onClick:G,nodeColor:s,nodeStrokeColor:a,nodeBorderRadius:n,nodeClassName:r,nodeStrokeWidth:l,nodeComponent:i}),(0,b.jsx)("path",{className:"react-flow__minimap-mask",d:`M${D-I},${z-I}h${B+2*I}v${W+2*I}h${-B-2*I}z
11        M${S.x},${S.y}h${S.width}v${S.height}h${-S.width}z`,fillRule:"evenodd",pointerEvents:"none"})]})})}hU.displayName="MiniMap";let hH=(0,_.memo)(hU),hq={[g.Line]:"right",[g.Handle]:"bottom-right"};(0,_.memo)(function({nodeId:e,position:t,variant:a=g.Handle,className:s,style:r,children:n,color:l,minWidth:i=10,minHeight:o=10,maxWidth:c=Number.MAX_VALUE,maxHeight:d=Number.MAX_VALUE,keepAspectRatio:u=!1,resizeDirection:h,autoScale:p=!0,shouldResize:m,onResizeStart:x,onResize:f,onResizeEnd:v}){let y,j=u_(),w="string"==typeof e?e:j,N=dk(),k=(0,_.useRef)(null),S=a===g.Handle,$=dN((0,_.useCallback)((y=S&&p,e=>y?`${Math.max(1/e.transform[2],1)}`:void 0),[S,p]),dv),C=(0,_.useRef)(null),M=t??hq[a];(0,_.useEffect)(()=>
11{if(k.current&&w)return C.current||(C.current=function({domNode:e,nodeId:t,getStoreItems:a,onChange:s,onEnd:r}){let n=l3(e),l={controlDirection:dn("bottom-right"),boundaries:{minWidth:0,minHeight:0,maxWidth:Number.MAX_VALUE,maxHeight:Number.MAX_VALUE},resizeDirection:void 0,keepAspectRatio:!1};return{update:function({controlPosition:e,boundaries:i,keepAspectRatio:o,resizeDirection:c,onResizeStart:d,onResize:u,onResizeEnd:h,shouldResize:p}){let m,x,g,f,b={...dd},_={...du};l={boundaries:i,resizeDirection:c,keepAspectRatio:o,controlDirection:dn(e)};let v=null,y=[],j=!1,w=id().on("start",e=>{let{nodeLookup:s,transform:r,snapGrid:n,snapToGrid:l,nodeOrigin:i,paneDomNode:o}=a();if(!(m=s.get(t)))return;v=o?.getBoundingClientRect()??null;let{xSnapped:c,ySnapped:u}=cy(e.sourceEvent,{transform:r,snapGrid:n,snapToGrid:l,containerBounds:v});for(let[e,a]of(_={...b={width:m.measured.width??0,height:m.measured.height??0,x:m.position.x??0,y:m.position.y??0},pointerX:c,pointerY:u,aspectRatio:b.width/b.height},x=void 0,g=cg(m.extent)?m.extent:void 0,m.parentId&&("parent"===m.extent||m.expandParent)&&(x=s.get(m.parentId)),x&&"parent"===m.extent&&(g=[[0,0],[x.measured.width,x.measured.height]]),y=[],f=void 0,s))if(a.parentId===t&&(y.push({id:e,position:{...a.position},extent:a.extent}),"parent"===a.extent||a.expandParent)){let e=function(e,t,a){let s=t.position.x+e.position.x,r=t.position.y+e.position.y,n=e.measured.width??0,l=e.measured.height??0,i=a[0]*n,o=a[1]*l;return[[s-i,r-o],[s+n-i,r+l-o]]}(a,m,a.origin??i);f=f?[[Math.min(e[0][0],f[0][0]),Math.min(e[0][1],f[0][1])],[Math.max(e[1][0],f[1][0]),Math.max(e[1][1],f[1][1])]]:e}d?.(e,{...b})}).on("drag",e=>{let{transform:t,snapGrid:r,snapToGrid:n,nodeOrigin:i}=a(),o=cy(e.sourceEvent,{transform:t,snapGrid:r,snapToGrid:n,containerBounds:v}),c=[];if(!m)return;let{x:d,y:h,width:w,height:N}=b,k={},S=m.origin??i,{width:$,height:C,x:M,y:E}=function(e,t,a,s,r,n,l,i){var o,c,d,u;let{affectsX:h,affectsY:p}=t,{isHorizontal:m,isVertical:x}=t,g=m&&x,{xSnapped:f,ySnapped:b}=a,{minWidth:_,maxWidth:v,minHeight:y,maxHeight:j}=s,{x:w,y:N,width:k,height:S,aspectRatio:$}=e,C=Math.floor(m?f-e.pointerX:0),M=Math.floor(x?b-e.pointerY:0),E=k+(h?-C:C),A=S+(p?-M:M),T=-n[0]*k,F=-n[1]*S,P=dc(E,_,v),R=dc(A,y,j);if(l){let e=0,t=0;h&&C<0?e=dl(w+C+T,l[0][0]):!h&&C>0&&(e=di(w+E+T,l[1][0])),p&&M<0?t=dl(N+M+F,l[0][1]):!p&&M>0&&(t=di(N+A+F,l[1][1])),P=Math.max(P,e),R=Math.max(R,t)}if(i){let e=0,t=0;h&&C>0?e=di(w+C,i[0][0]):!h&&C<0&&(e=dl(w+E,i[1][0])),p&&M>0?t=di(N+M,i[0][1]):!p&&M<0&&(t=dl(N+A,i[1][1])),P=Math.max(P,e),R=Math.max(R,t)}if(r){if(m){(P=Math.max(P,dc(E/$,y,j)*$),l)&&(P=Math.max(P,(h||p)&&(!h||p||!g)?dl(N+F+(h?C:-C)/$,l[0][1])*$:di(N+F+E/$,l[1][1])*$));i&&(P=Math.max(P,(h||p)&&(!h||p||!g)?di(N+(h?C:-C)/$,i[0][1])*$:dl(N+E/$,i[1][1])*$))}if(x){(R=Math.max(R,dc(A*$,_,v)/$),l)&&(R=Math.max(R,(h||p)&&(!p||h||!g)?dl(w+(p?M:-M)*$+T,l[0][0])/$:di(w+A*$+T,l[1][0])/$));i&&(R=Math.max(R,(h||p)&&(!p||h||!g)?di(w+(p?M:-M)*$,i[0][0])/$:dl(w+A*$,i[1][0])/$))}}M+=M<0?R:-R,C+=C<0?P:-P,r&&(g?E>A*$?M=((o=h,c=p,o?!c:c)?-C:C)/$:C=((d=h,u=p,d?!u:u)?-M:M)*$:m?(M=C/$,p=h):(C=M*$,h=p));let O=h?w+C:w,L=p?N+M:N;return{width:k+(h?-C:C),height:S+(p?-M:M),x:n[0]*C*(h?-1:1)+O,y:n[1]*M*(p?-1:1)+L}}(_,l.controlDirection,o,l.boundaries,l.keepAspectRatio,S,g,f),A=$!==w,T=C!==N,F=M!==d&&A,P=E!==h&&T;if(!F&&!P&&!A&&!T)return;if((F||P||1===S[0]||1===S[1])&&(k.x=F?M:b.x,k.y=P?E:b.y,b.x=k.x,b.y=k.y,y.length>0)){let e=M-d,t=E-h;for(let a of y)a.position={x:a.position.x-e+S[0]*($-w),y:a.position.y-t+S[1]*(C-N)},c.push(a)}if((A||T)&&(k.width=A&&(!l.resizeDirection||"horizontal"===l.resizeDirection)?$:b.width,k.height=T&&(!l.resizeDirection||"vertical"===l.resizeDirection)?C:b.height,b.width=k.width,b.height=k.height),x&&m.expandParent){let e=S[0]*(k.width??0);k.x&&k.x<e&&(b.x=e,_.x=_.x-(k.x-e));let t=S[1]*(k.height??0);k.y&&k.y<t&&(b.y=t,_.y=_.y-(k.y-t))}let R=function({width:e,prevWidth:t,height:a,prevHeight:s,affectsX:r,affectsY:n}){let l=e-t,i=a-s,o=[l>0?1:l<0?-1:0,i>0?1:i<0?-1:0];return l&&r&&(o[0]=-1*o[0]),i&&n&&(o[1]=-1*o[1]),o}({width:b.width,prevWidth:w,height:b.height,prevHeight:N,affectsX:l.controlDirection.affectsX,affectsY:l.controlDirection.affectsY}),O={...b,direction:R};!1!==p?.(e,O)&&(j=!0,u?.(e,O),s(k,c))}).on("end",e=>
11{j&&(h?.(e,{...b}),r?.({...b}),j=!1)});n.call(w)},destroy:function(){n.on(".drag",null)}}}({domNode:k.current,nodeId:w,getStoreItems:()=>{let{nodeLookup:e,transform:t,snapGrid:a,snapToGrid:s,nodeOrigin:r,domNode:n}=N.getState();return{nodeLookup:e,transform:t,snapGrid:a,snapToGrid:s,nodeOrigin:r,paneDomNode:n}},onChange:(e,t)=>{let{triggerNodeChanges:a,nodeLookup:s,parentLookup:r,nodeOrigin:n}=N.getState(),l=[],i={x:e.x,y:e.y},o=s.get(w);if(o&&o.expandParent&&o.parentId){let t=o.origin??n,a=e.width??o.measured.width??0,c=e.height??o.measured.height??0,d=cX([{id:o.id,parentId:o.parentId,rect:{width:a,height:c,...c_({x:e.x??o.position.x,y:e.y??o.position.y},{width:a,height:c},o.parentId,s,t)}}],s,r,n);l.push(...d),i.x=e.x?Math.max(t[0]*a,e.x):void 0,i.y=e.y?Math.max(t[1]*c,e.y):void 0}if(void 0!==i.x&&void 0!==i.y){let e={id:w,type:"position",position:{...i}};l.push(e)}if(void 0!==e.width&&void 0!==e.height){let t={id:w,type:"dimensions",resizing:!0,setAttributes:!h||("horizontal"===h?"width":"height"),dimensions:{width:e.width,height:e.height}};l.push(t)}for(let e of t){let t={...e,type:"position"};l.push(t)}a(l)},onEnd:({width:e,height:t})=>{N.getState().triggerNodeChanges([{id:w,type:"dimensions",resizing:!1,dimensions:{width:e,height:t}}])}})),C.current.update({controlPosition:M,boundaries:{minWidth:i,minHeight:o,maxWidth:c,maxHeight:d},keepAspectRatio:u,resizeDirection:h,onResizeStart:x,onResize:f,onResizeEnd:v,shouldResize:m}),()=>{C.current?.destroy()}},[M,i,o,c,d,u,x,f,v,m]);let E=M.split("-");return(0,b.jsx)("div",{className:lp(["react-flow__resize-control","nodrag",...E,a,s]),ref:k,style:{...r,scale:$,...l&&{[S?"backgroundColor":"borderColor"]:l}},children:n})});let hV=["home","draw","away"],hG={scope:{label:"Scope",family:"scope",params:{competitions:["FIFA World Cup"]},inputs:[],output:null},model_fair:{label:"Model fair",family:"feature",params:{outcome:"home"},inputs:[],output:"number",enums:{outcome:hV}},market_price:{label:"Market price",family:"feature",params:{outcome:"home"},inputs:[],output:"number",enums:{outcome:hV}},edge:{label:"Edge (pp)",family:"feature",params:{outcome:"home"},inputs:[],output:"number",enums:{outcome:hV}},minute:{label:"Minute",family:"feature",params:{},inputs:[],output:"number"},score_diff:{label:"Score diff",family:"feature",params:{},inputs:[],output:"number"},elo_gap:{label:"Elo gap",family:"feature",params:{},inputs:[],output:"number"},is_home_fav:{label:"Home favorite?",family:"feature",params:{},inputs:[],output:"number"},const:{label:"Constant",family:"feature",params:{value:6},inputs:[],output:"number"},compare:{label:"Compare",family:"logic",params:{op:"gte",value:6},inputs:[{handle:"a",type:"number"},{handle:"b",type:"number"}],output:"bool",enums:{op:["gte","lte","eq","crosses_above","crosses_below"]}},and:{label:"AND",family:"logic",params:{},inputs:[{handle:"in",type:"bool"}],output:"bool"},or:{label:"OR",family:"logic",params:{},inputs:[{handle:"in",type:"bool"}],output:"bool"},not:{label:"NOT",family:"logic",params:{},inputs:[{handle:"in",type:"bool"}],output:"bool"},buy:{label:"BUY",family:"action",params:{side:"yes",outcome:"home",stake:1},inputs:[{handle:"in",type:"bool"}],output:null,enums:{side:["yes","no"],outcome:hV}},edge_scan:{label:"Edge scan (all markets)",family:"action",params:{threshold_pp:6},inputs:[{handle:"in",type:"bool"}],output:null}},hJ=1,hY={block:function({id:e,data:t}){let{setNodes:a}=us(),s=hG[t.kind];if(!s)return null;let r=(t,s)=>a(a=>a.map(a=>{if(a.id!==e)return a;let r=a.data;return{...a,data:{...r,params:{...r.params,[t]:s}}}}));return(0,b.jsxs)("div",{className:`sl-node sl-${s.family}`,children:[s.inputs.map((e,t)=>(0,b.jsx)(uy,{id:e.handle,type:"target",position:x.Left,className:`sl-h sl-h-${e.type}`,style:{top:28+16*t}},e.handle)),(0,b.jsxs)("div",{className:"sl-node-title",children:[s.label,s.inputs.length>1?(0,b.jsx)("span",{className:"sl-node-handles",children:s.inputs.map(e=>e.handle).join(" · ")}):null]}),(0,b.jsx)("div",{className:"sl-node-body",children:Object.keys(s.params).map(e=>s.enums?.[e]?(0,b.jsx)("select",{className:"sl-input",value:t.params[e],onChange:t=>r(e,t.target.value),children:s.enums[e].map(e=>(0,b.jsx)("option",{value:e,children:e},e))}
11,e):"competitions"===e?(0,b.jsx)("span",{className:"sl-node-static",children:"World Cup"},e):(0,b.jsx)("input",{className:"sl-input",type:"number",step:"any",value:t.params[e],onChange:t=>r(e,Number(t.target.value))},e))}),s.output&&(0,b.jsx)(uy,{id:"out",type:"source",position:x.Right,className:`sl-h sl-h-${s.output}`})]})}};function hK({equity:e}){let t=(0,_.useRef)(null),a=(0,_.useRef)(null),s=(0,_.useRef)(null);return(0,_.useEffect)(()=>{if(!t.current)return;let e=(0,A.createChart)(t.current,{...(0,T.makeChartOptions)(180),autoSize:!0,rightPriceScale:{borderVisible:!1}});s.current=e.addSeries(A.AreaSeries,{lineWidth:2}),a.current=e;let r=new ResizeObserver(()=>e.applyOptions({width:t.current.clientWidth}));return r.observe(t.current),()=>{r.disconnect(),e.remove()}},[]),(0,_.useEffect)(()=>{s.current&&(s.current.setData(e.map((e,t)=>({time:t+1,value:e}))),a.current?.timeScale().fitContent())},[e]),(0,b.jsx)("div",{ref:t,style:{height:180}})}function hX(){let[e,t,a]=function(e){let[t,a]=(0,_.useState)(e),s=(0,_.useCallback)(e=>a(t=>dQ(e,t)),[]);return[t,a,s]}([]),[s,r,n]=function(e){let[t,a]=(0,_.useState)(e),s=(0,_.useCallback)(e=>a(t=>dQ(e,t)),[]);return[t,a,s]}([]),[l,i]=(0,_.useState)("My strategy"),[o,c]=(0,_.useState)(0),[d,u]=(0,_.useState)(1),[h,p]=(0,_.useState)(null),[m,x]=(0,_.useState)(!1),[g,f]=(0,_.useState)({}),[v,y]=(0,_.useState)([]),j=(0,_.useRef)(null);(0,_.useEffect)(()=>{(0,er.authGetJson)("/api/strategy/blocks").then(e=>f(e.data?.presets||{})).catch(()=>{}),(0,er.authGetJson)("/api/strategy").then(e=>y(e.data?.strategies||[])).catch(()=>{})},[]);let w=(0,_.useCallback)(t=>{let a=e.find(e=>e.id===t.source),s=e.find(e=>e.id===t.target);if(!a||!s)return!1;let r=hG[a.data.kind]?.output,n=hG[s.data.kind]?.inputs.find(e=>e.handle===(t.targetHandle||"in"));return!!r&&!!n&&r===n.type},[e]),N=(0,_.useCallback)(e=>r(t=>d3({...e,sourceHandle:"out"},t)),[r]),k=e=>{p(null),t((e.nodes||[]).map(e=>({id:e.id,type:"block",position:e.position||{x:100,y:100},data:{kind:e.type,params:e.params||{}}}))),r((e.edges||[]).map((e,t)=>({id:`e${t}`,source:e.source,target:e.target,sourceHandle:"out",targetHandle:e.targetHandle||"in"}))),e.name&&i(e.name)},S=()=>({name:l,nodes:e.map(e=>({id:e.id,type:e.data.kind,params:e.data.params,position:e.position})),edges:s.map(e=>({source:e.source,target:e.target,targetHandle:e.targetHandle||"in"}))}),$=async()=>{x(!0),p(null);try{let e=await (0,er.authPostJson)("/api/strategy/backtest",{graph:S(),params:{market_blend:o,slippage_pp:d,dedupe:!0}});p(e.data||{error:"no data"})}catch(e){p({error:e?.message||"backtest failed"})}finally{x(!1)}},C=async()=>{try{await (0,er.authPostJson)("/api/strategy",{name:l,graph:S(),params:{market_blend:o,slippage_pp:d}});let e=await (0,er.authGetJson)("/api/strategy");y(e.data?.strategies||[])}catch{}};return(0,b.jsxs)("div",{className:"sl-view",children:[(0,b.jsxs)("div",{className:"sl-toolbar",children:[(0,b.jsx)("input",{className:"sl-name",value:l,onChange:e=>i(e.target.value)}),(0,b.jsxs)("select",{className:"sl-input",defaultValue:"",onChange:e=>{e.target.value&&k(g[e.target.value])},children:[(0,b.jsx)("option",{value:"",children:"load preset…"}),Object.keys(g).map(e=>(0,b.jsx)("option",{value:e,children:g[e].name||e},e))]}),(0,b.jsxs)("select",{className:"sl-input",defaultValue:"",onChange:e=>{let t=v.find(t=>String(t.id)===e.target.value);t&&k({...t.graph,name:t.name})},children:[(0,b.jsx)("option",{value:"",children:"load saved…"}),v.map(e=>(0,b.jsx)("option",{value:e.id,children:e.name},e.id))]}),(0,b.jsxs)("label",{className:"sl-param",children:["blend ",(0,b.jsx)("input",{type:"number",min:0,max:1,step:.1,value:o,onChange:e=>c(Number(e.target.value))})]}),(0,b.jsxs)("label",{className:"sl-param",children:["slippage ",(0,b.jsx)("input",{type:"number",min:0,step:.5,value:d,onChange:e=>u(Number(e.target.value))}),"pp"]}),(0,b.jsx)("button",{className:"sl-btn",onClick:C,children:"save"}),(0,b.jsx)("button",{className:"sl-btn run",onClick:$,disabled:m,children:m?"running…":"▶ Run backtest"}),v.length>0&&(0,b.jsxs)("select",{className:"sl-input",defaultValue:"",onChange:async e=>{let t=v.find(t=>String(t.id)===e.target.value);if(!t)return;await (0,er.authPostJson)(`/api/strategy/${t.id}/live`,{live:!t.live});let a=await (0,er.authGetJson)("/api/strategy");y(a.data?.strategies||[]),e.target.value=""},title:"flip a saved strategy live/off — live strategies emit real signals every tick",children:[(0,b.jsx)("option",{value:"",children:"go live ▸"}),v.map(e=>(0,b.jsxs)("option",{value:e.id,children:[e.live?"● LIVE":"○ off"," — ",e.name]},e.id))]})]}),(0,b.jsxs)("div",{className:"sl-main",children:[(0,b.jsxs)("div",{className:"sl-palette",children:[[["Scope",["scope"]],["Features",["model_fair","market_price","edge","minute","score_diff","elo_gap","is_home_fav","const"]],["Logic",["compare","and","or","not"]],["Action",["buy","edge_scan"]]].map(([e,a])=>(0,b.jsxs)("div",{className:"sl-pal-group",children:[(0,b.jsx)("div",{className:"sl-pal-head",children:e}),a.map(e=>(0,b.jsxs)("button",{className:`sl-pal-node sl-${hG[e].family}`,onClick:()=>{let a;return a=hG[e],void t(t=>[...t,{id:`n${hJ++}`,type:"block",position:{x:120+240*Math.random(),y:80+320*Math.random()},data:{kind:e,params:JSON.parse(JSON.stringify(a.params))}}])},children:["+ ",hG[e].label]},e))]},e)),(0,b.jsx)("div",{className:"sl-pal-hint",children:"drag a wire from a ● output to a ● input. blue = number, green = yes/no."})]}),(0,b.jsx)("div",{className:"sl-canvas",ref:j,children:(0,b.jsxs)(hv,{nodes:e,edges:s,onNodesChange:a,onEdgesChange:n,onConnect:N,isValidConnection:w,nodeTypes:hY,fitView:!0,proOptions:{hideAttribution:!0},children:[(0,b.jsx)(hS,{}),(0,b.jsx)(hR,{}),(0,b.jsx)(hH,{pannable:!0,zoomable:!0})]})}),h&&(0,b.jsx)("div",{className:"sl-results",children:h.error?(0,b.jsx)("div",{className:"sl-err",children:h.error}):0===h.bets?(0,b.jsx)("div",{className:"radar-section-note",children:h.note||"No bets fired over the scoped matches."}):(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)("div",{className:"sl-stats",children:[(0,b.jsxs)("div",{className:"sl-stat",children:[(0,b.jsxs)("b",{className:h.pnl>=0?"radar-up":"radar-down",children:[h.pnl>=0?"+":"",h.pnl]}),(0,b.jsx)("span",{children:"P&L (units)"})]}),(0,b.jsxs)("div",{className:"sl-stat",children:[(0,b.jsxs)("b",{children:[Math.round(100*(h.hit_rate||0)),"%"]}),(0,b.jsx)("span",{children:"hit rate"})]}),(0,b.jsxs)("div",{className:"sl-stat",children:[(0,b.jsxs)("b",{children:[h.roc_pct,"%"]}),(0,b.jsx)("span",{children:"return on capital"})]}),(0,b.jsxs)("div",{className:"sl-stat",children:[(0,b.jsx)("b",{children:h.bets}),(0,b.jsxs)("span",{children:["bets · ",h.n_matches," matches"]})]}),(0,b.jsxs)("div",{className:"sl-stat",children:[(0,b.jsx)("b",{className:"radar-down",children:h.max_drawdown}),(0,b.jsx)("span",{children:"max drawdown"})]})]}),h.equity?.length?(0,b.jsx)(hK,{equity:h.equity}):null,(0,b.jsxs)("table",{className:"radar-moves-table",children:[(0,b.jsx)("thead",{children:(0,b.jsxs)("tr",{children:[(0,b.jsx)("th",{children:"Match"}),(0,b.jsx)("th",{children:"Min"}),(0,b.jsx)("th",{children:"Bet"}),(0,b.jsx)("th",{children:"Pay"}),(0,b.jsx)("th",{children:"Result"})]})}),(0,b.jsx)("tbody",{children:(h.log||[]).slice(0,40).map((e,t)=>(0,b.jsxs)("tr",{children:[(0,b.jsx)("td",{children:e.match}),(0,b.jsxs)("td",{children:[e.minute,"' (",e.score,")"]}),(0,b.jsx)("td",{children:(0,b.jsxs)("span",{className:`radar-badge ${"yes"===e.side?"radar-badge-up":"radar-badge-down"}`,children:["BUY ",e.side.toUpperCase()," ",e.outcome]})}),(0,b.jsxs)("td",{children:[(100*e.pay).toFixed(1),"c"]}),(0,b.jsxs)("td",{className:e.won?"radar-up":"radar-down",children:[e.won?"WON":"lost"," ",e.profit>=0?"+":"",e.profit]})]},t))})]})]})})]})]})}function hZ(){return(0,b.jsx)(hf,{children:(0,b.jsx)(hX,{})})}function hQ(e,t){let a=[],s=/(`[^`\n]+`)|(\*\*\*[^*]+\*\*\*)|(\*\*[^*]+\*\*)|(__[^_]+__)|(~~[^~]+~~)|(\*[^*\n]+\*)|(_[^_\n]+_)|(\[[^\]]+\]\((https?:\/\/[^)\s]+)\))|(https?:\/\/[^\s<>]+)|(<#\d+>)|(<@!?\d+>)|(<a?:\w+:\d+>)/g,r=0,n,l=0;for(;n=s.exec(e);){n.index>r&&a.push(e.slice(r,n.index));let s=n[0],i=`${t}-i${l++}`;if(s.startsWith("`"))a.push((0,b.jsx)("code",{className:"pb-code",children:s.slice(1,-1)},i));else if(s.startsWith("***"))a.push((0,b.jsx)("strong",{children:(0,b.jsx)("em",{children:s.slice(3,-3)})},i));else if(s.startsWith("**"))a.push((0,b.jsx)("strong",{children:s.slice(2,-2)},i));else if(s.startsWith("__"))a.push((0,b.jsx)("u",{children:s.slice(2,-2)},i));else if(s.startsWith("~~"))a.push((0,b.jsx)("s",{children:s.slice(2,-2)},i));else if(s.startsWith("[")){let e=s.slice(1,s.indexOf("]"));a.push((0,b.jsx)("a",{href:n[9],target:"_blank",rel:"noreferrer",children:e},i))}else if(s.startsWith("http"))a.push((0,b.jsx)("a",{href:s,target:"_blank",rel:"noreferrer",children:s},i));else if(s.startsWith("<#"))a.push((0,b.jsx)("span",{className:"pb-mention",children:"#channel"},i));else if(s.startsWith("<@"))a.push((0,b.jsx)("span",{className:"pb-mention",children:"@member"},i));else if(s.startsWith("<")){let e=s.split(":")[1]||"emoji";a.push((0,b.jsxs)("span",{className:"pb-mention",children:[":",e,":"]},i))}else s.startsWith("*")||s.startsWith("_")?a.push((0,b.jsx)("em",{children:s.slice(1,-1)},i)):a.push(s);r=n.index+s.length}return r<e.length&&a.push(e.slice(r)),a}let h0="openpoly.playbook.read";function h1(){let[e,t]=(0,_.useState)(null),[a,s]=(0,_.useState)(null),[r,n]=(0,_.useState)(null),[l,i]=(0,_.useState)(!0),[o,c]=(0,_.useState)(""),[d,u]=(0,_.useState)(new Set),[h,p]=(0,_.useState)(""),[m,x]=(0,_.useState)(null),g=(0,_.useRef)(null);(0,_.useEffect)(()=>{u(function(){try{return new Set(JSON.parse(localStorage.getItem(h0)||"[]"))}catch{return new Set}}())},[]),(0,_.useEffect)(()=>{(0,er.authGetJson)("/api/playbook").then(e=>{t(e.data||null);let a=e.data?.categories?.[0]?.lessons?.[0]?.channel_id;a&&s(e=>e||a)}).catch(()=>c("couldn’t load the playbook")).finally(()=>i(!1))},[]),(0,_.useEffect)(()=>{a&&(n(null),(0,er.authGetJson)(`/api/playbook/lessons/${a}`).then(e=>n(e.data||null)).catch(()=>c("couldn’t load that lesson")),g.current&&(g.current.scrollTop=0))},[a]);let f=(0,_.useMemo)(()=>(e?.categories||[]).flatMap(e=>e.lessons.map(t=>({...t,category:e.category}))),[e]),v=f.findIndex(e=>e.channel_id===a),y=(0,_.useCallback)((e,t)=>{u(a=>
11{let s=new Set(a);return t?s.add(e):s.delete(e),localStorage.setItem(h0,JSON.stringify([...s])),s})},[]),j=(0,_.useCallback)(async e=>{if(e.trim().length<2)return void x(null);try{let t=await (0,er.authGetJson)(`/api/playbook/search?q=${encodeURIComponent(e.trim())}`);x(t.data?.hits||[])}catch{x([])}},[]),w=f.filter(e=>d.has(e.channel_id)).length,N=f.length?Math.round(w/f.length*100):0;return l?(0,b.jsx)("div",{className:"pb-wrap",children:(0,b.jsx)("div",{className:"pb-empty",children:"Loading the playbook…"})}):o?(0,b.jsx)("div",{className:"pb-wrap",children:(0,b.jsx)("div",{className:"pb-empty",children:o})}):e&&f.length?(0,b.jsxs)("div",{className:"pb-wrap",children:[(0,b.jsxs)("aside",{className:"pb-side",children:[(0,b.jsxs)("div",{className:"pb-side-head",children:[(0,b.jsx)("div",{className:"pb-title",children:"📕 Playbook"}),(0,b.jsxs)("div",{className:"pb-sub",children:[e.totals.lessons," lessons · ",e.totals.words.toLocaleString()," words ·"," ",Math.round(e.totals.read_minutes/60*10)/10,"h read"]}),(0,b.jsx)("div",{className:"pb-progress",title:`${w} of ${f.length} lessons read`,children:(0,b.jsx)("div",{className:"pb-progress-fill",style:{width:`${N}%`}})}),(0,b.jsxs)("div",{className:"pb-sub",children:[w," of ",f.length," read · ",N,"%"]}),(0,b.jsx)("input",{className:"pb-search",value:h,placeholder:"Search the whole course…",onChange:e=>{p(e.target.value),j(e.target.value)}})]}),null!==m?(0,b.jsxs)("div",{className:"pb-hits",children:[(0,b.jsx)("button",{className:"pb-clear",onClick:()=>{p(""),x(null)},children:"← back to contents"}),!m.length&&(0,b.jsx)("div",{className:"pb-sub",style:{padding:"8px 14px"},children:"No matches."}),m.map((e,t)=>(0,b.jsxs)("button",{className:"pb-hit",onClick:()=>{s(e.channel_id),x(null),p("")},children:[(0,b.jsx)("div",{className:"pb-hit-title",children:e.title}),(0,b.jsx)("div",{className:"pb-hit-cat",children:e.category}),(0,b.jsx)("div",{className:"pb-hit-ex",children:e.excerpt})]},t))]}):(0,b.jsx)("nav",{className:"pb-nav",children:e.categories.map((e,t)=>(0,b.jsxs)("div",{className:"pb-cat",children:[(0,b.jsxs)("div",{className:"pb-cat-head",children:[(0,b.jsx)("span",{className:"pb-cat-num",children:t+1}),e.category]}),e.lessons.map(e=>(0,b.jsxs)("button",{className:`pb-lesson${a===e.channel_id?" on":""}${d.has(e.channel_id)?" read":""}`,onClick:()=>s(e.channel_id),children:[(0,b.jsx)("span",{className:"pb-check",children:d.has(e.channel_id)?"✓":""}),(0,b.jsx)("span",{className:"pb-lesson-title",children:e.title}),(0,b.jsxs)("span",{className:"pb-lesson-min",children:[e.read_minutes,"m"]})]},e.channel_id))]},e.category_id))})]}),(0,b.jsx)("main",{className:"pb-body",ref:g,children:r?(0,b.jsxs)("article",{className:"pb-article",children:[(0,b.jsx)("div",{className:"pb-crumb",children:r.category}),(0,b.jsx)("h1",{className:"pb-lesson-h1",children:r.title}),(0,b.jsxs)("div",{className:"pb-meta",children:[r.read_minutes," min read · ",r.words.toLocaleString()," words",v>=0&&(0,b.jsxs)(b.Fragment,{children:[" · lesson ",v+1," of ",f.length]})]}),r.topic&&(0,b.jsx)("div",{className:"pb-topic",children:r.topic}),r.blocks.map((e,t)=>(0,b.jsxs)("section",{className:"pb-block",children:[function e(t,a="b"){let s=(t||"").split("\n"),r=[],n=0,l=0,i=(e,t)=>{e.length&&r.push((0,b.jsx)(t?"ol":"ul",{className:"pb-list",children:e.map((e,t)=>(0,b.jsx)("li",{children:hQ(e,`${a}-l${l}-${t}`)},t))},`${a}-l${l++}`))};for(;n<s.length;){let t=s[n];if(t.trim().startsWith("```")){let e=t.trim().slice(3).trim(),i=[];for(n++;n<s.length&&!s[n].trim().startsWith("```");)i.push(s[n++]);n++,r.push((0,b.jsxs)("pre",{className:"pb-pre",children:[e&&(0,b.jsx)("span",{className:"pb-pre-lang",children:e}),(0,b.jsx)("code",{children:i.join("\n")})]},`${a}-c${l++}`));continue}let o=t.match(/^(#{1,3})\s+(.*)$/);if(o){let e=["h3","h4","h5"][o[1].length-1];r.push((0,b.jsx)(e,{className:"pb-h",children:hQ(o[2],`${a}-h${l}`)},`${a}-h${l++}`)),n++;continue}if(/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(t)){r.push((0,b.jsx)("hr",{className:"pb-hr"},`${a}-r${l++}`)),n++;continue}if(t.trim().startsWith(">")){let t=[];for(;n<s.length&&s[n].trim().startsWith(">");)t.push(s[n].replace(/^\s*>\s?/,"")),n++;r.push((0,b.jsx)("blockquote",{className:"pb-quote",children:e(t.join("\n"),`${a}-q${l}`)},`${a}-q${l++}`));continue}if(t.match(/^\s*[-*•]\s+(.*)$/)){let e=[];for(;n<s.length;){let t=s[n].match(/^\s*[-*•]\s+(.*)$/);if(!t)break;e.push(t[1]),n++}i(e,!1);continue}if(t.match(/^\s*\d+[.)]\s+(.*)$/)){let e=[];for(;n<s.length;){let t=s[n].match(/^\s*\d+[.)]\s+(.*)$/);if(!t)break;e.push(t[1]),n++}i(e,!0);continue}if(!t.trim()){n++;continue}let c=[];for(;n<s.length&&s[n].trim()&&!s[n].trim().startsWith("```")&&!s[n].trim().startsWith(">")&&!/^\s*[-*•]\s+/.test(s[n])&&!/^\s*\d+[.)]\s+/.test(s[n])&&!/^#{1,3}\s+/.test(s[n]);)c.push(s[n]),n++;r.push((0,b.jsx)("p",{className:"pb-p",children:c.map((e,t)=>(0,b.jsxs)(_.Fragment,{children:[t>0&&(0,b.jsx)("br",{}),hQ(e,`${a}-p${l}-${t}`)]},t))},`${a}-p${l++}`))}return r}(e.content,`b${t}`),(e.images||[]).map((e,t)=>(0,b.jsx)("img",{className:"pb-img",alt:"course diagram",loading:"lazy",src:e},t))]},t)),(0,b.jsxs)("div",{className:"pb-footer",children:[(0,b.jsxs)("label",{className:"pb-done",children:[(0,b.jsx)("input",{type:"checkbox",checked:d.has(r.channel_id),onChange:e=>y(r.channel_id,e.target.checked)}),"Mark this lesson read"]}),(0,b.jsxs)("div",{className:"pb-jump",children:[(0,b.jsx)("button",{disabled:v<=0,onClick:()=>s(f[v-1].channel_id),children:"← Previous"}),(0,b.jsx)("button",{disabled:v<0||v>=f.length-1,onClick:()=>{y(r.channel_id,!0),s(f[v+1].channel_id)},children:"Next lesson →"})]})]})]}):(0,b.jsx)("div",{className:"pb-empty",children:"Opening…"})})]}):(0,b.jsx)("div",{className:"pb-wrap",children:(0,b.jsxs)("div",{className:"pb-empty",children:["Nothing imported yet. Run the export, then the import:",(0,b.jsx)("pre",{className:"pb-pre",children:(0,b.jsxs)("code",{children:[".venv/bin/python scripts/discord_course_export.py","\n",".venv/bin/python scripts/playbook_import.py"]})})]})})}let h2=["universe","state_gates","market_gates","signal","sizing","exits","execution"];function h5({d:e}){return(0,b.jsx)("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"currentColor","aria-hidden":!0,
11children:(0,b.jsx)("path",{d:e})})}let h4={universe:{label:"Market",icon:(0,b.jsx)(h5,{d:"M8 1.5a6.5 6.5 0 1 0 0 13 6.5 6.5 0 0 0 0-13Zm0 2.4a4.1 4.1 0 1 1 0 8.2 4.1 4.1 0 0 1 0-8.2Zm0 2.5a1.6 1.6 0 1 0 0 3.2 1.6 1.6 0 0 0 0-3.2Z"})},state_gates:{label:"Timing",icon:(0,b.jsx)(h5,{d:"M8 1.5a6.5 6.5 0 1 0 0 13 6.5 6.5 0 0 0 0-13Zm0 2a4.5 4.5 0 1 1 0 9 4.5 4.5 0 0 1 0-9Zm-.75 1.6v3.2l2.6 1.55.75-1.26-2-1.19V5.1Z"})},market_gates:{label:"Price",icon:(0,b.jsx)(h5,{d:"M2 8.6 8.6 2h3.9a1.5 1.5 0 0 1 1.5 1.5v3.9L7.4 14a1.5 1.5 0 0 1-2.1 0L2 10.7a1.5 1.5 0 0 1 0-2.1Zm9.2-4.1a1.05 1.05 0 1 0 0 2.1 1.05 1.05 0 0 0 0-2.1Z"})},signal:{label:"Signal",icon:(0,b.jsx)(h5,{d:"M8 1.2 9.6 5.5l4.4.3-3.4 2.8 1.1 4.3L8 10.5l-3.7 2.4 1.1-4.3L2 5.8l4.4-.3Z"})},sizing:{label:"Sizing",icon:(0,b.jsx)(h5,{d:"M2.5 12.5h11V14h-11ZM3.3 7h2.2v4.4H3.3Zm3.6-3h2.2v7.4H6.9Zm3.6-2.4h2.2v9.8h-2.2Z"})},exits:{label:"Exit",icon:(0,b.jsx)(h5,{d:"M6.2 2h5.3A1.5 1.5 0 0 1 13 3.5v9a1.5 1.5 0 0 1-1.5 1.5H6.2v-1.6h5.2V3.6H6.2Zm.9 3.1L4.5 7.7h6v1.6h-6l2.6 2.6-1.1 1.1L1.5 8.5 6 4Z"})},execution:{label:"Pacing",icon:(0,b.jsx)(h5,{d:"M8 2a6 6 0 0 1 6 6h-1.7A4.3 4.3 0 1 0 8 12.3V14a6 6 0 1 1 0-12Zm-.8 2.7h1.6v3l2.3 1.4-.8 1.3-3.1-1.8Z"})}},h3=[["universe.","universe"],["state.","state_gates"],["market.","market_gates"],["signal.","signal"],["sizing.","sizing"],["exit","exits"],["exec.","execution"]];function h6(e){return JSON.parse(JSON.stringify(e))}let h8=e=>`${Math.round(100*Number(e))}\xa2`,h9=/(\{\{\s*\w+\s*\}\})/g,h7=/^\{\{\s*\w+\s*\}\}$/,pe=e=>e.replace(/[{}\s]/g,"");function pt({value:e,disabled:t,vars:a,onChange:s}){let r,[n,l]=(0,_.useState)(null),[i,o]=(0,_.useState)(null),c=Array.from(new Set((e.match(h9)||[]).map(pe))),d=Object.keys(a).filter(e=>!c.includes(e));return(0,b.jsxs)("div",{className:"pe",children:[(0,b.jsxs)("div",{className:"pe-editor",children:[(0,b.jsxs)("pre",{className:"pe-mirror","aria-hidden":!0,children:[e.split(h9).map((e,t)=>h7.test(e)?(0,b.jsx)("mark",{className:a[pe(e)]?"":"bad",children:e},t):(0,b.jsx)("span",{children:e},t)),"\n"]}),(0,b.jsx)("textarea",{ref:o,rows:11,value:e,disabled:t,spellCheck:!1,placeholder:"You are a football trader reading a live match…\n\nUse {{commentary}} and {{recent_momentum}} to decide whether a goal is coming.",onChange:e=>s(e.target.value),onScroll:e=>{let t=e.target.parentElement?.querySelector(".pe-mirror");t&&(t.scrollTop=e.target.scrollTop)}})]}),(0,b.jsxs)("div",{className:"pe-chips",children:[c.map(e=>(0,b.jsxs)("button",{type:"button",className:`pe-chip used ${a[e]?"":"bad"} ${n===e?"on":""}`,onClick:()=>l(n===e?null:e),children:["{{",e,"}}"]},e)),c.length>0&&d.length>0&&(0,b.jsx)("span",{className:"pe-sep"}),d.map(e=>(0,b.jsx)("button",{type:"button",className:`pe-chip ${n===e?"on":""}`,onClick:()=>l(n===e?null:e),children:e},e))]}),n&&((r=a[n])?(0,b.jsxs)("div",{className:"pe-info",children:[(0,b.jsxs)("div",{className:"pe-info-head",children:[(0,b.jsx)("b",{children:r.label}),!c.includes(n)&&!t&&(0,b.jsx)("button",{type:"button",className:"btn ghost sm",onClick:()=>(t=>{let a=`{{${t}}}`;if(!i)return void s(e+a);let r=i.selectionStart??e.length;s(e.slice(0,r)+a+e.slice(i.selectionEnd??r)),requestAnimationFrame(()=>{i.focus(),i.setSelectionRange(r+a.length,r+a.length)})})(n),children:"Insert"})]}),(0,b.jsx)("p",{children:r.what}),(0,b.jsx)("p",{className:"pe-src",children:r.source}),(0,b.jsx)("code",{children:r.example})]}):(0,b.jsxs)("div",{className:"pe-info bad",children:["Unknown variable — it won't receive data. Available: ",Object.keys(a).join(", "),"."]})),(0,b.jsx)("p",{className:"hint",children:"Only referenced variables are fetched and shown to the AI — fewer variables, faster and cheaper reads."})]})}function pa({on:e,disabled:t,onClick:a}){return(0,b.jsx)("button",{type:"button",role:"switch","aria-checked":e,disabled:t,className:`switch ${e?"on":""}`,onClick:a,children:(0,b.jsx)("span",{className:"switch-knob"})})}function ps({label:e,value:t,tone:a}){return(0,b.jsxs)("div",{className:"stat",children:[(0,b.jsx)("span",{className:"stat-label",children:e}),(0,b.jsx)("span",{className:`stat-value ${a||""}`,children:t})]})}function pr(){let e,t,[a,s]=(0,_.useState)(null),[r,n]=(0,_.useState)([]),[l,i]=(0,_.useState)([]),[o,c]=(0,_.useState)({}),[d,u]=(0,_.useState)([]),[h,p]=(0,_.useState)(null),[m,x]=(0,_.useState)(null),[g,f]=(0,_.useState)(!1),[v,y]=(0,_.useState)(null),[j,w]=(0,_.useState)(null),[N,k]=(0,_.useState)(null),[S,$]=(0,_.useState)(!1),[C,M]=(0,_.useState)([]),[E,A]=(0,_.useState)(null),[T,F]=(0,_.useState)(null),[P,R]=(0,_.useState)({}),[O,L]=(0,_.useState)(null),[I,D]=(0,_.useState)({}),z=(0,_.useRef)(()=>{}),B=(0,_.useCallback)(async()=>{try{let e=await (0,er.authGetJson)("/api/worldcup/studio/catalog");e.ok&&(s(e.data.catalog),n(e.data.templates),i(e.data.engines),c(e.data.prompt_variables||{}));let t=await (0,er.authGetJson)("/api/worldcup/studio/strategies");t.ok&&u(t.data.strategies)}catch{}},[]);(0,_.useEffect)(()=>{B()},[B]),(0,_.useEffect)(()=>{let e=()=>(0,er.authGetJson)("/api/worldcup/matches").then(e=>{e.ok&&M((e.data.matches||[]).filter(e=>"live"===e.status))}).catch(()=>{});e();let t=setInterval(e,3e4);return()=>clearInterval(t)},[]),(0,_.useEffect)(()=>{let e=!0;return(async()=>{let t={};for(let e of d)try{let a=await (0,er.authGetJson)(`/api/worldcup/autotrade/history?account_id=${encodeURIComponent(e.id)}&position_limit=1&order_limit=1`),s=a?.data?.summary||{};t[e.id]={n:Number(s.closed??s.positions??0),pnl:Number(s.realized_pnl??0)}}catch{}e&&R(t)})(),()=>{e=!1}},[d]),(0,_.useEffect)(()=>
11{if(!h||!E)return void F(null);let e=!0,t=()=>(0,er.authPostJson)("/api/worldcup/studio/trace",{strategy_id:h,event_id:E}).then(t=>{e&&t.ok&&F({rows:t.trace,at:Date.now()})}).catch(()=>{});t();let a=setInterval(t,1e4);return()=>{e=!1,clearInterval(a)}},[h,E]),(0,_.useEffect)(()=>{if(!N)return;let e=setTimeout(()=>k(null),2600);return()=>clearTimeout(e)},[N]),(0,_.useEffect)(()=>{let e=e=>{(e.metaKey||e.ctrlKey)&&"s"===e.key.toLowerCase()&&(e.preventDefault(),z.current())};return window.addEventListener("keydown",e),()=>window.removeEventListener("keydown",e)},[]);let W=e=>{p(e.id),x(h6(e)),f(!1),L(null),y(null),$(!1)},U=(e,t,a,s)=>{let r=window.prompt("Name it (a-z, 0-9, hyphen):",s);return!!r&&(p(`studio:${r}`),x({id:`studio:${r}`,slug:r,name:e,enabled:!1,based_on:t,blocks:h6(a)}),f(!0),L(null),y(null),!0)},H=e=>U(`${e.name} (copy)`,e.id,e.blocks,`${(e.slug||e.id.split(":")[1]||"my-strategy").slice(0,30)}-v2`),q=async()=>{if(m&&!m.readonly&&g){w("save");try{let e=await (0,er.authPostJson)("/api/worldcup/studio/strategies",{slug:m.slug||m.id.replace(/^studio:/,""),name:m.name,enabled:m.enabled??!1,based_on:m.based_on,rev:m.rev,blocks:m.blocks});e.ok&&e.data?(k({msg:"Saved",ok:!0}),f(!1),x(h6(e.data.strategy)),p(e.data.strategy.id),await B()):k({msg:e.error||"Save failed",ok:!1})}catch{k({msg:"Save failed",ok:!1})}w(null)}};z.current=q;let V=async e=>{w(`tog:${e.id}`);try{await (0,er.authPostJson)(`/api/worldcup/studio/strategies/${e.id.replace(/^studio:/,"")}/toggle`,{enabled:!e.enabled}),await B(),h===e.id&&m&&x({...m,enabled:!e.enabled}),k({msg:e.enabled?"Paused":"Paper trading started",ok:!0})}catch{k({msg:"Toggle failed",ok:!1})}w(null)},G=async e=>{if($(!1),window.confirm(`Delete ${e.name}? Its paper history stays in the ledger.`))try{await (0,er.authDeleteJson)(`/api/worldcup/studio/strategies/${e.id.replace(/^studio:/,"")}`),h===e.id&&(p(null),x(null)),await B(),k({msg:"Deleted",ok:!0})}catch{k({msg:"Delete failed",ok:!1})}},J=async e=>{let t=e.replace(/^studio:/,"");w(`bt:${e}`);try{await (0,er.authPostJson)(`/api/worldcup/studio/strategies/${t}/backtest`,{}),D(t=>({...t,[e]:{state:"running"}}));let a=setInterval(async()=>{try{let s=await (0,er.authGetJson)(`/api/worldcup/studio/strategies/${t}/backtest`);s.ok&&(D(t=>({...t,[e]:s.data})),"running"!==s.data.state&&clearInterval(a))}catch{clearInterval(a)}},4e3)}catch{k({msg:"Backtest failed to start",ok:!1})}w(null)},Y=(e,t,a)=>{m&&(x({...m,blocks:{...m.blocks,[e]:{...m.blocks[e]||{},[t]:a}}}),f(!0))},K=(()=>{if(!T)return null;let e=T.rows.find(e=>"exec.fill"===e.block||"exit"===e.block);if(e)return{pass:!0,text:e.detail};let t=T.rows.find(e=>!e.pass);if(!t)return{pass:!0,text:"Every rule passes"};let a=h3.find(([e])=>t.block.startsWith(e))?.[1];return{pass:!1,text:`Held at ${a?h4[a].label.toLowerCase():t.block}: ${t.detail}`}})(),X=(e,t)=>{let a=m?.blocks?.[e]?.[t.key]??t.default,s=!!m?.readonly;return"select"===t.kind?(0,b.jsx)("select",{value:String(a),disabled:s,onChange:a=>{let s=(t.options||[]).find(e=>String(e)===a.target.value);Y(e,t.key,s??a.target.value)},children:(t.options||[]).map(e=>(0,b.jsx)("option",{value:String(e),children:String(e)},String(e)))}):"textarea"===t.kind?(0,b.jsx)(pt,{value:String(a??""),disabled:s,vars:o,onChange:a=>Y(e,t.key,a)}):"text"===t.kind?(0,b.jsx)("input",{type:"text",value:String(a??""),disabled:s,onChange:a=>Y(e,t.key,a.target.value)}):(0,b.jsx)("input",{type:"number",min:t.min,max:t.max,step:"any",value:Number(a),disabled:s,onChange:a=>Y(e,t.key,Number(a.target.value))})};if(!a)return(0,b.jsx)("div",{className:"sw",children:(0,b.jsxs)("div",{className:"sw-loading",children:[(0,b.jsx)("span",{}),(0,b.jsx)("span",{}),(0,b.jsx)("span",{})]})});let Z=!!m&&d.some(e=>e.id===m.id),Q=String(m?.blocks?.signal?.type||"always"),ee=m?I[m.id]:null;return(0,b.jsxs)("div",{className:"sw",children:[(0,b.jsxs)("aside",{className:"sw-nav",children:[(0,b.jsxs)("div",{className:"sw-nav-section",children:[(0,b.jsxs)("div",{className:"sw-nav-h",children:[(0,b.jsx)("span",{children:"Strategies"}),(0,b.jsx)("span",{className:"sw-count",children:d.length})]}),0===d.length&&(0,b.jsx)("div",{className:"sw-nav-empty",children:"Clone a template below to begin."}),d.map(e=>{let t=P[e.id];return(0,b.jsxs)("button",{className:`sw-nav-item ${h===e.id?"on":""}`,onClick:()=>W(e),children:[(0,b.jsx)("span",{className:`dot ${e.enabled?"live":""}`}),(0,b.jsx)("span",{className:"sw-nav-name",children:e.name}),(0,b.jsx)("span",{className:"sw-nav-meta",children:t&&t.n>0?(0,b.jsxs)("b",{className:t.pnl>=0?"up":"down",children:[t.pnl>=0?"+":"−","$",Math.abs(t.pnl).toFixed(0)]}):e.enabled?"live":""})]},e.id)})]}),(0,b.jsxs)("div",{className:"sw-nav-section",children:[(0,b.jsxs)("div",{className:"sw-nav-h",children:[(0,b.jsx)("span",{children:"Templates"}),(0,b.jsx)("span",{className:"sw-count",children:r.length})]}),r.map(e=>(0,b.jsxs)("button",{className:`sw-nav-item ${h===e.id?"on":""}`,onClick:()=>W(e),children:[(0,b.jsx)("span",{className:"dot tpl"}),(0,b.jsx)("span",{className:"sw-nav-name",children:e.name})]},e.id))]}),(0,b.jsxs)("div",{className:"sw-nav-section",children:[(0,b.jsx)("div",{className:"sw-nav-h",children:(0,b.jsx)("span",{children:"Live bot internals"})}),l.map(e=>(0,b.jsxs)("button",{className:`sw-nav-item ${O===e.id?"on":""}`,onClick:()=>{L(e.id),p(null),x(null)},children:[(0,b.jsx)("span",{className:"dot lock"}),(0,b.jsx)("span",{className:"sw-nav-name",children:e.name})]},e.id))]})]}),(0,b.jsxs)("div",{className:"sw-work",children:[O&&((e=l.find(e=>e.id===O))?(0,b.jsx)("div",{className:"sw-scroll",children:(0,b.jsxs)("article",{className:"sw-engine",children:[(0,b.jsxs)("div",{className:"sw-engine-head",children:[(0,b.jsx)("h1",{children:e.name}),e.clone&&(0,b.jsx)("button",{className:"btn primary",onClick:()=>{e.clone&&U(e.clone.name,e.id,e.clone.blocks,"my-reader")&&y("signal")},children:"Clone as editable strategy"})]}),(0,b.jsx)("p",{className:"sw-engine-sum",children:e.summary}),(0,b.jsx)("div",{className:"sw-chips",children:e.inputs.map(e=>(0,b.jsx)("span",{children:e},e))}),e.prompts.map(e=>(0,b.jsxs)("details",{className:"sw-promptbox",children:[(0,b.jsx)("summary",{children:e.name}),(0,b.jsx)("pre",{children:e.text})]},e.name))]})}):null),!O&&!m&&(0,b.jsx)("div",{className:"sw-scroll",children:(0,b.jsxs)("div",{className:"sw-landing",children:[(0,b.jsx)("h1",{children:"Every rule on the table"}),(0,b.jsx)("p",{children:"A strategy is a pipeline of plain rules — market, timing, price, signal, sizing, exit, pacing. Start from a template, change what you believe, and paper-trade it against the same fills and fees the live bots pay. Nothing built here can touch a wallet."}),(0,b.jsxs)("div",{className:"sw-steps",children:[(0,b.jsxs)("div",{children:[(0,b.jsx)("i",{children:"1"}),(0,b.jsxs)("div",{children:[(0,b.jsx)("b",{children:"Clone"}),(0,b.jsx)("span",{children:"Each template is a live bot's exact shape."})]})]}),(0,b.jsxs)("div",{children:[(0,b.jsx)("i",{children:"2"}),(0,b.jsxs)("div",{children:[(0,b.jsx)("b",{children:"Edit & watch"}),(0,b.jsx)("span",{children:"Change a rule, watch it decide on a real match."})]})]}),(0,b.jsxs)("div",{children:[(0,b.jsx)("i",{children:"3"}),(0,b.jsxs)("div",{children:[(0,b.jsx)("b",{children:"Prove it"}),(0,b.jsx)("span",{children:"Backtest it, then let it paper-trade the nights."})]})]})]}),(0,b.jsx)("div",{className:"sw-gallery",children:r.map(e=>(0,b.jsxs)("button",{className:"sw-tpl",onClick:()=>W(e),children:[(0,b.jsx)("b",{children:e.name}),(0,b.jsx)("span",{children:e.notes}),(0,b.jsx)("em",{children:"View pipeline →"})]},e.id))})]})}),!O&&m&&(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)("header",{className:"sw-bar",children:[(0,b.jsxs)("div",{className:"sw-bar-left",children:[(0,b.jsx)("button",{className:"sw-crumb",onClick:()=>{p(null),x(null)},children:"Studio"}),(0,b.jsx)("span",{className:"sw-crumb-sep",children:"/"}),(0,b.jsx)("input",{className:"sw-name",value:m.name,disabled:!!m.readonly,onChange:e=>{x({...m,name:e.target.value}),f(!0)}}),m.readonly?(0,b.jsx)("span",{className:"badge",children:"Template"}):(0,b.jsx)("span",{className:`badge ${m.enabled?"live":""}`,children:m.enabled?"Paper · live":"Paper · paused"}),g&&(0,b.jsx)("span",{className:"sw-dirty",title:"Unsaved — ⌘S"})]}),(0,b.jsx)("div",{className:"sw-bar-right",children:m.readonly?(0,b.jsx)("button",{className:"btn primary",onClick:()=>H(m),children:"Clone & edit"}):(0,b.jsxs)(b.Fragment,{children:[Z&&(0,b.jsx)("button",{className:"btn ghost",disabled:ee?.state==="running",onClick:()=>J(m.id),children:ee?.state==="running"?`Backtesting ${ee?.done??0}/${ee?.total??"…"}`:"Backtest"}),(0,b.jsxs)("button",{className:"btn primary",disabled:!g||"save"===j,onClick:q,children:["save"===j?"Saving…":"Save",(0,b.jsx)("kbd",{children:"⌘S"})]}),Z&&(0,b.jsxs)("div",{className:"sw-run",children:[(0,b.jsx)("span",{children:"Paper"}),(0,b.jsx)(pa,{on:!!m.enabled,disabled:j===`tog:${m.id}`,onClick:()=>V(m)})]}),Z&&(0,b.jsxs)("div",{className:"sw-menu-wrap",children:[(0,b.jsx)("button",{className:"btn ghost icon","aria-label":"More actions",onClick:()=>$(!S),children:"⋯"}),S&&(0,b.jsxs)("div",{className:"sw-menu",onMouseLeave:()=>$(!1),children:[(0,b.jsx)("button",{onClick:()=>{$(!1),H(m)},children:"Duplicate"}),(0,b.jsx)("button",{className:"danger",onClick:()=>G(m),children:"Delete strategy"})]})]})]})})]}),(0,b.jsx)("div",{className:"sw-scroll",children:(0,b.jsxs)("div",{className:"sw-canvas",children:[(0,b.jsxs)("div",{className:"sw-pipe",children:[ee?.state==="done"&&(t=ee.result||{},(0,b.jsxs)("div",{className:"card sw-btcard",children:[(0,b.jsxs)("div",{className:"sw-btcard-h",children:["Backtest · last ",t.population," finished matches"]}),(0,b.jsxs)("div",{className:"sw-stats",children:[(0,b.jsx)(ps,{label:"Entered",value:String(t.entered)}),(0,b.jsx)(ps,{label:"P&L",value:`${t.pnl>=0?"+":"−"}$${Math.abs(t.pnl)}`,tone:t.pnl>=0?"up":"down"}),(0,b.jsx)(ps,{label:"ROI",value:`${t.roi_pct}%`,tone:t.roi_pct>=0?"up":"down"}),(0,b.jsx)(ps,{label:"Win rate",value:`${t.win_rate_pct}%`}),(0,b.jsx)(ps,{label:"Worst",value:`$${t.worst_match}`,tone:"down"})]}),(0,b.jsx)("p",{className:"hint",children:t.note})]})),ee?.state==="error"&&(0,b.jsx)("div",{className:"card sw-btcard bad",children:ee.error}),h2.filter(e=>"signal"===e||a[e]).map((e,t,s)=>{let r=v===e,n=(e=>{if(!T)return"idle";let t=T.rows.filter(t=>h3.some(([a,s])=>s===e&&t.block.startsWith(a)));return t.length?t.every(e=>e.pass)?"pass":"stop":"idle"})(e);return(0,b.jsxs)("div",{className:"sw-seg",children:[(0,b.jsxs)("div",{className:"sw-spine",children:[(0,b.jsx)("span",{className:`node ${n}`,children:h4[e].icon}),t<s.length-1&&(0,b.jsx)("span",{className:`wire ${"pass"===n?"pass":""}`})]}),(0,b.jsxs)("section",{className:`card sw-stage ${r?"open":""} v-${n}`,children:[(0,b.jsxs)("button",{className:"sw-stage-head",onClick:()=>y(r?null:e),"aria-expanded":r,children:[(0,b.jsx)("span",{className:"sw-stage-title",children:h4[e].label}),(0,b.jsx)("span",{className:"sw-stage-sum",children:function(e,t){let a=t[e]||{};switch(e){case"universe":{let e="under"===a.side?"Under":"Over",t="allow"===a.leagues_mode?`only ${a.leagues||"…"}`:"deny"===a.leagues_mode?`except ${a.leagues||"…"}`:"every league";return`${e} ${a.line??.5} \xb7 ${"h1"===a.period?"first half":"full match"} \xb7 ${t}`}case"state_gates":return`${a.start_minute??20}′–${a.end_minute??80}′, while ≤ ${a.max_total_goals??0} goals`;case"market_gates":{let e=`pay up to ${h8(a.max_price??.7)}`;return t.universe?.side!=="under"&&(e+=` — cagey ${h8(a.trap_price??.62)}, open ${h8(a.open_price??.74)}`),e}case"signal":{let e=String(a.type||"always");if("always"===e)return"price alone is enough";if("form"===e)return`both teams in scoring form (${a.min_total??2.7}+ goals/match)`;if("model_edge"===e)return`our model sees ${h8(a.min_edge??.05)}+ edge`;if("sharp_anchor"===e)return`bookmakers see ${h8(a.min_edge??.03)}+ edge`;if("ai_signal"===e)return`the commentary AI says buy (fresh within ${a.recency_min??5}′)`;if("ai_prompt"===e)return`your own prompt says buy (runs every ${a.ca
11dence_min??5}′)`;if("safety_meter"===e)return`history says ${h8(a.min_edge??.05)}+ edge`;return e}case"sizing":return`$${a.match_cap_usd??250} per match in ${a.tranches??5} buys`+(Number(a.daily_loss_usd)>0?`, stop at −$${a.daily_loss_usd}/day`:"");case"exits":{let e=[];return Number(a.take_profit_bid)>0&&e.push(`sell winners at ${h8(a.take_profit_bid)}`),Number(a.defensive_minute)>0&&e.push(`salvage after ${a.defensive_minute}′`),e.length?e.join(", "):"hold to the final whistle"}case"execution":return`one buy per ${a.cadence_min??10}′, adds must be ${h8(a.add_improve??.01)} cheaper`}}(e,m.blocks)}),(0,b.jsx)("svg",{className:"chev",width:"12",height:"12",viewBox:"0 0 16 16",fill:"none","aria-hidden":!0,children:(0,b.jsx)("path",{d:"M4 6l4 4 4-4",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round"})})]}),r&&(0,b.jsx)("div",{className:"sw-stage-body",children:"signal"===e?(0,b.jsxs)(b.Fragment,{children:[(0,b.jsxs)("div",{className:"frow",children:[(0,b.jsx)("label",{children:"signal"}),(0,b.jsx)("select",{value:Q,disabled:!!m.readonly,onChange:e=>{let t=e.target.value,s={type:t};for(let e of a.signal.types[t].fields)s[e.key]=e.default;x({...m,blocks:{...m.blocks,signal:s}}),f(!0)},children:Object.keys(a.signal.types).map(e=>(0,b.jsx)("option",{value:e,children:e},e))})]}),(0,b.jsx)("p",{className:"hint",children:a.signal.types[Q]?.help}),a.signal.types[Q]?.fields.map(e=>(0,b.jsxs)("div",{className:`frow ${"textarea"===e.kind?"tall":""}`,title:e.help||"",children:[(0,b.jsx)("label",{children:e.key.replaceAll("_"," ")}),X("signal",e)]},e.key))]}):a[e].fields.map(t=>(0,b.jsxs)("div",{className:"frow",title:t.help||"",children:[(0,b.jsx)("label",{children:t.key.replaceAll("_"," ")}),X(e,t)]},t.key))})]})]},e)})]}),(0,b.jsx)("aside",{className:"sw-inspect",children:(0,b.jsxs)("div",{className:"card sw-inspect-card",children:[(0,b.jsx)("div",{className:"sw-inspect-h",children:"Live decision"}),(0,b.jsxs)("select",{value:E||"",onChange:e=>A(e.target.value||null),children:[(0,b.jsx)("option",{value:"",children:"Choose a live match…"}),C.map(e=>(0,b.jsxs)("option",{value:e.event_id,children:[e.home_team," v ",e.away_team," · ",e.score_home,"-",e.score_away," · ",e.minute,"′"]},e.event_id))]}),!E&&(0,b.jsxs)("div",{className:"sw-inspect-empty",children:[(0,b.jsx)("b",{children:C.length}),(0,b.jsxs)("span",{children:["match",1===C.length?"":"es"," live right now. Pick one and this strategy decides on it every 10 seconds — you'll see exactly which rule holds it back",Z?"":" (save first: the trace runs the saved version)","."]})]}),E&&T&&K&&(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)("div",{className:`sw-conclusion ${K.pass?"":"stop"}`,children:K.text}),(0,b.jsx)("div",{className:"sw-verdicts",children:T.rows.map((e,t)=>(0,b.jsxs)("div",{className:`vrow ${e.pass?"":"stop"}`,children:[(0,b.jsx)("span",{children:e.pass?"✓":"✕"}),(0,b.jsx)("p",{children:e.detail})]},t))}),(0,b.jsxs)("div",{className:"hint",children:["Dry run — no orders placed · ",new Date(T.at).toLocaleTimeString()]})]})]})})]})})]})]}),N&&(0,b.jsx)("div",{className:`toast ${N.ok?"":"bad"}`,children:N.msg})]})}function pn(){let[e,t]=(0,_.useState)("");return(0,_.useEffect)(()=>{function e(){t(new Date().toISOString().slice(11,19)+" UTC")}e();let a=setInterval(e,1e3);return()=>clearInterval(a)},[]),(0,b.jsx)("span",{className:"ws-topbar-clock",children:e})}function pl({views:e,activeView:t,onViewChange:a}){let s=(0,_.useRef)(null);return(0,_.useEffect)(()=>{s.current?.querySelector(".ws-topbar-tab.active")?.scrollIntoView({behavior:"smooth",block:"nearest",inline:"nearest"})},[t]),(0,b.jsxs)("header",{className:"ws-topbar",children:[(0,b.jsxs)("div",{className:"ws-topbar-logo",children:[(0,b.jsx)("span",{children:"OP"})," OpenPoly"]}),(0,b.jsx)("nav",{ref:s,className:"ws-topbar-nav","aria-label":"Workspace views",onWheel:function(e){let t=e.currentTarget;t.scrollWidth<=t.clientWidth||Math.abs(e.deltaX)>=Math.abs(e.deltaY)||(t.scrollLeft+=e.deltaY,e.preventDefault())},children:e.map(e=>(0,b.jsxs)("button",{type:"button",className:`ws-topbar-tab${t===e.key?" active":""}`,onClick:()=>
11a(e.key),children:[e.label,e.shortcut?(0,b.jsx)("kbd",{children:e.shortcut}):null]},e.key))}),(0,b.jsx)("div",{className:"ws-topbar-spacer"}),(0,b.jsx)(pn,{}),(0,b.jsx)("div",{className:"ws-topbar-account",children:(0,b.jsx)(sW.default,{})})]})}let pi={status:null,ts:0},po=new Set,pc=!1;async function pd(){if(!pc){pc=!0;try{let t=await (0,er.getJson)("/api/status");var e=t?.data||null;for(let t of(pi={status:e,ts:Date.now()},po))t(e)}catch{}finally{pc=!1}}}let pu=null;function ph(){let{status:e,isLive:t}=function(){let[e,t]=(0,_.useState)(pi.status),a=(0,_.useRef)(t);a.current=t,(0,_.useEffect)(()=>{let e=e=>a.current(e);return po.add(e),pu||(pd(),pu=setInterval(pd,6e3)),pi.status&&t(pi.status),()=>{po.delete(e),0===po.size&&pu&&(clearInterval(pu),pu=null)}},[]);let s=(0,_.useCallback)(()=>{pd()},[]);return{status:e,isLive:!!e?.stack?.running,refresh:s}}(),a=e?.stack?.pid??"-",s=(()=>{if(!t||!e?.stack?.started_at_ms)return"-";let a=Math.floor((Date.now()-e.stack.started_at_ms)/1e3);if(a<60)return`${a}s`;let s=Math.floor(a/60);if(s<60)return`${s}m ${a%60}s`;let r=Math.floor(s/60);return`${r}h ${s%60}m`})();return(0,b.jsxs)("footer",{className:"ws-statusbar",children:[(0,b.jsxs)("div",{className:"ws-statusbar-item",children:[(0,b.jsx)("span",{className:`status-dot ${t?"live":"down"}`}),(0,b.jsxs)("span",{children:["Engine ",t?"Running":"Stopped"]})]}),(0,b.jsxs)("div",{className:"ws-statusbar-item",children:["PID ",a]}),(0,b.jsxs)("div",{className:"ws-statusbar-item",children:["Uptime ",s]}),(0,b.jsx)("div",{className:"ws-statusbar-spacer"}),(0,b.jsxs)("div",{className:"ws-statusbar-shortcuts",children:[(0,b.jsxs)("span",{children:[(0,b.jsx)("kbd",{children:"Ctrl+1"})," Command"]}),(0,b.jsxs)("span",{children:[(0,b.jsx)("kbd",{children:"Ctrl+2"})," Backtest"]}),(0,b.jsxs)("span",{children:[(0,b.jsx)("kbd",{children:"Ctrl+3"})," Monitor"]})]})]})}var pp=e.i(94155);let pm=[{key:"bots",label:"Bots",shortcut:"1"},{key:"research",label:"Research",shortcut:"2"},{key:"pattern",label:"Pattern Lab",shortcut:"3"},{key:"aggregator",label:"Aggregator",shortcut:"4"},{key:"wallet",label:"Wallet Management",shortcut:"5"}];function px(){return(0,b.jsx)(ez.MarketTabsProvider,{children:(0,b.jsx)(pg,{})})}function pg(){let{user:e,loading:t,openModal:a}=(0,pp.useAuth)(),[s,r]=(0,_.useState)("bots"),[n,l]=(0,_.useState)(null),{tabs:i,activeId:o,activate:c,closeTab:d,setTitle:u}=(0,ez.useMarketTabs)(),h=i.find(e=>e.id===o)||null;(0,_.useEffect)(()=>{t||e||a()},[t,e,a]),(0,_.useEffect)(()=>{e?(0,er.authGetJson)("/api/terminal-access").then(()=>l(!0)).catch(()=>l(!1)):l(null)},[e]);let p=(0,_.useCallback)(e=>{r(e),c(null)},[c]);!function({onViewSwitch:e,onToggleAgent:t}){(0,_.useEffect)(()=>{function a(a){if(a.ctrlKey||a.metaKey){let s=v[a.key];if(s&&e){a.preventDefault(),e(s);return}if("k"===a.key&&t){a.preventDefault(),t();return}}}return window.addEventListener("keydown",a),()=>window.removeEventListener("keydown",a)},[e,t])}({onViewSwitch:p});let[m,x]=(0,_.useState)([]);(0,_.useEffect)(()=>{h&&x(e=>e.includes(h.id)?e:[...e,h.id])},[h?.id]);let g=i.filter(e=>"wc"===e.kind||m.includes(e.id)),f=(0,_.useCallback)(()=>{switch(s){case"wallet":return(0,b.jsx)(sJ,{});case"trader":return(0,b.jsx)(ea,{});case"traderwatch":return(0,b.jsx)(e0,{});case"reverselab":return(0,b.jsx)(tS,{});case"weather":return(0,b.jsx)(tH,{});case"entertainment":return(0,b.jsx)(tq.default,{});case"synthesizer":return(0,b.jsx)(eP,{});case"hunt":return(0,b.jsx)(eD,{});case"aggregator":return(0,b.jsx)(sM,{});case"radar":return(0,b.jsx)(s7.default,{});case"worldcup":return(0,b.jsx)(rQ,{});case"esports":return(0,b.jsx)(nQ,{});case"umabonder":return(0,b.jsx)(n0,{});case"bots":default:return(0,b.jsx)(lt,{});case"research":return(0,b.jsx)(lh,{});case"autotraders":return(0,b.jsx)(n2,{});case"studio":return(0,b.jsx)(pr,{});case"fcpo":return(0,b.jsx)(nL,{});case"sports":return(0,b.jsx)(nV,{});case"strategy":return(0,b.jsx)(hZ,{});case"playbook":return(0,b.jsx)(h1,{});case"pattern":return(0,b.jsx)(sp,{})}},[s]),y=(0,_.useCallback)(()=>(0,b.jsxs)(b.Fragment,{children:[(0,b.jsx)("div",{className:"ws-keepalive",style:{display:h?"none":void 0},children:f()}),g.map(e=>(0,b.jsx)("div",{className:"ws-keepalive",style:{display:h?.id===e.id?void 0:"none"},children:"wc"===e.kind?(0,b.jsx)(np,{eventId:e.marketId,inline:!0,active:h?.id===e.id,onClose:()=>d(e.id),onTitle:t=>u(e.id,t)}
11):"es"===e.kind?(0,b.jsx)(nZ,{eventId:e.marketId,inline:!0,onClose:()=>d(e.id),onTitle:t=>u(e.id,t)}):"sport"===e.kind?(0,b.jsx)(nY,{eventId:e.marketId,inline:!0,onClose:()=>d(e.id),onTitle:t=>u(e.id,t)}):(0,b.jsx)(s7.DetailOverlay,{marketId:e.marketId,inline:!0,onClose:()=>d(e.id),onTitle:t=>u(e.id,t)})},e.id))]}),[h,g,f,d,u]);if(t)return(0,b.jsx)("div",{className:"ws-shell",children:(0,b.jsx)("main",{className:"ws-viewport",children:(0,b.jsx)("div",{className:"empty-state",style:{height:"100%",minHeight:"40vh"},children:"Checking authentication..."})})});if(!e)return(0,b.jsx)("div",{className:"ws-shell",children:(0,b.jsx)("main",{className:"ws-viewport",children:(0,b.jsxs)("div",{className:"empty-state",style:{height:"100%",minHeight:"40vh",gap:"var(--space-3)"},children:[(0,b.jsx)("div",{children:"Terminal access requires authentication."}),(0,b.jsx)("button",{className:"btn btn-primary",onClick:a,children:"Sign in to continue"})]})})});if(null===n)return(0,b.jsx)("div",{className:"ws-shell",children:(0,b.jsx)("main",{className:"ws-viewport",children:(0,b.jsx)("div",{className:"empty-state",style:{height:"100%",minHeight:"40vh"},children:"Verifying access..."})})});if(!1===n)return(0,b.jsx)("div",{className:"ws-shell",children:(0,b.jsx)("main",{className:"ws-viewport",children:(0,b.jsxs)("div",{className:"empty-state",style:{height:"100%",minHeight:"40vh",gap:"var(--space-3)"},children:[(0,b.jsx)("div",{children:"Terminal access restricted."}),(0,b.jsx)("div",{style:{fontSize:"var(--fs-xs)",color:"var(--fg-muted)"},children:"Your account does not have terminal access."})]})})});let j=pm.find(e=>e.key===s)?.label||"list";return(0,b.jsx)(b.Fragment,{children:(0,b.jsxs)("div",{className:"ws-shell",children:[(0,b.jsx)(pl,{views:pm,activeView:s,onViewChange:p}),(0,b.jsx)("div",{className:"ws-tabsrow",children:(0,b.jsx)(ez.MarketTabStrip,{viewLabel:j})}),(0,b.jsx)("main",{className:"ws-viewport",children:y()}),(0,b.jsx)(ph,{})]})})}e.s(["default",()=>px],89364)}]);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.