const{useState,useEffect,useMemo,useReducer,useCallback,useRef}=React,{RadarChart,PolarGrid,PolarAngleAxis,PolarRadiusAxis,Radar,LineChart,Line,XAxis,YAxis,Tooltip,ResponsiveContainer,BarChart,Bar,Cell,PieChart,Pie,AreaChart,Area,CartesianGrid,ReferenceLine}=Recharts;class StockfishEngine{constructor(){this.worker=null,this.ready=!1}async init(){return new Promise((t,n)=>{try{const i=window.LumiAssets?.stockfishSingleWorkerUrl?.();if(!i)throw new Error("Stockfish asset loader unavailable");this.worker=new Worker(i)}catch(i){n(new Error("Failed to create Stockfish worker: "+i.message));return}const a=setTimeout(()=>n(new Error("Stockfish init timeout")),15e3),s=i=>{if((typeof i.data=="string"?i.data:i.data?.data||"").includes("uciok")){clearTimeout(a),this.ready=!0,this.worker.removeEventListener("message",s),this.worker.postMessage("setoption name Hash value 16"),this.worker.postMessage("isready");const m=l=>{(typeof l.data=="string"?l.data:"").includes("readyok")&&(this.worker.removeEventListener("message",m),t())};this.worker.addEventListener("message",m)}};this.worker.addEventListener("message",s),this.worker.postMessage("uci")})}newGame(){return this.ready?new Promise(t=>{this.worker.postMessage("ucinewgame"),this.worker.postMessage("isready");const n=a=>{(typeof a.data=="string"?a.data:"").includes("readyok")&&(this.worker.removeEventListener("message",n),t())};this.worker.addEventListener("message",n)}):Promise.resolve()}analyze(t,n=10){return new Promise((a,s)=>{let i={depth:0,score:0,type:"cp",raw:0,bestMove:null},p=!1;const m=setTimeout(()=>{if(!p){p=!0;try{this.worker?.removeEventListener("message",l)}catch{}try{this.worker?.postMessage("stop")}catch{}this.ready=!1,s(new Error("analyze timeout"))}},15e3),l=r=>{const c=typeof r.data=="string"?r.data:"";if(c.startsWith("info")&&c.includes("score")){const y=c.match(/\bdepth (\d+)/),k=c.match(/\bscore (cp|mate) (-?\d+)/),d=c.match(/\bpv (.+)/);if(y&&k){const u=parseInt(y[1]),o=k[1],g=parseInt(k[2]),f=o==="mate"?g>0?1e4-Math.abs(g)*10:-1e4+Math.abs(g)*10:g;u>=i.depth&&(i={depth:u,score:f,type:o,raw:g,bestMove:d?d[1].split(" ")[0]:null})}}if(c.startsWith("bestmove")){if(p)return;p=!0,clearTimeout(m),this.worker.removeEventListener("message",l);const y=c.split(" ")[1];y&&!i.bestMove&&(i.bestMove=y),a(i)}};this.worker.addEventListener("message",l),this.worker.postMessage("position fen "+t),this.worker.postMessage("go depth "+n)})}stop(){this.worker&&this.worker.postMessage("stop")}destroy(){this.worker&&(this.worker.postMessage("quit"),this.worker.terminate(),this.worker=null,this.ready=!1)}}function parsePGNHeaders(e){const t={},n=/\[(\w+)\s+"([^"]*)"\]/g;let a;for(;(a=n.exec(e))!==null;)t[a[1]]=a[2];return t}function openingNameFromHeaders(e){const t=(e.ECOUrl||"").split("/").pop()?.replace(/-/g," ");return t||(e.Opening?e.Opening:e.ECO?ECO_NAMES[e.ECO]||e.ECO:"Unknown")}const ECO_NAMES={A00:"Uncommon Opening",A01:"Nimzo-Larsen Attack",A02:"Bird's Opening",A03:"Bird's Opening",A04:"Reti Opening",A05:"Reti Opening",A06:"Reti Opening",A07:"King's Indian Attack",A08:"King's Indian Attack",A09:"Reti Opening",A10:"English Opening",A11:"English Opening",A12:"English Opening",A13:"English Opening",A14:"English Opening",A15:"English Opening",A16:"English Opening",A17:"English Opening",A18:"English Opening",A19:"English Opening",A20:"English Opening",A21:"English Opening",A22:"English Opening",A23:"English Opening",A24:"English Opening",A25:"English Opening",A26:"English Opening",A27:"English Opening",A28:"English Opening",A29:"English Opening",A30:"English Opening",A31:"English Opening",A32:"English Opening",A33:"English Opening",A34:"English Opening",A35:"English Opening",A36:"English Opening",A37:"English Opening",A38:"English Opening",A39:"English Opening",A40:"Queen's Pawn Game",A41:"Queen's Pawn Game",A42:"Modern Defense",A43:"Old Benoni",A44:"Old Benoni",A45:"Queen's Pawn Game",A46:"Queen's Pawn Game",A47:"Queen's Indian Defense",A48:"King's Indian Defense",A49:"King's Indian Defense",A50:"Queen's Indian Defense",A51:"Budapest Gambit",A52:"Budapest Gambit",A53:"Old Indian Defense",A54:"Old Indian Defense",A55:"Old Indian Defense",A56:"Benoni Defense",A57:"Benko Gambit",A58:"Benko Gambit",A59:"Benko Gambit",A60:"Benoni Defense",A61:"Benoni Defense",A62:"Benoni Defense",A63:"Benoni Defense",A64:"Benoni Defense",A65:"Benoni Defense",A66:"Benoni Defense",A67:"Benoni Defense",A68:"Benoni Defense",A69:"Benoni Defense",A70:"Benoni Defense",A71:"Benoni Defense",A72:"Benoni Defense",A73:"Benoni Defense",A74:"Benoni Defense",A75:"Benoni Defense",A76:"Benoni Defense",A77:"Benoni Defense",A78:"Benoni Defense",A79:"Benoni Defense",A80:"Dutch Defense",A81:"Dutch Defense",A82:"Dutch Defense",A83:"Dutch Defense",A84:"Dutch Defense",A85:"Dutch Defense",A86:"Dutch Defense",A87:"Dutch Defense",A88:"Dutch Defense",A89:"Dutch Defense",A90:"Dutch Defense",A91:"Dutch Defense",A92:"Dutch Defense",A93:"Dutch Defense",A94:"Dutch Defense",A95:"Dutch Defense",A96:"Dutch Defense",A97:"Dutch Defense",A98:"Dutch Defense",A99:"Dutch Defense",B00:"King's Pawn Game",B01:"Scandinavian Defense",B02:"Alekhine's Defense",B03:"Alekhine's Defense",B04:"Alekhine's Defense",B05:"Alekhine's Defense",B06:"Modern Defense",B07:"Pirc Defense",B08:"Pirc Defense",B09:"Pirc Defense",B10:"Caro-Kann Defense",B11:"Caro-Kann Defense",B12:"Caro-Kann Defense",B13:"Caro-Kann Defense",B14:"Caro-Kann Defense",B15:"Caro-Kann Defense",B16:"Caro-Kann Defense",B17:"Caro-Kann Defense",B18:"Caro-Kann Defense",B19:"Caro-Kann Defense",B20:"Sicilian Defense",B21:"Sicilian Defense",B22:"Sicilian Defense",B23:"Sicilian Defense",B24:"Sicilian Defense",B25:"Sicilian Defense",B26:"Sicilian Defense",B27:"Sicilian Defense",B28:"Sicilian Defense",B29:"Sicilian Defense",B30:"Sicilian Defense",B31:"Sicilian Defense",B32:"Sicilian Defense",B33:"Sicilian Defense",B34:"Sicilian Defense",B35:"Sicilian Defense",B36:"Sicilian Defense",B37:"Sicilian Defense",B38:"Sicilian Defense",B39:"Sicilian Defense",B40:"Sicilian Defense",B41:"Sicilian Defense",B42:"Sicilian Defense",B43:"Sicilian Defense",B44:"Sicilian Defense",B45:"Sicilian Defense",B46:"Sicilian Defense",B47:"Sicilian Defense",B48:"Sicilian Defense",B49:"Sicilian Defense",B50:"Sicilian Defense",B51:"Sicilian Defense",B52:"Sicilian Defense",B53:"Sicilian Defense",B54:"Sicilian Defense",B55:"Sicilian Defense",B56:"Sicilian Defense",B57:"Sicilian Defense",B58:"Sicilian Defense",B59:"Sicilian Defense",B60:"Sicilian Defense",B61:"Sicilian Defense",B62:"Sicilian Defense",B63:"Sicilian Defense",B64:"Sicilian Defense",B65:"Sicilian Defense",B66:"Sicilian Defense",B67:"Sicilian Defense",B68:"Sicilian Defense",B69:"Sicilian Defense",B70:"Sicilian Defense",B71:"Sicilian Defense",B72:"Sicilian Defense",B73:"Sicilian Defense",B74:"Sicilian Defense",B75:"Sicilian Defense",B76:"Sicilian Defense",B77:"Sicilian Defense",B78:"Sicilian Defense",B79:"Sicilian Defense",B80:"Sicilian Defense",B81:"Sicilian Defense",B82:"Sicilian Defense",B83:"Sicilian Defense",B84:"Sicilian Defense",B85:"Sicilian Defense",B86:"Sicilian Defense",B87:"Sicilian Defense",B88:"Sicilian Defense",B89:"Sicilian Defense",B90:"Sicilian Defense",B91:"Sicilian Defense",B92:"Sicilian Defense",B93:"Sicilian Defense",B94:"Sicilian Defense",B95:"Sicilian Defense",B96:"Sicilian Defense",B97:"Sicilian Defense",B98:"Sicilian Defense",B99:"Sicilian Defense",C00:"French Defense",C01:"French Defense",C02:"French Defense",C03:"French Defense",C04:"French Defense",C05:"French Defense",C06:"French Defense",C07:"French Defense",C08:"French Defense",C09:"French Defense",C10:"French Defense",C11:"French Defense",C12:"French Defense",C13:"French Defense",C14:"French Defense",C15:"French Defense",C16:"French Defense",C17:"French Defense",C18:"French Defense",C19:"French Defense",C20:"King's Pawn Game",C21:"King's Pawn Game",C22:"Center Game",C23:"Bishop's Opening",C24:"Bishop's Opening",C25:"Vienna Game",C26:"Vienna Game",C27:"Vienna Game",C28:"Vienna Game",C29:"Vienna Game",C30:"King's Gambit",C31:"King's Gambit",C32:"King's Gambit",C33:"King's Gambit",C34:"King's Gambit",C35:"King's Gambit",C36:"King's Gambit",C37:"King's Gambit",C38:"King's Gambit",C39:"King's Gambit",C40:"King's Pawn Game",C41:"Philidor Defense",C42:"Russian Game",C43:"Russian Game",C44:"King's Pawn Game",C45:"Scotch Game",C46:"Three Knights Game",C47:"Four Knights Game",C48:"Four Knights Game",C49:"Four Knights Game",C50:"Italian Game",C51:"Italian Game",C52:"Italian Game",C53:"Italian Game",C54:"Italian Game",C55:"Italian Game",C56:"Italian Game",C57:"Italian Game",C58:"Italian Game",C59:"Italian Game",C60:"Ruy Lopez",C61:"Ruy Lopez",C62:"Ruy Lopez",C63:"Ruy Lopez",C64:"Ruy Lopez",C65:"Ruy Lopez",C66:"Ruy Lopez",C67:"Ruy Lopez",C68:"Ruy Lopez",C69:"Ruy Lopez",C70:"Ruy Lopez",C71:"Ruy Lopez",C72:"Ruy Lopez",C73:"Ruy Lopez",C74:"Ruy Lopez",C75:"Ruy Lopez",C76:"Ruy Lopez",C77:"Ruy Lopez",C78:"Ruy Lopez",C79:"Ruy Lopez",C80:"Ruy Lopez",C81:"Ruy Lopez",C82:"Ruy Lopez",C83:"Ruy Lopez",C84:"Ruy Lopez",C85:"Ruy Lopez",C86:"Ruy Lopez",C87:"Ruy Lopez",C88:"Ruy Lopez",C89:"Ruy Lopez",C90:"Ruy Lopez",C91:"Ruy Lopez",C92:"Ruy Lopez",C93:"Ruy Lopez",C94:"Ruy Lopez",C95:"Ruy Lopez",C96:"Ruy Lopez",C97:"Ruy Lopez",C98:"Ruy Lopez",C99:"Ruy Lopez",D00:"Queen's Pawn Game",D01:"Richter-Veresov Attack",D02:"Queen's Pawn Game",D03:"Torre Attack",D04:"Queen's Pawn Game",D05:"Queen's Pawn Game",D06:"Queen's Gambit",D07:"Queen's Gambit",D08:"Queen's Gambit",D09:"Queen's Gambit",D10:"Queen's Gambit Declined",D11:"Queen's Gambit Declined",D12:"Queen's Gambit Declined",D13:"Queen's Gambit Declined",D14:"Queen's Gambit Declined",D15:"Queen's Gambit Declined",D16:"Queen's Gambit Declined",D17:"Queen's Gambit Declined",D18:"Queen's Gambit Declined",D19:"Queen's Gambit Declined",D20:"Queen's Gambit Accepted",D21:"Queen's Gambit Accepted",D22:"Queen's Gambit Accepted",D23:"Queen's Gambit Accepted",D24:"Queen's Gambit Accepted",D25:"Queen's Gambit Accepted",D26:"Queen's Gambit Accepted",D27:"Queen's Gambit Accepted",D28:"Queen's Gambit Accepted",D29:"Queen's Gambit Accepted",D30:"Queen's Gambit Declined",D31:"Queen's Gambit Declined",D32:"Queen's Gambit Declined",D33:"Queen's Gambit Declined",D34:"Queen's Gambit Declined",D35:"Queen's Gambit Declined",D36:"Queen's Gambit Declined",D37:"Queen's Gambit Declined",D38:"Queen's Gambit Declined",D39:"Queen's Gambit Declined",D40:"Queen's Gambit Declined",D41:"Queen's Gambit Declined",D42:"Queen's Gambit Declined",D43:"Queen's Gambit Declined",D44:"Queen's Gambit Declined",D45:"Queen's Gambit Declined",D46:"Queen's Gambit Declined",D47:"Queen's Gambit Declined",D48:"Queen's Gambit Declined",D49:"Queen's Gambit Declined",D50:"Queen's Gambit Declined",D51:"Queen's Gambit Declined",D52:"Queen's Gambit Declined",D53:"Queen's Gambit Declined",D54:"Queen's Gambit Declined",D55:"Queen's Gambit Declined",D56:"Queen's Gambit Declined",D57:"Queen's Gambit Declined",D58:"Queen's Gambit Declined",D59:"Queen's Gambit Declined",D60:"Queen's Gambit Declined",D61:"Queen's Gambit Declined",D62:"Queen's Gambit Declined",D63:"Queen's Gambit Declined",D64:"Queen's Gambit Declined",D65:"Queen's Gambit Declined",D66:"Queen's Gambit Declined",D67:"Queen's Gambit Declined",D68:"Queen's Gambit Declined",D69:"Queen's Gambit Declined",D70:"Neo-Grunfeld Defense",D71:"Neo-Grunfeld Defense",D72:"Neo-Grunfeld Defense",D73:"Neo-Grunfeld Defense",D74:"Neo-Grunfeld Defense",D75:"Neo-Grunfeld Defense",D76:"Neo-Grunfeld Defense",D77:"Neo-Grunfeld Defense",D78:"Neo-Grunfeld Defense",D79:"Neo-Grunfeld Defense",D80:"Grunfeld Defense",D81:"Grunfeld Defense",D82:"Grunfeld Defense",D83:"Grunfeld Defense",D84:"Grunfeld Defense",D85:"Grunfeld Defense",D86:"Grunfeld Defense",D87:"Grunfeld Defense",D88:"Grunfeld Defense",D89:"Grunfeld Defense",D90:"Grunfeld Defense",D91:"Grunfeld Defense",D92:"Grunfeld Defense",D93:"Grunfeld Defense",D94:"Grunfeld Defense",D95:"Grunfeld Defense",D96:"Grunfeld Defense",D97:"Grunfeld Defense",D98:"Grunfeld Defense",D99:"Grunfeld Defense",E00:"Catalan Opening",E01:"Catalan Opening",E02:"Catalan Opening",E03:"Catalan Opening",E04:"Catalan Opening",E05:"Catalan Opening",E06:"Catalan Opening",E07:"Catalan Opening",E08:"Catalan Opening",E09:"Catalan Opening",E10:"Queen's Pawn Game",E11:"Bogo-Indian Defense",E12:"Queen's Indian Defense",E13:"Queen's Indian Defense",E14:"Queen's Indian Defense",E15:"Queen's Indian Defense",E16:"Queen's Indian Defense",E17:"Queen's Indian Defense",E18:"Queen's Indian Defense",E19:"Queen's Indian Defense",E20:"Nimzo-Indian Defense",E21:"Nimzo-Indian Defense",E22:"Nimzo-Indian Defense",E23:"Nimzo-Indian Defense",E24:"Nimzo-Indian Defense",E25:"Nimzo-Indian Defense",E26:"Nimzo-Indian Defense",E27:"Nimzo-Indian Defense",E28:"Nimzo-Indian Defense",E29:"Nimzo-Indian Defense",E30:"Nimzo-Indian Defense",E31:"Nimzo-Indian Defense",E32:"Nimzo-Indian Defense",E33:"Nimzo-Indian Defense",E34:"Nimzo-Indian Defense",E35:"Nimzo-Indian Defense",E36:"Nimzo-Indian Defense",E37:"Nimzo-Indian Defense",E38:"Nimzo-Indian Defense",E39:"Nimzo-Indian Defense",E40:"Nimzo-Indian Defense",E41:"Nimzo-Indian Defense",E42:"Nimzo-Indian Defense",E43:"Nimzo-Indian Defense",E44:"Nimzo-Indian Defense",E45:"Nimzo-Indian Defense",E46:"Nimzo-Indian Defense",E47:"Nimzo-Indian Defense",E48:"Nimzo-Indian Defense",E49:"Nimzo-Indian Defense",E50:"Nimzo-Indian Defense",E51:"Nimzo-Indian Defense",E52:"Nimzo-Indian Defense",E53:"Nimzo-Indian Defense",E54:"Nimzo-Indian Defense",E55:"Nimzo-Indian Defense",E56:"Nimzo-Indian Defense",E57:"Nimzo-Indian Defense",E58:"Nimzo-Indian Defense",E59:"Nimzo-Indian Defense",E60:"King's Indian Defense",E61:"King's Indian Defense",E62:"King's Indian Defense",E63:"King's Indian Defense",E64:"King's Indian Defense",E65:"King's Indian Defense",E66:"King's Indian Defense",E67:"King's Indian Defense",E68:"King's Indian Defense",E69:"King's Indian Defense",E70:"King's Indian Defense",E71:"King's Indian Defense",E72:"King's Indian Defense",E73:"King's Indian Defense",E74:"King's Indian Defense",E75:"King's Indian Defense",E76:"King's Indian Defense",E77:"King's Indian Defense",E78:"King's Indian Defense",E79:"King's Indian Defense",E80:"King's Indian Defense",E81:"King's Indian Defense",E82:"King's Indian Defense",E83:"King's Indian Defense",E84:"King's Indian Defense",E85:"King's Indian Defense",E86:"King's Indian Defense",E87:"King's Indian Defense",E88:"King's Indian Defense",E89:"King's Indian Defense",E90:"King's Indian Defense",E91:"King's Indian Defense",E92:"King's Indian Defense",E93:"King's Indian Defense",E94:"King's Indian Defense",E95:"King's Indian Defense",E96:"King's Indian Defense",E97:"King's Indian Defense",E98:"King's Indian Defense",E99:"King's Indian Defense"};function extractClockTimes(e){const t=[],n=/\{[^}]*\[%clk\s+(\d+):(\d+):(\d+(?:\.\d+)?)\][^}]*\}/g;let a;for(;(a=n.exec(e))!==null;)t.push(parseInt(a[1])*3600+parseInt(a[2])*60+parseFloat(a[3]));return t}function replayGame(e){if(!window.Chess)return null;const t=new Chess,n=e.replace(/\{[\s\S]*?\}/g,"").replace(/\$\d+/g,"").replace(/\d+\.\.\./g,"");try{t.loadPgn(n)}catch{return null}const a=t.history({verbose:!0});if(!a||a.length===0)return null;t.reset();const s=[t.fen()],i=[];for(const p of a)t.move(p.san),s.push(t.fen()),i.push(p.san);return{moves:a,positions:s,sanMoves:i}}function getFenPhase(e,t){const n=e?e.split(" ")[0]:"";let a=0;for(const s of n)(s==="Q"||s==="q"||s==="R"||s==="r"||s==="B"||s==="b"||s==="N"||s==="n")&&a++;return a<=4?"endgame":t<30?"opening":"middlegame"}function classifyMoveByWinDrop(e){return e<=0?"best":e<=2?"excellent":e<=5?"good":e<=10?"inaccuracy":e<=20?"mistake":"blunder"}const CLASSIFICATION_COLORS={brilliant:"#14e6e6",best:"#7bcc18",excellent:"#7bcc18",good:"#088a28",book:"#d5a47d",inaccuracy:"#ddd015",mistake:"#e5820d",blunder:"#d44242"},CLASSIFICATION_LABELS={brilliant:"Brilliant",best:"Best",excellent:"Excellent",good:"Good",book:"Book",inaccuracy:"Inaccuracy",mistake:"Mistake",blunder:"Blunder"};function cpToWinPct(e){return 100/(1+Math.exp(-.00368208*e))}function moveAccuracy(e){if(e<=0)return 100;const t=103.1668*Math.exp(-.04354*e)-3.1669;return Math.max(0,Math.min(100,t+1))}function computeAccuracy(e){if(e<=0)return 100;const t=cpToWinPct(e)-50;return Math.max(0,Math.min(100,moveAccuracy(Math.max(0,t))))}function capEval(e){return Math.max(-1e3,Math.min(1e3,e))}const ProfileCache={_db:null,_ready:!1,async init(){if(!this._ready)try{this._db=await new Promise((e,t)=>{const n=indexedDB.open("lumichess-profile",1);n.onupgradeneeded=a=>{const s=a.target.result;s.objectStoreNames.contains("cache")||s.createObjectStore("cache",{keyPath:"key"})},n.onsuccess=()=>e(n.result),n.onerror=()=>t(n.error)}),this._ready=!0}catch(e){console.warn("ProfileCache init failed:",e.message)}},async _get(e){return this._ready?new Promise(t=>{try{const a=this._db.transaction("cache","readonly").objectStore("cache").get(e);a.onsuccess=()=>t(a.result||null),a.onerror=()=>t(null)}catch{t(null)}}):null},async _put(e,t){if(this._ready)try{this._db.transaction("cache","readwrite").objectStore("cache").put({key:e,...t})}catch(n){console.warn("ProfileCache write failed:",n.message)}},_key(e,...t){return`profile_${e}_${t.join("_")}`},async getGameAnalysis(e,t,n){return(await this._get(this._key("game",e,t,n)))?.data||null},async saveGameAnalysis(e,t,n,a){await this._put(this._key("game",e,t,n),{data:a,ts:Date.now()})},async getSnapshot(e,t){return(await this._get(this._key("snapshot",e,t)))?.data||null},async saveSnapshot(e,t,n){await this._put(this._key("snapshot",e,t),{data:n,ts:Date.now()})},async getFullReport(e,t){return(await this._get(this._key("full",e,t)))?.data||null},async saveFullReport(e,t,n){await this._put(this._key("full",e,t),{data:n,ts:Date.now()})},async getLastUsed(){return(await this._get("profile_lastused"))?.data||null},async saveLastUsed(e,t){await this._put("profile_lastused",{data:{platform:e,username:t}})},async getHistory(e,t){return(await this._get(this._key("history",e,t)))?.entries||[]},async appendHistory(e,t,n){const a=await this.getHistory(e,t);a.push({...n,date:new Date().toISOString()});const s=a.slice(-20);await this._put(this._key("history",e,t),{entries:s,ts:Date.now()})}},MC_TYPE_TO_LEGACY={bestmove:"best",excellent:"excellent",good:"good",inaccuracy:"inaccuracy",mistake:"mistake",blunder:"blunder",bookmove:"book",forced:"best",missed:"mistake",great:"excellent",brilliant:"best"};function uciFromVerboseMove(e){return e.from+e.to+(e.promotion||"")}async function analyzeGameWithEngine(e,t,n,a,s){const i=replayGame(e);if(!i)return null;const{positions:p,sanMoves:m,moves:l}=i,r=parsePGNHeaders(e),c=extractClockTimes(e),y=(r.White||"").toLowerCase()===s.toLowerCase()?"w":"b",k=window.LumiProfile?.MoveClassifier,d=window.LumiProfile?.Classification;await t.newGame();const u=[];let o=null;o=await t.analyze(p[0],n);let g=d?d.BOOKMOVE:null;for(let z=0;z<m.length;z++){const B=p[z],W=p[z+1],G=await t.analyze(W,n),$=Math.max(0,Math.min(300,capEval(o.score)+capEval(G.score))),A=z%2===0?"w":"b",O=A==="w"?-G.score:G.score,F=cpToWinPct(capEval(o.score)),K=cpToWinPct(capEval(-G.score)),V=Math.max(0,F-K),Z=moveAccuracy(V),J=B.includes(" b ")?-o.score:o.score,X=W.includes(" b ")?-G.score:G.score;let Y="good",H=null;if(k&&d){const U=l[z]?uciFromVerboseMove(l[z]):null,te={fen:W,uciMove:U,san:m[z],lines:[{id:1,score:X,type:G.type||"cp",uciMove:G.bestMove||null}]},ne={fen:B,classification:g,lines:[{id:1,score:J,type:o.type||"cp",uciMove:o.bestMove||null}]};try{H=k.classifyMove(te,ne,m.slice(0,z+1)),g=H;const Q=H?.type||"good";Y=MC_TYPE_TO_LEGACY[Q]||"good"}catch(Q){console.warn("[profile-report] classifyMove threw; falling back to good:",Q?.message||Q),Y="good"}}const q=H?.type,ee=q==="bookmove"||q==="forced";let j;if(ee)j=100;else{const U=(H?.accuracy??.84)*100;j=.25*Z+.75*U}u.push({moveNumber:Math.floor(z/2)+1,san:m[z],turn:A,cpl:$,classification:Y,gamePhase:getFenPhase(W,z),evalBefore:o.score,evalAfter:G.score,whiteEval:O,bestMove:o.bestMove,clock:c[z]||null,isPlayerMove:A===y,accuracy:j}),o=G,a&&a(z+1,m.length)}const f=u.filter(z=>z.isPlayerMove),x=u.filter(z=>!z.isPlayerMove),v=f.length>0?f.reduce((z,B)=>z+B.cpl,0)/f.length:0,h=x.length>0?x.reduce((z,B)=>z+B.cpl,0)/x.length:0,S=f.length>0?f.reduce((z,B)=>z+B.accuracy,0)/f.length:0,C=x.length>0?x.reduce((z,B)=>z+B.accuracy,0)/x.length:0,M={};for(const z of f)M[z.classification]=(M[z.classification]||0)+1;const R=f.filter(z=>z.gamePhase==="opening"),b=f.filter(z=>z.gamePhase==="middlegame"),w=f.filter(z=>z.gamePhase==="endgame"),D=R.length>0?R.reduce((z,B)=>z+B.cpl,0)/R.length:0,N=b.length>0?b.reduce((z,B)=>z+B.cpl,0)/b.length:0,T=w.length>0?w.reduce((z,B)=>z+B.cpl,0)/w.length:0,E=u.map(z=>z.whiteEval),L=E.some(z=>(y==="w"?z:-z)>=150),_=E.some(z=>(y==="w"?z:-z)<=-150),I=E.map(z=>y==="w"?z:-z),P=I.length>0?Math.max(...I):0;return{pgn:e,headers:r,playerColor:y,totalMoves:m.length,moveAnalysis:u,playerAccuracy:Math.round(S*10)/10,opponentAccuracy:Math.round(C*10)/10,playerAvgCpl:Math.round(v*10)/10,classifications:M,openingCpl:Math.round(D*10)/10,middlegameCpl:Math.round(N*10)/10,endgameCpl:Math.round(T*10)/10,wasWinning:L,wasLosing:_,maxAdvantage:Math.round(P),evalGraph:E,clocks:c}}function analyzeGameFromChessComAccuracy(e,t,n){const a=replayGame(e);if(!a)return null;const{sanMoves:s}=a,i=parsePGNHeaders(e),p=extractClockTimes(e),m=(i.White||"").toLowerCase()===n.toLowerCase()?"w":"b",l=s.map((r,c)=>{const y=c%2===0?"w":"b";return{moveNumber:Math.floor(c/2)+1,san:r,turn:y,cpl:null,classification:null,evalBefore:null,evalAfter:null,whiteEval:null,bestMove:null,clock:p[c]||null,isPlayerMove:y===m,accuracy:null}});return{pgn:e,headers:i,playerColor:m,totalMoves:s.length,moveAnalysis:l,playerAccuracy:t||0,opponentAccuracy:0,playerAvgCpl:0,classifications:null,openingCpl:0,middlegameCpl:0,endgameCpl:0,wasWinning:!1,wasLosing:!1,maxAdvantage:0,evalGraph:null,clocks:p,isQuickMode:!0}}function computeRadarFromAnalysis(e,t,n){const a=e.filter(E=>E!==null&&!E.isQuickMode);if(a.length===0)return computeHeuristicRadar(t,n);const s=a.reduce((E,L)=>E+L.openingCpl,0)/a.length,i=Math.max(15,Math.min(95,Math.round(100-s*1.5))),p=a.flatMap(E=>E.moveAnalysis.filter(L=>L.isPlayerMove)),m=p.filter(E=>E.classification==="brilliant"||E.classification==="best"||E.classification==="excellent").length,l=Math.max(15,Math.min(95,Math.round(m/Math.max(1,p.length)*130))),r=t.length,c=t.filter(E=>E.finalClock!==null&&E.finalClock<15).length,y=t.filter(E=>E.result==="loss"&&E.method==="timeout").length,k=Math.max(15,Math.round(100-c/Math.max(1,r)*200-y*3)),d=p.filter(E=>{const L=a.find(I=>I.moveAnalysis.includes(E));if(!L)return!1;const _=L.moveAnalysis.filter(I=>I.isPlayerMove);return _.indexOf(E)>=Math.floor(_.length*.7)}),u=d.length>0?d.reduce((E,L)=>E+(L.accuracy||0),0)/d.length:50,o=Math.max(15,Math.min(95,Math.round(u))),f=p.filter(E=>E.classification==="blunder").length/Math.max(1,p.length),x=Math.max(15,Math.min(95,Math.round(100-f*300))),v=a.filter(E=>E.maxAdvantage>=150),h=v.filter(E=>{const L=E.headers?.Result;return E.playerColor==="w"&&L==="1-0"||E.playerColor==="b"&&L==="0-1"}),S=v.length>0?h.length/v.length:.5,C=Math.max(15,Math.min(95,Math.round(S*100))),M=p.filter(E=>(E.turn==="w"?E.evalBefore:-E.evalBefore)<-100),R=M.length>0?M.reduce((E,L)=>E+(L.accuracy||0),0)/M.length:50,b=Math.max(15,Math.min(95,Math.round(R))),w=a.map(E=>E.playerAccuracy),D=w.reduce((E,L)=>E+L,0)/w.length,N=Math.sqrt(w.reduce((E,L)=>E+(L-D)**2,0)/w.length),T=Math.max(15,Math.min(95,Math.round(90-N*2)));return[{dim:"Opening Prep",value:i,fullMark:100},{dim:"Tactical Vision",value:l,fullMark:100},{dim:"Time Management",value:k,fullMark:100},{dim:"Endgame",value:o,fullMark:100},{dim:"Blunder Resist.",value:x,fullMark:100},{dim:"Conversion",value:C,fullMark:100},{dim:"Defense",value:b,fullMark:100},{dim:"Mental Game",value:T,fullMark:100}]}function computeHeuristicRadar(e,t){const n=t||{tactics:{highest:0}},a=e.length||1,s=e.filter(u=>u.result==="win").length,i=e.filter(u=>u.finalClock!==null&&u.finalClock<15).length,p=e.filter(u=>u.moves>=50).length,m=e.filter(u=>u.accuracy!==null),l=m.length>0?m.reduce((u,o)=>u+o.accuracy,0)/m.length:70,r=(()=>{const u={};return e.forEach(o=>{u[o.date]=(u[o.date]||0)+1}),Object.values(u).filter(o=>o>=8).length})();let c=0,y=0,k=null;e.forEach(u=>{u.result===k?y++:(y=1,k=u.result),u.result==="loss"&&(c=Math.max(c,y))});const d={};return e.forEach(u=>{d[u.opening]=(d[u.opening]||0)+1}),[{dim:"Opening Prep",value:Math.min(95,Math.round(50+Object.keys(d).filter(u=>d[u]>=3).length*5)),fullMark:100},{dim:"Tactical Vision",value:Math.min(95,Math.round(Math.min(n.tactics.highest/25,80))),fullMark:100},{dim:"Time Management",value:Math.max(15,Math.round(100-i/a*200)),fullMark:100},{dim:"Endgame",value:Math.min(85,Math.round(40+p*3)),fullMark:100},{dim:"Blunder Resist.",value:Math.round(Math.max(30,l-10)),fullMark:100},{dim:"Conversion",value:Math.round(s/Math.max(1,a)*120),fullMark:100},{dim:"Defense",value:Math.round(50+e.filter(u=>u.result==="draw").length*5),fullMark:100},{dim:"Mental Game",value:Math.max(25,Math.round(70-r*15-c*5)),fullMark:100}]}function analyzeGamesHeuristic(e,t){const n=t||{rapid:{current:0,best:0},blitz:{current:0,best:0},bullet:{current:0,best:0},daily:{current:0,best:0},tactics:{highest:0},puzzleRush:{best:0}};if(!e||e.length===0)return{total:0,wins:0,losses:0,draws:0,winRate:0,timeoutLosses:0,timeoutWins:0,timeTrouble:0,severeTimeTrouble:0,avgAccuracy:0,openings:[],asWhite:0,asBlack:0,whiteWinRate:0,blackWinRate:0,avgMoves:0,ratingTrend:[],winMethods:{},lossMethods:{},longestSession:0,marathonDays:0,longestWinStreak:0,longestLossStreak:0,afterLossWinRate:0,radar:[{dim:"Opening Prep",value:50,fullMark:100},{dim:"Tactical Vision",value:50,fullMark:100},{dim:"Time Management",value:50,fullMark:100},{dim:"Endgame",value:50,fullMark:100},{dim:"Blunder Resist.",value:50,fullMark:100},{dim:"Conversion",value:50,fullMark:100},{dim:"Defense",value:50,fullMark:100},{dim:"Mental Game",value:50,fullMark:100}],lumiScore:50,personality:"Unknown",rapidBlitzGap:0,analyzedGames:[],isHeuristic:!0};const a=e.length,s=e.filter(A=>A.result==="win").length,i=e.filter(A=>A.result==="loss").length,p=e.filter(A=>A.result==="draw").length,m=e.filter(A=>A.result==="loss"&&A.method==="timeout").length,l=e.filter(A=>A.result==="win"&&A.method==="timeout").length,r=e.filter(A=>A.finalClock!==null&&A.finalClock<15).length,c=e.filter(A=>A.finalClock!==null&&A.finalClock<5).length,y=e.filter(A=>A.accuracy!==null),k=y.length>0?y.reduce((A,O)=>A+O.accuracy,0)/y.length:0,d=A=>{const O=A.split(/\s+/);let F=O.slice(0,2).join(" ");return F.length>22&&(F=O[0]),F.length>22&&(F=F.slice(0,20)+".."),F},u={};e.forEach(A=>{const O=d(A.opening);u[O]||(u[O]={name:O,wins:0,losses:0,draws:0,total:0,eco:A.eco}),u[O].total++,A.result==="win"?u[O].wins++:A.result==="loss"?u[O].losses++:u[O].draws++});const o=Object.values(u).sort((A,O)=>O.total-A.total),g=e.filter(A=>A.color==="white"),f=e.filter(A=>A.color==="black"),x=g.filter(A=>A.result==="win").length,v=f.filter(A=>A.result==="win").length,h=e.reduce((A,O)=>A+O.moves,0)/a,S={};e.forEach(A=>{A.timeClass&&(S[A.timeClass]=(S[A.timeClass]||0)+1)});const C=Object.entries(S).sort((A,O)=>O[1]-A[1])[0]?.[0]||"blitz",R=e.filter(A=>A.timeClass===C).reverse().map((A,O)=>({game:O+1,rating:A.color==="white"?A.wRating:A.bRating,result:A.result})),b={},w={};e.filter(A=>A.result==="win").forEach(A=>{b[A.method]=(b[A.method]||0)+1}),e.filter(A=>A.result==="loss").forEach(A=>{w[A.method]=(w[A.method]||0)+1});const D={};e.forEach(A=>{D[A.date]=(D[A.date]||0)+1});const N=Object.values(D),T=N.length>0?Math.max(...N):0,E=Object.entries(D).filter(([,A])=>A>=8).length;let L=0,_=0,I=0,P=null;e.forEach(A=>{A.result===P?I++:(I=1,P=A.result),A.result==="win"&&(L=Math.max(L,I)),A.result==="loss"&&(_=Math.max(_,I))});let z=0,B=0;for(let A=1;A<e.length;A++)e[A-1].result==="loss"&&(B++,e[A].result==="win"&&z++);const W=computeHeuristicRadar(e,n),G=Math.round(W.reduce((A,O)=>A+O.value,0)/W.length);let $="Balanced Player";return h<25?$="Aggressive Attacker":e.filter(A=>A.moves>=50).length>a*.3?$="Endgame Grinder":k>80?$="Precision Player":m>i*.4&&($="Time Scrambler"),{total:a,wins:s,losses:i,draws:p,winRate:Math.round(s/a*100),timeoutLosses:m,timeoutWins:l,timeTrouble:r,severeTimeTrouble:c,avgAccuracy:Math.round(k*10)/10,openings:o,asWhite:g.length,asBlack:f.length,whiteWinRate:Math.round(x/Math.max(1,g.length)*100),blackWinRate:Math.round(v/Math.max(1,f.length)*100),avgMoves:Math.round(h),ratingTrend:R,primaryTimeClass:C,winMethods:b,lossMethods:w,longestSession:T,marathonDays:E,longestWinStreak:L,longestLossStreak:_,afterLossWinRate:B>0?Math.round(z/B*100):0,radar:W,lumiScore:G,personality:$,rapidBlitzGap:n.rapid.current-n.blitz.current,analyzedGames:[],isHeuristic:!0}}function buildAnalysisFromEngine(e,t,n){const a=analyzeGamesHeuristic(t,n),s=e.filter(h=>h!==null);if(s.length===0)return a;const i=s.reduce((h,S)=>h+S.playerAccuracy,0)/s.length,p={};s.forEach(h=>{Object.entries(h.classifications||{}).forEach(([S,C])=>{p[S]=(p[S]||0)+C})});const m=computeRadarFromAnalysis(e,t,n),l=Math.round(m.reduce((h,S)=>h+S.value,0)/m.length);let r="Balanced Player";const c=p.blunder||0,y=s.reduce((h,S)=>h+S.moveAnalysis.filter(C=>C.isPlayerMove).length,0),k=c/Math.max(1,y);i>85?r="Precision Player":k>.08?r="Tactical Risk-Taker":a.timeoutLosses>a.losses*.4?r="Time Scrambler":a.avgMoves<25&&(r="Aggressive Attacker");let d=null,u=[],o=null,g=l;try{const h=window.LumiProfile?.SkillProfile,S=window.LumiProfile?.Recommendations,C=window.LumiProfile?.CoachingInsights;if(h&&S){const M=s.map((R,b)=>convertToCoachingRecord(R,t[b])).filter(Boolean);if(M.length>0){const R=n?.blitz?.current||n?.rapid?.current||n?.bullet?.current||1200;if(d=h.compute(M,R),u=S.generate(d,R),C)try{o=C.generate(M,d,R)}catch(w){console.warn("CoachingInsights.generate failed:",w.message)}const b=Object.values(d.dimensions).filter(w=>w.score!=null);b.length>0&&(g=Math.round(b.reduce((w,D)=>w+D.score,0)/b.length))}}}catch(h){console.warn("6D coaching computation failed, using 8D fallback:",h.message)}const f=s.filter(h=>!h.isQuickMode&&h.wasLosing),x=f.filter(h=>{const S=h.headers?.Result;return h.playerColor==="w"&&S==="1-0"||h.playerColor==="b"&&S==="0-1"||S==="1/2-1/2"}),v=f.length>0?{total:f.length,saved:x.length,rate:Math.round(x.length/f.length*100)}:null;return{...a,avgAccuracy:Math.round(i*10)/10,radar:m,lumiScore:g,personality:r,totalClassifications:p,analyzedGames:s,isHeuristic:!1,skillProfile:d,recommendations:u,insights:o,resourcefulness:v}}function convertToCoachingRecord(e,t){if(!e||e.isQuickMode)return null;const n=e.moveAnalysis.filter(G=>G.isPlayerMove),a=n.length;if(a===0)return null;let s=0,i=null;const p=window.LumiProfile?.OpeningBook;if(p&&p.loaded&&e.pgn)try{const G=replayGame(e.pgn);if(G){const $=p.getDeviation(G.positions);if(s=$.inBookMoves,$.deviationIndex>0&&$.deviationIndex<e.moveAnalysis.length){const A=e.moveAnalysis[$.deviationIndex];A&&(i=e.playerColor==="w"?A.whiteEval:-A.whiteEval,i=i/100)}}}catch{}if(s===0)for(const G of n)if(G.classification==="book"||G.classification==="best"||G.classification==="excellent")s++;else break;const m=Math.ceil(s/2),l=n.slice(m,m+6),r=l.length>0?l.reduce((G,$)=>G+$.accuracy,0)/l.length:50;let c=!1,y=!1,k=15;const d=e.pgn?replayGame(e.pgn):null,u=e.moveAnalysis;for(let G=0;G<u.length;G++){const $=u[G],A=$.moveNumber||Math.floor(G/2)+1;if(A>15)break;if($.san&&($.san==="O-O"||$.san==="O-O-O")&&(c=!0),!y&&d&&d.positions&&d.positions[G+1]){const O=d.positions[G+1].split(" ")[0];!O.includes("Q")&&!O.includes("q")&&(y=!0)}if(c&&y){k=A;break}}const o=n.filter(G=>(G.moveNumber||1)<=k),g=o.length>0?o.reduce((G,$)=>G+($.accuracy||0),0)/o.length:50,f=["mistake","blunder"],x=["brilliant","best","excellent","good"];let v=0,h=0;const S=e.moveAnalysis.filter(G=>!G.isPlayerMove);for(const G of S)if(f.includes(G.classification)){v++;const $=n.find(A=>A.moveNumber>=G.moveNumber&&(G.turn==="w"?A.turn==="b":A.turn==="w"));$&&x.includes($.classification)&&h++}const C=e.moveAnalysis.map(G=>{const $=G.whiteEval;return e.playerColor==="w"?$:-$}),M=C.length>0?Math.max(...C):0,R=C.length>0?Math.min(...C):0,b=M>=150,w=R<=-150,D=e.headers?.Result,N=e.playerColor==="w"&&D==="1-0"||e.playerColor==="b"&&D==="0-1",T=D==="1/2-1/2",E=b&&N,L=w&&(N||T),_=n.filter(G=>G.gamePhase==="endgame"),I=_.length>0?_.reduce((G,$)=>G+($.accuracy||0),0)/_.length:50,P=n.filter(G=>G.clock!==null&&G.clock<30).length,z=b?1:0,B=b&&(N||T)?1:0,W=b&&!N&&!T?1:0;return{book_depth:s,post_book_accuracy:r,opening_accuracy:g,exit_eval:i,tactical_found:h,tactical_moments:Math.max(1,v),endgame_positions:_.length,had_advantage:b?1:0,converted:E?1:0,was_losing:w?1:0,saved:L?1:0,winning_positions:z,advantage_held:B,advantage_lost:W,eg_accuracy:I,overall_accuracy:e.playerAccuracy,time_trouble_moves:P,total_moves:a}}function computeCorrelations(e,t){const n=e.filter(o=>o!==null&&!(o.isQuickMode&&o.playerAccuracy===0));if(n.length<5)return[];const a=[],s={morning:[],afternoon:[],evening:[],night:[]};n.forEach((o,g)=>{const f=t[g];if(!f?.date)return;const x=f.date,v=f.hour??new Date(x).getHours(),h=o.playerAccuracy;v>=6&&v<12?s.morning.push(h):v>=12&&v<17?s.afternoon.push(h):v>=17&&v<22?s.evening.push(h):s.night.push(h)});const i=Object.entries(s).filter(([,o])=>o.length>=3);if(i.length>=2){const o=i.map(([x,v])=>({name:x,avg:v.reduce((h,S)=>h+S,0)/v.length,count:v.length}));o.sort((x,v)=>v.avg-x.avg);const g=o[0],f=o[o.length-1];g.avg-f.avg>5&&a.push({type:"time_of_day",title:"Best Time to Play",description:`You play best in the ${g.name} (${Math.round(g.avg)}% accuracy) vs ${f.name} (${Math.round(f.avg)}%).`,magnitude:Math.round(g.avg-f.avg),color:"#6B9FD4"})}const p={"much weaker":[],weaker:[],equal:[],stronger:[],"much stronger":[]};n.forEach((o,g)=>{const f=t[g],x=f.color==="white"?f.wRating:f.bRating,h=(f.color==="white"?f.bRating:f.wRating)-x,S=o.playerAccuracy;h<-150?p["much weaker"].push(S):h<-50?p.weaker.push(S):h<=50?p.equal.push(S):h<=150?p.stronger.push(S):p["much stronger"].push(S)});const m=Object.entries(p).filter(([,o])=>o.length>=3);if(m.length>=2){const o=m.map(([x,v])=>({name:x,avg:v.reduce((h,S)=>h+S,0)/v.length,count:v.length})),g=o.find(x=>x.name==="equal"),f=o.find(x=>x.name==="stronger"||x.name==="much stronger");g&&f&&g.avg-f.avg>5&&a.push({type:"opponent_strength",title:"Performance vs Stronger Opponents",description:`Your accuracy drops ${Math.round(g.avg-f.avg)}% against stronger opponents (${Math.round(f.avg)}% vs ${Math.round(g.avg)}%).`,magnitude:Math.round(g.avg-f.avg),color:"#D4A44B"})}const l={"short (<20)":[],"medium (20-40)":[],"long (40+)":[]};n.forEach((o,g)=>{const f=t[g],x=o.playerAccuracy;f.moves<20?l["short (<20)"].push(x):f.moves<=40?l["medium (20-40)"].push(x):l["long (40+)"].push(x)});const r=Object.entries(l).filter(([,o])=>o.length>=3);if(r.length>=2){const o=r.map(([x,v])=>({name:x,avg:v.reduce((h,S)=>h+S,0)/v.length,count:v.length}));o.sort((x,v)=>v.avg-x.avg);const g=o[0],f=o[o.length-1];g.avg-f.avg>5&&a.push({type:"game_length",title:"Game Length Impact",description:`You perform best in ${g.name} games (${Math.round(g.avg)}%) and worst in ${f.name} games (${Math.round(f.avg)}%).`,magnitude:Math.round(g.avg-f.avg),color:"#9B8ABF"})}const c=t.filter(o=>o.result==="loss"),y=c.filter(o=>o.method==="timeout");c.length>=3&&y.length/c.length>.3&&a.push({type:"timeout",title:"Time Trouble Alert",description:`${Math.round(y.length/c.length*100)}% of your losses are from timeout (${y.length}/${c.length}). Consider longer time controls or faster play.`,magnitude:Math.round(y.length/c.length*100),color:"#CF6E6E"});const k={},d=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];t.forEach((o,g)=>{if(!o?.date)return;const f=new Date(o.date).getDay();k[f]||(k[f]={wins:0,total:0}),k[f].total++,o.result==="win"&&k[f].wins++});const u=Object.entries(k).filter(([,o])=>o.total>=3);if(u.length>=3){const o=u.map(([x,v])=>({name:d[x],rate:v.wins/v.total*100,count:v.total}));o.sort((x,v)=>v.rate-x.rate);const g=o[0],f=o[o.length-1];g.rate-f.rate>15&&a.push({type:"day_of_week",title:"Lucky Day",description:`You win ${Math.round(g.rate)}% on ${g.name}s but only ${Math.round(f.rate)}% on ${f.name}s.`,magnitude:Math.round(g.rate-f.rate),color:"#5DB67D"})}return a.sort((o,g)=>g.magnitude-o.magnitude)}function detectPatterns(e,t){const n=e.filter(g=>g!==null&&!(g.isQuickMode&&g.playerAccuracy===0));if(n.length<3)return[];const a=[],s={};n.forEach((g,f)=>{const h=(t[f]?.opening||"Unknown").split(/[,:]/)[0].trim().split(/\s+/).slice(0,3).join(" ");s[h]||(s[h]=[]),s[h].push(g.playerAccuracy)}),Object.entries(s).forEach(([g,f])=>{if(f.length>=3){const x=f.reduce((v,h)=>v+h,0)/f.length;x<70&&a.push({type:"opening_weakness",severity:x<60?"critical":"warning",title:`Weak in ${g}`,detail:`Avg accuracy of ${Math.round(x)}% across ${f.length} games. Consider studying this opening or switching.`})}});const i={opening:[],middlegame:[],endgame:[]};n.forEach(g=>{i.opening.push(g.openingCpl),i.middlegame.push(g.middlegameCpl),i.endgame.push(g.endgameCpl)});const p=Object.entries(i).map(([g,f])=>({name:g,avg:f.reduce((x,v)=>x+v,0)/f.length})),m=p.reduce((g,f)=>g+f.avg,0)/3;p.forEach(g=>{g.avg>m+10&&g.avg>30&&a.push({type:"phase_weakness",severity:g.avg>m+20?"critical":"warning",title:`Weak ${g.name}`,detail:`Your ${g.name} CPL (${Math.round(g.avg)}) is significantly higher than your average (${Math.round(m)}).`})});const l=t.filter(g=>g.finalClock!==null&&g.finalClock<15);t.length>=5&&l.length/t.length>.4&&a.push({type:"time_trouble",severity:l.length/t.length>.6?"critical":"warning",title:"Chronic Time Trouble",detail:`${Math.round(l.length/t.length*100)}% of games end with less than 15 seconds. This is severely impacting your results.`});const r=n.flatMap(g=>g.moveAnalysis.filter(f=>f.isPlayerMove)),c={"1-10":{blunders:0,total:0},"11-20":{blunders:0,total:0},"21-30":{blunders:0,total:0},"31+":{blunders:0,total:0}};r.forEach(g=>{const f=g.moveNumber<=10?"1-10":g.moveNumber<=20?"11-20":g.moveNumber<=30?"21-30":"31+";c[f].total++,g.classification==="blunder"&&c[f].blunders++});const y=Object.entries(c).filter(([,g])=>g.total>=10);if(y.length>=2){const g=y.map(([f,x])=>({range:f,rate:x.blunders/x.total}));g.sort((f,x)=>x.rate-f.rate),g[0].rate>.05&&g[0].rate>g[g.length-1].rate*2&&a.push({type:"blunder_cluster",severity:"info",title:`Blunders Cluster in Moves ${g[0].range}`,detail:`${Math.round(g[0].rate*100)}% blunder rate in moves ${g[0].range} \u2014 focus extra attention on this phase.`})}let k=0,d=0;t.forEach(g=>{g.result==="loss"?(d++,k=Math.max(k,d)):d=0}),k>=4&&a.push({type:"tilt",severity:k>=6?"critical":"warning",title:`${k}-Game Loss Streak Detected`,detail:`A ${k}-game loss streak suggests tilt. Consider stopping after 3 consecutive losses.`});const u={};n.forEach((g,f)=>{const x=t[f]?.date||"";u[x]||(u[x]=[]),u[x].push(g.playerAccuracy)});let o=0;return Object.values(u).forEach(g=>{if(g.length>=4){const f=g.slice(0,Math.floor(g.length/2)),x=g.slice(Math.floor(g.length/2)),v=f.reduce((S,C)=>S+C,0)/f.length,h=x.reduce((S,C)=>S+C,0)/x.length;v-h>8&&o++}}),o>0&&a.push({type:"session_fatigue",severity:"warning",title:"Session Fatigue Detected",detail:`On ${o} day(s), your accuracy dropped significantly after multiple games. Limit sessions to 5-6 games.`}),a.sort((g,f)=>(g.severity==="critical"?0:g.severity==="warning"?1:2)-(f.severity==="critical"?0:f.severity==="warning"?1:2))}function pieceFromSan(e){if(!e||e==="--")return null;if(e.startsWith("O-O"))return"K";const t=e[0];return"NBRQK".includes(t)?t:"P"}const PIECE_NAMES={P:"Pawn",N:"Knight",B:"Bishop",R:"Rook",Q:"Queen",K:"King"},PIECE_ORDER=["P","N","B","R","Q","K"],PIECE_COLORS={P:"#A09B96",N:"#9B8ABF",B:"#D4A44B",R:"#CF6E6E",Q:"#C48AAF",K:"#D4A44B"};function computeAccuracyByResult(e){const t={win:[],draw:[],loss:[]};return e.forEach(n=>{if(!n)return;const a=n.headers?.Result,s=n.playerColor;let i;a==="1/2-1/2"?i="draw":s==="w"&&a==="1-0"||s==="b"&&a==="0-1"?i="win":(a==="1-0"||a==="0-1")&&(i="loss"),i&&n.playerAccuracy!=null&&t[i].push(n.playerAccuracy)}),Object.fromEntries(Object.entries(t).map(([n,a])=>[n,{count:a.length,avg:a.length>0?Math.round(a.reduce((s,i)=>s+i,0)/a.length*10)/10:null}]))}function computeAccuracyByMoveNumber(e){const t={};e.forEach(s=>{!s||s.isQuickMode||s.moveAnalysis.filter(i=>i.isPlayerMove&&i.accuracy!==null).forEach(i=>{t[i.moveNumber]||(t[i.moveNumber]=[]),t[i.moveNumber].push(i.accuracy)})});const n=Math.min(60,Math.max(...Object.keys(t).map(Number),1)),a=[];for(let s=1;s<=n;s++){const i=t[s]||[];i.length>=2&&a.push({move:s,accuracy:Math.round(i.reduce((p,m)=>p+m,0)/i.length*10)/10,games:i.length})}return a}function computePieceAccuracy(e){const t={};return PIECE_ORDER.forEach(n=>{t[n]={totalAcc:0,count:0}}),e.forEach(n=>{!n||n.isQuickMode||n.moveAnalysis.filter(a=>a.isPlayerMove&&a.accuracy!==null).forEach(a=>{const s=pieceFromSan(a.san);s&&t[s]&&(t[s].totalAcc+=a.accuracy,t[s].count++)})}),PIECE_ORDER.map(n=>({piece:n,name:PIECE_NAMES[n],accuracy:t[n].count>0?Math.round(t[n].totalAcc/t[n].count*10)/10:0,moves:t[n].count,color:PIECE_COLORS[n]})).filter(n=>n.moves>0)}function computeGamePhaseStats(e){const t={opening:{games:0,wins:0,losses:0},middlegame:{games:0,wins:0,losses:0},endgame:{games:0,wins:0,losses:0}},n={opening:[],middlegame:[],endgame:[]};return e.forEach(a=>{if(!a)return;const s=a.totalMoves||a.moveAnalysis?.length||40,i=s<=20?"opening":s<=40?"middlegame":"endgame";t[i].games++;const p=a.headers?.Result,m=a.playerColor;m==="w"&&p==="1-0"||m==="b"&&p==="0-1"?t[i].wins++:(p==="1-0"||p==="0-1")&&p!=="1/2-1/2"&&t[i].losses++,a.isQuickMode?n[i].push(a.playerAccuracy):(a.openingCpl!==void 0&&n.opening.push(Math.max(0,100-a.openingCpl*1.2)),a.middlegameCpl!==void 0&&n.middlegame.push(Math.max(0,100-a.middlegameCpl*.8)),a.endgameCpl!==void 0&&n.endgame.push(Math.max(0,100-a.endgameCpl*1)))}),Object.fromEntries(Object.entries(t).map(([a,s])=>{const i=n[a];return[a,{...s,draws:s.games-s.wins-s.losses,winRate:s.games>0?Math.round(s.wins/s.games*100):0,accuracy:i.length>0?Math.round(i.reduce((p,m)=>p+m,0)/i.length*10)/10:0}]}))}function computeCastlingStats(e){let t=0,n=0,a=0;const s={kingside:{win:0,loss:0,draw:0},queenside:{win:0,loss:0,draw:0},none:{win:0,loss:0,draw:0}},i=[],p=r=>{const c=r.headers?.Result,y=r.playerColor;return c==="1/2-1/2"?"draw":y==="w"&&c==="1-0"||y==="b"&&c==="0-1"?"win":c==="1-0"||c==="0-1"?"loss":null};e.forEach(r=>{if(!r)return;const y=r.moveAnalysis.filter(d=>d.isPlayerMove).find(d=>d.san&&d.san.startsWith("O-O")),k=p(r);k&&(y?(y.san==="O-O-O"?(n++,s.queenside[k]++):(t++,s.kingside[k]++),i.push(y.moveNumber)):(a++,s.none[k]++))});const m=t+n+a,l=i.length>0?Math.round(i.reduce((r,c)=>r+c,0)/i.length*10)/10:0;return{kingSide:t,queenSide:n,noCastle:a,total:m,avgCastleMove:l,castleResults:s,castledPct:m>0?Math.round((t+n)/m*100):0}}function computeOpeningDeepDive(e){const t={};return e.forEach(n=>{if(!n)return;const a=openingNameFromHeaders(n.headers||{}),s=n.headers?.Result,i=n.playerColor,p=i==="w"&&s==="1-0"||i==="b"&&s==="0-1",m=s==="1/2-1/2",l=(s==="1-0"||s==="0-1")&&!p;if(!(!p&&!m&&!l)&&(t[a]||(t[a]={wins:0,losses:0,draws:0,accuracies:[],bookDepths:[],color:i}),p?t[a].wins++:l?t[a].losses++:t[a].draws++,n.playerAccuracy!=null&&t[a].accuracies.push(n.playerAccuracy),!n.isQuickMode)){const r=n.moveAnalysis.filter(y=>y.isPlayerMove);let c=0;for(const y of r)if(y.classification==="book"||y.classification==="best"||y.classification==="excellent")c++;else break;t[a].bookDepths.push(c)}}),Object.entries(t).map(([n,a])=>{const s=a.wins+a.losses+a.draws;return{name:n,total:s,wins:a.wins,losses:a.losses,draws:a.draws,winRate:s>0?Math.round(a.wins/s*100):0,avgAccuracy:a.accuracies.length>0?Math.round(a.accuracies.reduce((i,p)=>i+p,0)/a.accuracies.length*10)/10:null,avgBookDepth:a.bookDepths.length>0?Math.round(a.bookDepths.reduce((i,p)=>i+p,0)/a.bookDepths.length*10)/10:null}}).sort((n,a)=>a.total-n.total)}async function fetchChessComGames(e,t=40,n="all"){let a=[];try{const i=await fetch(`https://api.chess.com/pub/player/${e}/games/archives`,{headers:{Accept:"application/json"}});if(i.ok){const p=await i.json();p.archives&&p.archives.length>0&&(a=[...p.archives].reverse())}}catch(i){console.warn("Failed to fetch archives list:",i.message)}if(a.length===0){const i=new Date;for(let p=0;p<6;p++){const m=new Date(i.getFullYear(),i.getMonth()-p,1);a.push(`https://api.chess.com/pub/player/${e}/games/${m.getFullYear()}/${String(m.getMonth()+1).padStart(2,"0")}`)}}const s=[];for(const i of a){try{const p=await fetch(i,{headers:{Accept:"application/json"}});if(!p.ok)continue;const m=await p.json();if(m.games){const l=m.games.filter(r=>(n==="all"||r.time_class===n)&&r.pgn);s.push(...l)}}catch(p){console.warn(`Failed to fetch ${i}:`,p.message)}if(s.length>=t)break}return s.sort((i,p)=>(p.end_time||0)-(i.end_time||0)),s.slice(0,t)}function apiGameToMetadata(e,t){const n=e.white?.username?.toLowerCase()===t.toLowerCase(),a=n?e.white:e.black,s=n?e.black:e.white,i=a.result==="win"?"win":a.result==="agreed"||a.result==="repetition"||a.result==="stalemate"||a.result==="insufficient"||a.result==="50move"?"draw":"loss",p=a.result==="win"?s.result||"resigned":a.result==="checkmated"?"checkmate":a.result||"unknown",m=parsePGNHeaders(e.pgn||""),r=((e.pgn||"").replace(/\[[^\]]*\]/g,"").replace(/\{[^}]*\}/g,"").match(/\b\d+\./g)||[]).length;return{date:m.Date?m.Date.replace(/\./g,"-"):new Date((e.end_time||0)*1e3).toISOString().slice(0,10),white:m.White||e.white?.username||"?",black:m.Black||e.black?.username||"?",wRating:e.white?.rating||parseInt(m.WhiteElo)||1400,bRating:e.black?.rating||parseInt(m.BlackElo)||1400,result:i,method:p,eco:m.ECO||"?",opening:openingNameFromHeaders(m),moves:r,accuracy:e.accuracies?n?e.accuracies.white:e.accuracies.black:null,timeControl:e.time_control||m.TimeControl||"?",timeClass:e.time_class||"blitz",color:n?"white":"black",finalClock:(()=>{const c=extractClockTimes(e.pgn||"");if(c.length===0)return null;const y=c.filter((k,d)=>n?d%2===0:d%2===1);return y.length>0?y[y.length-1]:null})(),pgn:e.pgn||null}}async function fetchLichessProfile(e){const t=await fetch(`https://lichess.org/api/user/${encodeURIComponent(e)}`,{headers:{Accept:"application/json"}});if(!t.ok)throw t.status===404?new Error(`User "${e}" not found on Lichess.`):new Error(`Lichess API returned ${t.status}.`);const n=await t.json();return{profile:{username:n.username||e,country:n.profile?.country||"",status:n.patron?"patron":"basic",joined:Math.floor((n.createdAt||0)/1e3),lastOnline:Math.floor((n.seenAt||0)/1e3),followers:n.nbFollowers||0,league:"",title:n.title||"",platform:"lichess"},stats:{rapid:{current:n.perfs?.rapid?.rating||0,best:n.perfs?.rapid?.rating||0,wins:n.perfs?.rapid?.games||0,losses:0,draws:0},blitz:{current:n.perfs?.blitz?.rating||0,best:n.perfs?.blitz?.rating||0,wins:n.perfs?.blitz?.games||0,losses:0,draws:0},bullet:{current:n.perfs?.bullet?.rating||0,best:n.perfs?.bullet?.rating||0,wins:n.perfs?.bullet?.games||0,losses:0,draws:0},daily:{current:n.perfs?.correspondence?.rating||0,best:n.perfs?.correspondence?.rating||0,wins:0,losses:0,draws:0},tactics:{highest:n.perfs?.puzzle?.rating||0},puzzleRush:{best:0}}}}async function fetchLichessGames(e,t=40,n="all",a){const s=new URLSearchParams({evals:"true",clocks:"true",opening:"true",pgnInJson:"true",rated:"true",max:String(t)});if(n!=="all"){const y={rapid:"rapid",blitz:"blitz",bullet:"bullet",daily:"correspondence"};y[n]&&s.set("perfType",y[n])}const i=`https://lichess.org/api/games/user/${encodeURIComponent(e)}?${s}`,p=await fetch(i,{headers:{Accept:"application/x-ndjson"}});if(!p.ok)throw new Error(`Could not load Lichess games (${p.status})`);const m=p.body.getReader(),l=new TextDecoder,r=[];let c="";for(;;){const{done:y,value:k}=await m.read();if(y)break;c+=l.decode(k,{stream:!0});const d=c.split(`
`);c=d.pop();for(const u of d)if(u.trim())try{const o=JSON.parse(u);if(o.variant&&o.variant!=="standard"||o.status==="aborted")continue;r.push(o),a?.(r.length)}catch{}if(r.length>=t)break}if(c.trim()&&r.length<t)try{const y=JSON.parse(c);(!y.variant||y.variant==="standard")&&y.status!=="aborted"&&r.push(y)}catch{}return r.slice(0,t)}function lichessGameToMetadata(e,t){if(!e.players?.white||!e.players?.black)return null;const n=(e.players.white.user?.name||e.players.white.user?.id||"").toLowerCase()===t.toLowerCase(),a=n?e.players.white:e.players.black,s=n?e.players.black:e.players.white;let i;e.winner?e.winner==="white"===n?i="win":i="loss":i="draw";const p={mate:"checkmate",resign:"resigned",timeout:"timeout",outoftime:"timeout",stalemate:"stalemate",draw:"agreement"},m=p[e.status]||e.status;let l="";if(e.clock){const u=Math.floor(e.clock.initial/60),o=e.clock.increment||0;l=`${u*60}+${o}`}const r={ultraBullet:"bullet",bullet:"bullet",blitz:"blitz",rapid:"rapid",classical:"rapid",correspondence:"daily"},c=e.moves?e.moves.split(" ").length:0,y=Math.ceil(c/2);let k=null;if(e.clocks&&e.clocks.length>0){const u=e.clocks.filter((o,g)=>n?g%2===0:g%2===1);u.length>0&&(k=u[u.length-1]/100)}return{date:e.createdAt?new Date(e.createdAt).toISOString().slice(0,10):"",white:e.players.white.user?.name||e.players.white.user?.id||"Anonymous",black:e.players.black.user?.name||e.players.black.user?.id||"Anonymous",wRating:e.players.white.rating||1500,bRating:e.players.black.rating||1500,result:i,method:m,eco:e.opening?.eco||"?",opening:e.opening?.name||"Unknown",moves:y,accuracy:null,timeControl:l,timeClass:r[e.speed]||"blitz",color:n?"white":"black",finalClock:k,pgn:e.pgn||null,lichessId:e.id,hasServerEvals:!!(e.analysis&&e.analysis.length>0),serverAnalysis:e.analysis||null}}function analyzeGameFromLichessEvals(e,t,n){const a=e.analysis;if(!a||a.length===0)return null;const s=(e.moves||"").split(" ").filter(Boolean);if(s.length===0)return null;const i=t.color==="white"?"w":"b",p=t.pgn?replayGame(t.pgn):null,m=p?p.positions:null,l=[];for(let h=0;h<s.length&&h<a.length;h++){const S=a[h],C=h%2===0?"w":"b";let M;S.eval!==void 0?M=S.eval:S.mate!==void 0?M=S.mate>0?1e4-Math.abs(S.mate)*10:-1e4+Math.abs(S.mate)*10:M=0;const R=M,b=C==="w"?-M:M,w=h>0?a[h-1].eval!==void 0?a[h-1].eval:a[h-1].mate!==void 0?a[h-1].mate>0?9990:-9990:0:0,D=cpToWinPct(C==="w"?w:-w),N=cpToWinPct(C==="w"?M:-M),T=Math.max(0,D-N),E=moveAccuracy(T),L=Math.round(Math.max(0,w-M)*(C==="w"?1:-1)),_=classifyMoveByWinDrop(T);let I=E;_==="book"||_==="brilliant"||_==="best"?I=100:_==="excellent"?I=Math.max(I,98):_==="good"&&(I=Math.max(I,95));const P=m?m[h+1]:null;l.push({moveNumber:Math.floor(h/2)+1,san:s[h],turn:C,cpl:L,classification:_,gamePhase:getFenPhase(P,h),evalBefore:h>0?C==="w"?w:-w:0,evalAfter:b,whiteEval:R,bestMove:S.best||null,clock:t.finalClock,isPlayerMove:C===i,accuracy:I})}const r=l.filter(h=>h.isPlayerMove),c=l.filter(h=>!h.isPlayerMove),y=r.length>0?r.reduce((h,S)=>h+S.accuracy,0)/r.length:0,k=c.length>0?c.reduce((h,S)=>h+S.accuracy,0)/c.length:0,d={};for(const h of r)d[h.classification]=(d[h.classification]||0)+1;const u=r.filter(h=>h.gamePhase==="opening"),o=r.filter(h=>h.gamePhase==="middlegame"),g=r.filter(h=>h.gamePhase==="endgame"),f=h=>h.length>0?h.reduce((S,C)=>S+C.cpl,0)/h.length:0,x=l.map(h=>h.whiteEval),v=x.map(h=>i==="w"?h:-h);return{pgn:e.pgn||"",headers:{White:t.white,Black:t.black,Date:t.date,Result:t.result==="win"?i==="w"?"1-0":"0-1":t.result==="loss"?i==="w"?"0-1":"1-0":"1/2-1/2",TimeControl:t.timeControl},playerColor:i,totalMoves:s.length,moveAnalysis:l,playerAccuracy:Math.round(y*10)/10,opponentAccuracy:Math.round(k*10)/10,playerAvgCpl:Math.round(f(r)*10)/10,classifications:d,openingCpl:Math.round(f(u)*10)/10,middlegameCpl:Math.round(f(o)*10)/10,endgameCpl:Math.round(f(g)*10)/10,wasWinning:v.some(h=>h>=150),wasLosing:v.some(h=>h<=-150),maxAdvantage:Math.round(Math.max(0,...v)),evalGraph:x,clocks:[]}}const MOCK_PROFILE={username:"sriramchess007",country:"IN",status:"premium",joined:1605356573,lastOnline:1773048691,followers:17,league:"Champion"},MOCK_STATS={rapid:{current:1744,best:1821,wins:610,losses:523,draws:44},blitz:{current:1423,best:1478,wins:1279,losses:1240,draws:112},bullet:{current:774,best:1203,wins:950,losses:966,draws:20},daily:{current:1272,best:1392,wins:11,losses:22,draws:1},tactics:{highest:1825},puzzleRush:{best:52}},MOCK_GAMES=[{date:"2026-03-07",white:"SinopleLeVert",black:"sriramchess007",wRating:1424,bRating:1423,result:"loss",method:"resigned",eco:"C45",opening:"Scotch Game",moves:35,accuracy:67.6,timeControl:"180+2",timeClass:"blitz",color:"black",finalClock:15.7},{date:"2026-03-07",white:"sriramchess007",black:"jspicer",wRating:1431,bRating:1505,result:"loss",method:"timeout",eco:"A15",opening:"English Opening",moves:18,accuracy:null,timeControl:"180+2",timeClass:"blitz",color:"white",finalClock:8.4},{date:"2026-03-07",white:"georgizahariev",black:"sriramchess007",wRating:1478,bRating:1438,result:"loss",method:"timeout",eco:"B27",opening:"Sicilian Defense",moves:26,accuracy:81.9,timeControl:"180+2",timeClass:"blitz",color:"black",finalClock:2.4},{date:"2026-03-03",white:"sriramchess007",black:"GuilleCHF",wRating:1445,bRating:1547,result:"loss",method:"timeout",eco:"E20",opening:"Nimzo-Indian",moves:36,accuracy:79.4,timeControl:"180+2",timeClass:"blitz",color:"white",finalClock:5.3},{date:"2026-03-02",white:"sriramchess007",black:"BALDZ2034",wRating:1451,bRating:1423,result:"win",method:"abandoned",eco:"A40",opening:"Englund Gambit",moves:24,accuracy:78.1,timeControl:"180+2",timeClass:"blitz",color:"white",finalClock:38.4},{date:"2026-02-14",white:"Bunnaye",black:"sriramchess007",wRating:1448,bRating:1443,result:"win",method:"timeout",eco:"B30",opening:"Sicilian Rossolimo",moves:24,accuracy:89.7,timeControl:"180+2",timeClass:"blitz",color:"black",finalClock:42},{date:"2026-02-14",white:"sriramchess007",black:"Ali_xso",wRating:1435,bRating:1402,result:"win",method:"resigned",eco:"C50",opening:"Giuoco Piano",moves:23,accuracy:82.6,timeControl:"180+2",timeClass:"blitz",color:"white",finalClock:120},{date:"2026-02-13",white:"sriramchess007",black:"Mh19_8",wRating:1427,bRating:1432,result:"win",method:"resigned",eco:"E90",opening:"King's Indian",moves:51,accuracy:null,timeControl:"180+2",timeClass:"blitz",color:"white",finalClock:30},{date:"2026-02-12",white:"sriramchess007",black:"Joaquin13",wRating:1419,bRating:1425,result:"draw",method:"agreement",eco:"A60",opening:"Benoni Defense",moves:17,accuracy:80.2,timeControl:"180+2",timeClass:"blitz",color:"white",finalClock:140},{date:"2026-02-10",white:"OwenLeflar",black:"sriramchess007",wRating:1433,bRating:1419,result:"loss",method:"resigned",eco:"D53",opening:"Queen's Gambit Declined",moves:50,accuracy:null,timeControl:"180+2",timeClass:"blitz",color:"black",finalClock:11.1},{date:"2026-02-06",white:"vaux76",black:"sriramchess007",wRating:1430,bRating:1427,result:"loss",method:"resigned",eco:"A57",opening:"Benko Gambit",moves:56,accuracy:null,timeControl:"180+2",timeClass:"blitz",color:"black",finalClock:26.8},{date:"2026-02-05",white:"isHomerSpringField",black:"sriramchess007",wRating:1418,bRating:1435,result:"win",method:"checkmate",eco:"B32",opening:"Sicilian Defense",moves:64,accuracy:79.2,timeControl:"180+2",timeClass:"blitz",color:"black",finalClock:50.8},{date:"2026-02-04",white:"TheHypnoToad",black:"sriramchess007",wRating:1479,bRating:1441,result:"loss",method:"timeout",eco:"A45",opening:"Indian Game",moves:82,accuracy:82.1,timeControl:"180+2",timeClass:"blitz",color:"black",finalClock:3.3},{date:"2026-02-03",white:"sriramchess007",black:"bmhk100",wRating:1448,bRating:1446,result:"win",method:"checkmate",eco:"D20",opening:"Queen's Gambit Accepted",moves:38,accuracy:80.7,timeControl:"180+2",timeClass:"blitz",color:"white",finalClock:45},{date:"2026-02-03",white:"cantxryc",black:"sriramchess007",wRating:1403,bRating:1440,result:"win",method:"checkmate",eco:"C48",opening:"Four Knights",moves:32,accuracy:78.5,timeControl:"180+2",timeClass:"blitz",color:"black",finalClock:10.6},{date:"2026-01-14",white:"sriramchess007",black:"Anon89921",wRating:1440,bRating:1475,result:"win",method:"timeout",eco:"D80",opening:"Grunfeld Defense",moves:39,accuracy:null,timeControl:"180+2",timeClass:"blitz",color:"white",finalClock:10.6},{date:"2026-01-14",white:"sriramchess007",black:"PunkRokh",wRating:1431,bRating:1487,result:"win",method:"checkmate",eco:"C40",opening:"Latvian Gambit",moves:31,accuracy:null,timeControl:"180+2",timeClass:"blitz",color:"white",finalClock:67},{date:"2026-01-14",white:"sriramchess007",black:"GiovoMonroe",wRating:1421,bRating:1389,result:"win",method:"resigned",eco:"C50",opening:"Italian Game",moves:20,accuracy:null,timeControl:"180+2",timeClass:"blitz",color:"white",finalClock:148.3},{date:"2026-01-03",white:"sriramchess007",black:"dosu6990",wRating:1419,bRating:1380,result:"win",method:"resigned",eco:"C58",opening:"Italian Knight Attack",moves:46,accuracy:null,timeControl:"180+2",timeClass:"blitz",color:"white",finalClock:97.3},{date:"2026-01-02",white:"sriramchess007",black:"GM_RichardFeynman",wRating:1420,bRating:1428,result:"win",method:"resigned",eco:"C47",opening:"Four Knights Italian",moves:19,accuracy:null,timeControl:"180+2",timeClass:"blitz",color:"white",finalClock:99}],SKILL_BENCHMARKS={opening:{800:35,1e3:42,1200:50,1400:58,1600:66,1800:73,2e3:78},tactical:{800:20,1e3:30,1200:40,1400:52,1600:62,1800:72,2e3:80},endgame:{800:25,1e3:33,1200:42,1400:52,1600:62,1800:70,2e3:77},consistency:{800:30,1e3:38,1200:48,1400:56,1600:64,1800:72,2e3:78},capitalization:{800:20,1e3:28,1200:38,1400:48,1600:58,1800:66,2e3:74},time_mgmt:{800:40,1e3:48,1200:55,1400:62,1600:68,1800:74,2e3:80}};function _interpolateBenchmark(e,t){const n=SKILL_BENCHMARKS[t];if(!n)return 50;const a=Object.keys(n).map(Number).sort((s,i)=>s-i);if(e<=a[0])return n[a[0]];if(e>=a[a.length-1])return n[a[a.length-1]];for(let s=0;s<a.length-1;s++)if(e>=a[s]&&e<=a[s+1]){const i=(e-a[s])/(a[s+1]-a[s]);return n[a[s]]*(1-i)+n[a[s+1]]*i}return 50}function _makeDimension(e,t,n,a,s=3){if(e===null||a<s)return{score:null,percentile:null,confidence:a<1?"none":"insufficient",rawScore:null};const i=_interpolateBenchmark(t,n),p=e-i,m=Math.max(5,Math.min(95,Math.round(50+45*(2/(1+Math.exp(-p/15))-1)))),l=a>=15?"high":a>=8?"medium":"low";return{score:Math.round(e),percentile:m,confidence:l,rawScore:e}}function _mean(e){return e.length>0?e.reduce((t,n)=>t+n,0)/e.length:0}function _stdDev(e){const t=_mean(e);return Math.sqrt(e.reduce((n,a)=>n+(a-t)**2,0)/Math.max(1,e.length))}function computeInlineSkillProfile(e,t){const n=e.length;if(n===0)return{dimensions:{},gamesAnalyzed:0,confidence:"none",primaryWeakness:null,lastUpdated:new Date().toISOString()};const a=e.filter(b=>b.opening_accuracy!==null).map(b=>b.opening_accuracy),s=_makeDimension(a.length>0?_mean(a):null,t,"opening",a.length),i=e.map(b=>b.tactical_moments>0?b.tactical_found/b.tactical_moments*100:50),p=_makeDimension(_mean(i),t,"tactical",n),m=e.filter(b=>b.endgame_positions>0).map(b=>b.eg_accuracy),l=_makeDimension(m.length>0?_mean(m):null,t,"endgame",m.length),r=e.filter(b=>b.was_losing>0),c=r.filter(b=>b.saved>0).length,y=r.length>0?c/r.length*100:50,k=_makeDimension(y,t,"resourcefulness",r.length),d=e.filter(b=>b.had_advantage>0),u=d.filter(b=>b.converted>0).length,o=d.length>0?u/d.length*100:50,g=_makeDimension(o,t,"capitalization",d.length),f=e.reduce((b,w)=>b+w.time_trouble_moves,0),x=e.reduce((b,w)=>b+w.total_moves,0),v=Math.max(0,Math.min(100,100-f/Math.max(1,x)*200)),h=_makeDimension(v,t,"time_mgmt",n),S={opening:s,tactical:p,endgame:l,resourcefulness:k,capitalization:g,time_mgmt:h},C=Object.entries(S).filter(([,b])=>b.score!==null);C.sort((b,w)=>(b[1].score||50)-(w[1].score||50));const M=C.length>0&&C[0][1].score<45?C[0][0]:null,R=n>=15?"high":n>=8?"medium":n>=3?"low":"none";return{dimensions:S,gamesAnalyzed:n,confidence:R,primaryWeakness:M,lastUpdated:new Date().toISOString()}}const DIMENSION_INFO={opening:{label:"Opening Preparation",color:"#D4A44B",descriptions:{low:"Your opening preparation needs work. Study 1-2 openings deeply rather than playing many superficially.",medium:"Decent opening knowledge. Focus on understanding plans after the opening moves.",high:"Strong opening preparation. You exit the opening with solid positions consistently."},training:{ctaText:"Study Openings",actionUrl:"/learn"}},tactical:{label:"Tactical Awareness",color:"#CF6E6E",descriptions:{low:"You miss many tactical opportunities. Daily puzzle training will help the most.",medium:"You spot some tactics but miss critical ones. Increase puzzle difficulty.",high:"Strong tactical vision. Continue challenging yourself with harder puzzles."},training:{ctaText:"Train Tactics",actionUrl:"/puzzle/training"}},endgame:{label:"Endgame Technique",color:"#6B9FD4",descriptions:{low:"Endgame play is your weakest area. Study basic endgame principles.",medium:"Decent endgame understanding. Work on converting advantages.",high:"Strong endgame technique. You convert advantages reliably."},training:{ctaText:"Study Endgames",actionUrl:"/learn"}},resourcefulness:{label:"Resourcefulness",color:"#9B8ABF",descriptions:{low:"You struggle to fight back from losing positions. Work on defensive technique and counterplay.",medium:"You save some lost games. Improve your ability to create complications when behind.",high:"Excellent fighting spirit. You rarely give up lost positions without a fight."},training:{ctaText:"Practice Defense",actionUrl:"/puzzle/training"}},capitalization:{label:"Advantage Conversion",color:"#5DB67D",descriptions:{low:"You often fail to convert winning positions. Practice winning technique.",medium:"You convert some advantages. Work on simplifying to winning endgames.",high:"Excellent at converting advantages into wins."},training:{ctaText:"Practice Conversion",actionUrl:"/puzzle/training"}},time_mgmt:{label:"Time Management",color:"#D4A44B",descriptions:{low:"Time management is costing you games. Practice with increment.",medium:"Decent time management. Watch for spending too long in the opening.",high:"Excellent time management. You rarely get into time trouble."},training:{ctaText:"Practice Time Control",actionUrl:"/play"}}};function computeInlineRecommendations(e,t){return e?.dimensions?Object.entries(e.dimensions).filter(([,a])=>a.score!==null).map(([a,s])=>{const i=DIMENSION_INFO[a]||{},p=s.score<35?"low":s.score<65?"medium":"high";return{dimension:a,label:i.label||a,color:i.color||"#888",score:s.score,rawScore:s.rawScore,confidence:s.confidence,gap:Math.max(0,50-s.score),isPrimary:a===e.primaryWeakness,level:p,description:i.descriptions?.[p]||"",training:i.training||{}}}).sort((a,s)=>a.score-s.score):[]}const initialState={phase:"ready",username:"",platform:"chesscom",accounts:[],depth:10,format:"rapid",gameCount:40,profile:null,stats:null,games:[],apiGames:[],analyzedGames:[],progress:{gameIndex:0,moveIndex:0,totalGames:0,totalMoves:0,currentGame:""},error:null,isHeuristic:!1,freeTier:!1,signedIn:null,selectedGameIdx:null,cachedGamesCount:0,correlations:null,patterns:null,progressHistory:[],analysisTime:null};function reducer(e,t){switch(t.type){case"SET_USERNAME":return{...e,username:t.value};case"SET_PLATFORM":return{...e,platform:t.value};case"ADD_ACCOUNT":return e.accounts.some(a=>a.platform===t.platform&&a.username.toLowerCase()===t.username.toLowerCase())?e:{...e,accounts:[...e.accounts,{platform:t.platform,username:t.username}],username:""};case"REMOVE_ACCOUNT":return{...e,accounts:e.accounts.filter((n,a)=>a!==t.index)};case"SET_DEPTH":return{...e,depth:t.value};case"SET_FORMAT":return{...e,format:t.value};case"SET_GAME_COUNT":return{...e,gameCount:t.value};case"START_FETCH":return{...e,phase:"fetching",error:null,analyzedGames:[],games:[],profile:null,stats:null,selectedGameIdx:null,cachedGamesCount:0,correlations:null,patterns:null,progressHistory:[],analysisTime:null,_startTime:Date.now()};case"FETCH_SUCCESS":return{...e,phase:"analyzing",profile:t.profile,stats:t.stats,games:t.games,apiGames:t.apiGames,progress:{...e.progress,totalGames:t.games.length}};case"FETCH_FALLBACK":return{...e,phase:"error",profile:t.profile,stats:t.stats,isHeuristic:!0,error:t.error};case"ANALYSIS_PROGRESS":return{...e,progress:{...e.progress,...t.progress}};case"GAME_ANALYZED":return{...e,analyzedGames:[...e.analyzedGames,t.result]};case"CACHE_HIT":return{...e,cachedGamesCount:e.cachedGamesCount+1};case"ANALYSIS_COMPLETE":return{...e,phase:"complete",correlations:t.correlations||null,patterns:t.patterns||null,progressHistory:t.progressHistory||[],analysisTime:e._startTime?Math.round((Date.now()-e._startTime)/1e3):null};case"ENGINE_FALLBACK":return{...e,phase:"complete",isHeuristic:!0,error:t.error};case"SET_SIGNED_IN":return{...e,signedIn:!!t.value};case"FREE_TIER_COMPLETE":return{...e,phase:"complete",isHeuristic:!0,freeTier:!0};case"SELECT_GAME":return{...e,selectedGameIdx:t.idx};case"BACK_TO_REPORT":return{...e,selectedGameIdx:null};case"RESTORE_STATE":return{...initialState,signedIn:e.signedIn,phase:"ready",username:t.p.username||"",platform:t.p.platform||"chesscom",accounts:t.p.accounts||(t.p.username?[{platform:t.p.platform,username:t.p.username}]:[]),depth:t.p.depth||10,format:t.p.format||"rapid",gameCount:t.p.gameCount||40};case"LOAD_HISTORICAL_REPORT":{const n=t.p||{},a=n.aggregates||{};return{...initialState,phase:"complete",username:n.username||"",platform:n.platform||"chesscom",format:n.format||"rapid",depth:n.depth||10,gameCount:n.gameCount||40,profile:a.profile||null,stats:a.stats||null,games:a.games||[],analyzedGames:a.analyzedGames||[],correlations:a.correlations||null,patterns:a.patterns||null,analysisTime:a.analysisTime||null,_loadedAnalysis:n.aggregates?{...a,insights:n.insights||null}:null,_loadedReportId:n.id||null,_historyList:e._historyList||[]}}case"SET_HISTORY_LIST":return{...e,_historyList:t.rows||[]};case"RESET":return{...initialState,username:e.username,platform:e.platform,depth:e.depth,format:e.format,gameCount:e.gameCount};case"BACK_TO_SELECTION":return{...initialState,phase:"ready",username:e.username,platform:e.platform,format:e.format,depth:e.depth,gameCount:e.gameCount,accounts:e.accounts,_historyList:e._historyList||[]};default:return e}}function StatBox({label:e,value:t,sub:n,color:a="white",large:s,icon:i,stripe:p}){const m=p?{borderTop:`3px solid ${p}`}:null;return i?React.createElement("div",{className:"pr-stat-box",style:{display:"flex",alignItems:"center",gap:12,...m||{}}},React.createElement("span",{style:{display:"inline-flex",lineHeight:0,opacity:.7},dangerouslySetInnerHTML:{__html:i}}),React.createElement("div",null,React.createElement("div",{className:"pr-label",style:{marginTop:6}},e),React.createElement("div",{className:s?"pr-stat-value--lg":"pr-stat-value",style:{color:a}},t),n&&React.createElement("div",{className:"pr-dim pr-mt-1"},n))):React.createElement("div",{className:"pr-stat-box",style:m||void 0},React.createElement("div",{className:"pr-label"},e),React.createElement("div",{className:s?"pr-stat-value--lg":"pr-stat-value",style:{color:a}},t),n&&React.createElement("div",{className:"pr-dim pr-mt-1"},n))}const TC_ICONS={rapid:'<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#81B64C" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="10" x2="14" y1="2" y2="2"/><line x1="12" x2="15" y1="14" y2="11"/><circle cx="12" cy="14" r="8"/></svg>',blitz:'<svg width="28" height="28" viewBox="0 0 24 24" fill="#FFBF00" stroke="none"><polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/></svg>',bullet:'<svg width="28" height="28" viewBox="0 0 24 24" fill="#E8A035"><path d="M8 7C5 7 5 17 8 17C12 17 22 14 22 12C22 10 12 7 8 7Z"/><rect x="0" y="8" width="5" height="1.8" rx=".9"/><rect x="0" y="11.1" width="6" height="1.8" rx=".9"/><rect x="0" y="14.2" width="5" height="1.8" rx=".9"/></svg>',tactics:'<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="#9B8ABF" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"/></svg>'};function SectionCard({title:e,badge:t,children:n,className:a="",delay:s=0}){return React.createElement("div",{className:`pr-card pr-animate-section ${a}`,style:{animationDelay:`${s}s`}},e&&React.createElement("div",{className:"pr-card__header"},React.createElement("h2",{className:"pr-heading"},e),t&&React.createElement("span",{className:"pr-badge--pill",style:{background:t==="estimated"?"rgba(212,164,75,0.15)":t==="instant"?"rgba(107,159,212,0.15)":"rgba(93,182,125,0.15)",color:t==="estimated"?"#D4A44B":t==="instant"?"#6B9FD4":"#5DB67D"}},t)),n)}function ProgressBar({value:e,max:t=100,color:n="#5DB67D",height:a=6,label:s,showPct:i=!0}){const p=Math.min(100,Math.round(e/t*100));return React.createElement("div",{className:"pr-row--3"},s&&React.createElement("span",{className:"pr-meta pr-text-right pr-shrink-0",style:{width:80}},s),React.createElement("div",{className:"pr-flex-1 pr-progress-bar",style:{height:a,background:"rgba(255,255,255,0.04)"}},React.createElement("div",{className:"pr-progress-bar__fill",style:{width:`${p}%`,background:n}})),i&&React.createElement("span",{className:"pr-text-xs pr-font-bold pr-text-right",style:{color:n,width:40}},p,"%"))}function Badge({children:e,color:t="#5DB67D"}){return React.createElement("span",{className:"pr-badge",style:{background:t+"18",color:t}},e)}function escapeHtml(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}function InlineProgressInner({state:e}){const{progress:t,analyzedGames:n,phase:a}=e,s=t.totalGames>0?Math.round(n.length/t.totalGames*100):0,i=n.filter(m=>m),p=i.length>0?Math.round(i.reduce((m,l)=>m+l.playerAccuracy,0)/i.length*10)/10:null;return React.createElement("div",{style:{width:"100%"}},React.createElement("div",{className:"pr-text-center",style:{marginBottom:20}},React.createElement("div",{className:"pr-spinner pr-spinner--lg",style:{margin:"0 auto 14px",width:56,height:56}}),React.createElement("h2",{style:{fontSize:22,fontWeight:700,color:"#F0EDE8",margin:"0 0 6px",letterSpacing:"-0.01em"}},a==="fetching"?"Fetching Games...":e.depth===0?"Processing Games...":"Analyzing Moves..."),React.createElement("p",{style:{fontSize:16,color:"#E8E4DF",margin:0,lineHeight:1.4}},a==="fetching"?`Loading ${e.platform==="lichess"?"Lichess":"Chess.com"} games for ${e.username}...`:`Game ${Math.min(n.length+1,t.totalGames)} of ${t.totalGames}`)),a==="analyzing"&&React.createElement(React.Fragment,null,React.createElement("div",{style:{marginBottom:16}},React.createElement("div",{className:"pr-row--between",style:{fontSize:14,fontWeight:700,letterSpacing:"0.06em",textTransform:"uppercase",color:"#E8E4DF",marginBottom:8}},React.createElement("span",null,"Overall Progress"),React.createElement("span",{style:{color:"#FFFFFF"}},s,"%")),React.createElement("div",{className:"pr-progress-bar",style:{height:10,background:"rgba(255,255,255,0.08)"}},React.createElement("div",{className:"pr-progress-bar__fill",style:{width:`${s}%`,background:"linear-gradient(90deg, #5DB67D, #6B9FD4)"}}))),React.createElement("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12}},React.createElement("div",{style:{background:"rgba(255,255,255,0.05)",border:"1px solid rgba(255,255,255,0.08)",borderRadius:10,padding:"10px 12px",textAlign:"center"}},React.createElement("div",{style:{fontSize:12,fontWeight:700,letterSpacing:"0.08em",textTransform:"uppercase",color:"#E8E4DF",marginBottom:5}},"Avg Accuracy"),React.createElement("div",{style:{fontSize:24,fontWeight:800,color:"#7DD49E",lineHeight:1}},p!==null?`${p}%`:"\u2014")),React.createElement("div",{style:{background:"rgba(255,255,255,0.05)",border:"1px solid rgba(255,255,255,0.08)",borderRadius:10,padding:"10px 12px",textAlign:"center"}},React.createElement("div",{style:{fontSize:12,fontWeight:700,letterSpacing:"0.08em",textTransform:"uppercase",color:"#E8E4DF",marginBottom:5}},"Games Done"),React.createElement("div",{style:{fontSize:24,fontWeight:800,color:"#8FB8E0",lineHeight:1}},i.length)))))}function InlineProgress({state:e}){const{progress:t,analyzedGames:n,phase:a,cachedGamesCount:s}=e,i=t.totalGames>0?Math.round(n.length/t.totalGames*100):0,p=n.filter(m=>m).length>0?Math.round(n.filter(m=>m).reduce((m,l)=>m+l.playerAccuracy,0)/n.filter(m=>m).length*10)/10:null;return React.createElement("div",{className:"pr-max-w-lg",style:{marginTop:96}},React.createElement("div",{className:"pr-card pr-card--p8"},React.createElement("div",{className:"pr-text-center pr-mb-6"},React.createElement("div",{className:"pr-spinner pr-spinner--lg pr-mb-4"}),React.createElement("h2",{className:"pr-heading--lg pr-mb-1"},a==="fetching"?"Fetching Games...":e.depth===0?"Processing Games...":"Analyzing Moves..."),React.createElement("p",{className:"pr-body pr-text-muted"},a==="fetching"?`Loading ${e.platform==="lichess"?"Lichess":"Chess.com"} games for ${e.username}...`:`Game ${Math.min(n.length+1,t.totalGames)} of ${t.totalGames}`)),a==="analyzing"&&React.createElement(React.Fragment,null,React.createElement("div",{className:"pr-mb-5"},React.createElement("div",{className:"pr-row--between pr-meta pr-mb-2"},React.createElement("span",null,"Overall Progress"),React.createElement("span",{className:"pr-font-bold pr-text-white"},i,"%")),React.createElement("div",{className:"pr-progress-bar",style:{height:10,background:"rgba(255,255,255,0.04)"}},React.createElement("div",{className:"pr-progress-bar__fill",style:{width:`${i}%`,background:"linear-gradient(90deg, #5DB67D, #6B9FD4)"}}))),t.currentGame&&React.createElement("div",{className:"pr-elevated pr-mb-4"},React.createElement("div",{className:"pr-meta pr-mb-1"},"Currently Analyzing"),React.createElement("div",{className:"pr-title--white pr-progress-pulse"},t.currentGame),t.totalMoves>0&&React.createElement("div",{className:"pr-mt-2 pr-progress-bar",style:{height:4,background:"rgba(255,255,255,0.04)"}},React.createElement("div",{className:"pr-progress-bar__fill",style:{width:`${Math.round(t.moveIndex/t.totalMoves*100)}%`,background:"#5DB67D"}}))),p!==null&&React.createElement("div",{className:"pr-grid-2"},React.createElement("div",{className:"pr-stat-box--center"},React.createElement("div",{className:"pr-meta--10",style:{textTransform:"uppercase"}},"Avg Accuracy"),React.createElement("div",{className:"pr-text-lg pr-font-extrabold",style:{color:"#5DB67D"}},p,"%")),React.createElement("div",{className:"pr-stat-box--center"},React.createElement("div",{className:"pr-meta--10",style:{textTransform:"uppercase"}},"Games Done"),React.createElement("div",{className:"pr-text-lg pr-font-extrabold",style:{color:"#6B9FD4"}},n.length))))))}function InlineError({error:e,onRetry:t}){return React.createElement("div",{className:"pr-max-w-lg",style:{marginTop:96}},React.createElement("div",{className:"pr-card--error"},React.createElement("div",{className:"pr-error-icon"},React.createElement("span",{style:{color:"#CF6E6E",fontSize:20,fontWeight:700}},"!")),React.createElement("h2",{className:"pr-heading--lg pr-mb-2"},"Could Not Load Games"),React.createElement("p",{className:"pr-body pr-text-muted pr-mb-5"},e),React.createElement("button",{onClick:t,className:"pr-btn",style:{background:"linear-gradient(135deg, #5DB67D, #4A9466)"}},"Try Again")))}function SelectionScreen({state:e,dispatch:t,onStart:n,onLoadHistory:a}){const[s,i]=useState(!1),[p,m]=useState(!1),[l,r]=useState(""),c=e._historyList||[],y=!!e.username.trim(),k=()=>{if(!y){r("Enter your username first.");const v=document.getElementById("pr-username");v&&v.focus();return}r("");try{window.LumiProfile?.Analytics?.track("profile_report_started",{platform:e.platform||null,format:e.format||null,game_count:e.gameCount??null,depth:e.depth??null})}catch{}n()},d=[{id:"rapid",label:"Rapid"},{id:"blitz",label:"Blitz"},{id:"bullet",label:"Bullet"}],u=e.depth<=10?"Fast":e.depth<=18?"Standard":"Deep",o=({platform:v,size:h=22,color:S})=>{if(v==="chesscom"){const M=S||"#81B64C";return React.createElement("svg",{width:h,height:h,viewBox:"0 1.5 50 50","aria-hidden":"true"},React.createElement("ellipse",{cx:"25",cy:"18.126",fill:M,stroke:"rgba(0,0,0,0.35)",strokeLinejoin:"round",rx:"7.161",ry:"6.834"}),React.createElement("path",{fill:M,stroke:"rgba(0,0,0,0.35)",d:"M25 24.598c-5.228.044-7.985-.028-8.394 4.508h16.788c-.41-4.536-3.165-4.464-8.394-4.508z"}),React.createElement("path",{fill:M,stroke:"rgba(0,0,0,0.35)",d:"M20.484 29.106c.496 6.787-9.303 7.996-8.706 17.19h26.444c.597-9.194-9.202-10.403-8.706-17.19H25z"}))}const C=S||"#F0EBE0";return React.createElement("svg",{width:h,height:h,viewBox:"0 0 50 50","aria-hidden":"true"},React.createElement("path",{fill:C,stroke:C,strokeLinejoin:"round",d:"M38.956.5c-3.53.418-6.452.902-9.286 2.984C5.534 1.786-.692 18.533.68 29.364 3.493 50.214 31.918 55.785 41.329 41.7c-7.444 7.696-19.276 8.752-28.323 3.084S-.506 27.392 4.683 17.567C9.873 7.742 18.996 4.535 29.03 6.405c2.43-1.418 5.225-3.22 7.655-3.187l-1.694 4.86 12.752 21.37c-.439 5.654-5.459 6.112-5.459 6.112-.574-1.47-1.634-2.942-4.842-6.036-3.207-3.094-17.465-10.177-15.788-16.207-2.001 6.967 10.311 14.152 14.04 17.663 3.73 3.51 5.426 6.04 5.795 6.756 0 0 9.392-2.504 7.838-8.927L37.4 7.171z"}))},g={rapid:"#81B64C",blitz:"#FFBF00",bullet:"#E8A035"},f=({format:v,size:h=18})=>{const S=g[v]||"var(--pr-text-body)";return v==="rapid"?React.createElement("svg",{width:h,height:h,viewBox:"0 0 24 24",fill:"none",stroke:S,strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},React.createElement("line",{x1:"10",x2:"14",y1:"2",y2:"2"}),React.createElement("line",{x1:"12",x2:"15",y1:"14",y2:"11"}),React.createElement("circle",{cx:"12",cy:"14",r:"8"})):v==="blitz"?React.createElement("svg",{width:h,height:h,viewBox:"0 0 24 24",fill:S,stroke:"none","aria-hidden":"true"},React.createElement("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})):v==="bullet"?React.createElement("svg",{width:h,height:h,viewBox:"0 0 24 24",fill:S,"aria-hidden":"true"},React.createElement("path",{d:"M8 7C5 7 5 17 8 17C12 17 22 14 22 12C22 10 12 7 8 7Z"}),React.createElement("rect",{x:"0",y:"8",width:"5",height:"1.8",rx:".9"}),React.createElement("rect",{x:"0",y:"11.1",width:"6",height:"1.8",rx:".9"}),React.createElement("rect",{x:"0",y:"14.2",width:"5",height:"1.8",rx:".9"})):null},x={display:"block",fontSize:14,fontWeight:600,letterSpacing:"0.06em",textTransform:"uppercase",color:"var(--lumi-text-secondary, #E8E4E0)",marginBottom:8};return React.createElement("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",padding:"56px 20px 80px",minHeight:"60vh"}},React.createElement("h1",{style:{fontSize:26,fontWeight:700,margin:"0 0 8px",color:"var(--lumi-amber-200)",letterSpacing:"-0.015em",textAlign:"center",lineHeight:1.2}},"Free Profile Report"),React.createElement("p",{style:{fontSize:16,fontWeight:450,margin:"0 0 32px",color:"var(--lumi-text-secondary, #E8E4E0)",letterSpacing:"0.005em",textAlign:"center",lineHeight:1.5,maxWidth:620}},"A detailed report on Openings, Tactics, Endgame, Time Management, Mental Game, etc., with a personalised improvement plan."),React.createElement("div",{style:{width:"100%",maxWidth:540,background:"var(--lumi-bg-nav)",border:"1px solid rgba(212, 164, 75, 0.22)",borderRadius:22,padding:"clamp(24px, 3vw, 36px) clamp(24px, 3.2vw, 40px)",display:"flex",flexDirection:"column",gap:18,position:"relative",boxShadow:"0 1px 0 rgba(255,255,255,0.03) inset, 0 0 0 1px rgba(0,0,0,0.20) inset, 0 12px 36px rgba(0,0,0,0.28)"}},React.createElement("span",{"aria-hidden":"true",style:{position:"absolute",left:32,right:32,top:-1,height:1,background:"linear-gradient(90deg, transparent 0%, rgba(212,164,75,0.55) 40%, rgba(212,164,75,0.55) 60%, transparent 100%)",pointerEvents:"none"}}),React.createElement("div",{style:{display:"flex",alignItems:"center",gap:14,marginBottom:4}},React.createElement("span",{"aria-hidden":"true",style:{flexShrink:0,width:38,height:38,display:"inline-flex",alignItems:"center",justifyContent:"center",borderRadius:9,overflow:"hidden",boxShadow:"0 4px 12px rgba(0,0,0,0.35)"}},React.createElement("svg",{viewBox:"0 0 24 24",xmlns:"http://www.w3.org/2000/svg",style:{width:"100%",height:"100%",display:"block"}},React.createElement("path",{d:"M 3,1 H 12 V 12 H 1 V 3 A 2,2 0 0,1 3,1 Z",fill:"#F5E4C3"}),React.createElement("path",{d:"M 12,1 H 21 A 2,2 0 0,1 23,3 V 12 H 12 V 1 Z",fill:"#9C7044"}),React.createElement("path",{d:"M 1,12 H 12 V 23 H 3 A 2,2 0 0,1 1,21 V 12 Z",fill:"#9C7044"}),React.createElement("path",{d:"M 12,12 H 23 V 21 A 2,2 0 0,1 21,23 H 12 V 12 Z",fill:"#F5E4C3"}))),React.createElement("p",{style:{margin:0,fontFamily:"Satoshi, sans-serif",fontSize:18,fontWeight:700,lineHeight:1.2,letterSpacing:"-0.012em",color:"var(--lumi-text-primary, #F0EDE8)"}},"Start your free Profile Report.")),React.createElement("div",null,React.createElement("label",{style:x},"Platform"),React.createElement("div",{className:"pr-platform-toggle",style:{width:"100%",gap:10}},[{id:"chesscom",label:"Chess.com",activeBg:"rgba(129,182,76,0.16)",activeBorder:"#81b64c"},{id:"lichess",label:"Lichess",activeBg:"rgba(255,255,255,0.10)",activeBorder:"var(--lumi-amber-300, #E0B35A)"}].map(v=>{const h=e.platform===v.id;return React.createElement("button",{key:v.id,onClick:()=>t({type:"SET_PLATFORM",value:v.id}),className:"pr-platform-toggle__btn",style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",gap:10,background:h?v.activeBg:"rgba(255,255,255,0.045)",border:h?`2px solid ${v.activeBorder}`:"1.5px solid rgba(255,255,255,0.10)",borderRadius:12,color:"#fff",fontSize:16,fontWeight:600,padding:"12px 14px",height:56,opacity:h?1:.85,transform:h?"translateY(-1px)":"translateY(0)",boxShadow:h?"0 0 0 3px rgba(212,164,75,0.22), 0 8px 18px rgba(0,0,0,0.30)":"none",transition:"opacity 0.18s ease, background 0.18s ease, border-color 0.18s ease, box-shadow 0.22s ease, transform 0.18s ease"}},v.id==="chesscom"?React.createElement("img",{src:"/assets/images/brand/chesscom-logo-white.png",alt:"Chess.com",style:{height:22,width:"auto",display:"block",opacity:h?1:.78}}):React.createElement(React.Fragment,null,React.createElement(o,{platform:v.id,size:22,color:h?"#F0EBE0":"var(--pr-text-body)"}),React.createElement("span",{style:{color:h?"#fff":"var(--pr-text-body)"}},v.label)))}))),React.createElement("div",null,React.createElement("label",{style:x,htmlFor:"pr-username"},"Username"),React.createElement("form",{autoComplete:"off",onSubmit:v=>v.preventDefault(),style:{margin:0}},React.createElement("div",{"aria-hidden":"true",style:{position:"absolute",left:-1e4,top:-1e4,width:1,height:1,overflow:"hidden",opacity:0}},React.createElement("input",{type:"text",name:"fakeusernameremembered",tabIndex:-1,autoComplete:"username"}),React.createElement("input",{type:"password",name:"fakepasswordremembered",tabIndex:-1,autoComplete:"current-password"})),React.createElement("input",{id:"pr-username",autoFocus:!0,type:"text",name:"lumichess-handle",value:e.username,onChange:v=>{l&&r(""),t({type:"SET_USERNAME",value:v.target.value})},onKeyDown:v=>{v.key==="Enter"&&k()},className:"pr-input",placeholder:e.platform==="lichess"?"Your Lichess username":"Your Chess.com username",autoComplete:"off",autoCorrect:"off",autoCapitalize:"off",spellCheck:!1,"data-1p-ignore":"true","data-lpignore":"true","data-bwignore":"true","aria-label":"Chess handle",style:{width:"100%",fontSize:16,padding:"12px 14px"}}))),React.createElement("div",null,React.createElement("label",{style:x},"Format"),React.createElement("div",{className:"pr-pill-group",style:{width:"100%",gap:10}},d.map(v=>{const h=e.format===v.id,S=g[v.id];return React.createElement("button",{key:v.id,onClick:()=>t({type:"SET_FORMAT",value:v.id}),className:"pr-pill-btn",style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",gap:8,background:h?`${S}26`:"rgba(255,255,255,0.045)",color:h?S:"var(--pr-text-primary)",border:h?`2px solid ${S}`:"1.5px solid rgba(255,255,255,0.10)",borderRadius:12,fontSize:16,fontWeight:600,padding:"12px 14px",height:48,transform:h?"translateY(-1px)":"translateY(0)",boxShadow:h?"0 0 0 3px rgba(212,164,75,0.18), 0 6px 14px rgba(0,0,0,0.25)":"none",transition:"background 0.18s ease, color 0.18s ease, border-color 0.18s ease, box-shadow 0.22s ease, transform 0.18s ease"}},React.createElement(f,{format:v.id,size:18}),React.createElement("span",null,v.label))}))),React.createElement("button",{onClick:k,className:"pr-cta-3d",style:{width:"100%",marginTop:12,background:"linear-gradient(180deg, #EAC178 0%, #D4A44B 50%, #B6862B 100%)",color:"#1a1a14",fontSize:16,fontWeight:800,letterSpacing:"0.01em",padding:"18px 20px",borderRadius:12,border:"1px solid #B6862B",cursor:"pointer",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:10,boxShadow:"inset 0 1px 0 rgba(255,255,255,0.35), inset 0 -2px 0 rgba(0,0,0,0.18), 0 5px 0 #7B5A1C, 0 12px 24px rgba(0,0,0,0.40)",transform:"translateY(0)",transition:"transform 0.05s ease-out, box-shadow 0.05s ease-out"},onMouseDown:v=>{v.currentTarget.style.transform="translateY(3px)",v.currentTarget.style.boxShadow="inset 0 1px 0 rgba(255,255,255,0.35), inset 0 -2px 0 rgba(0,0,0,0.18), 0 2px 0 #7B5A1C, 0 4px 10px rgba(0,0,0,0.35)"},onMouseUp:v=>{v.currentTarget.style.transform="translateY(0)",v.currentTarget.style.boxShadow="inset 0 1px 0 rgba(255,255,255,0.35), inset 0 -2px 0 rgba(0,0,0,0.18), 0 5px 0 #7B5A1C, 0 12px 24px rgba(0,0,0,0.40)"},onMouseLeave:v=>{v.currentTarget.style.transform="translateY(0)",v.currentTarget.style.boxShadow="inset 0 1px 0 rgba(255,255,255,0.35), inset 0 -2px 0 rgba(0,0,0,0.18), 0 5px 0 #7B5A1C, 0 12px 24px rgba(0,0,0,0.40)"}},React.createElement("span",null,"Create Profile Report"),React.createElement("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.6",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},React.createElement("path",{d:"M5 12h14M13 5l7 7-7 7"}))),l&&React.createElement("div",{role:"alert",style:{marginTop:-4,fontSize:14,color:"#CF6E6E",fontFamily:"Satoshi, sans-serif",display:"flex",alignItems:"center",gap:8}},React.createElement("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},React.createElement("circle",{cx:"12",cy:"12",r:"10"}),React.createElement("line",{x1:"12",y1:"8",x2:"12",y2:"12"}),React.createElement("line",{x1:"12",y1:"16",x2:"12.01",y2:"16"})),l)),c.length>0&&React.createElement("div",{style:{width:"100%",maxWidth:720,marginTop:40}},React.createElement("div",{style:{display:"flex",alignItems:"baseline",justifyContent:"space-between",marginBottom:12}},React.createElement("div",{style:{fontSize:14,fontWeight:600,letterSpacing:"0.18em",textTransform:"uppercase",color:"#D4A44B"}},"Past Reports"),React.createElement("div",{style:{fontSize:14,color:"var(--pr-text-body)"}},c.length," saved")),React.createElement("div",{style:{background:"#1e1e1b",border:"1px solid rgba(255,255,255,0.06)",borderRadius:12,overflow:"hidden"}},React.createElement("div",{style:{display:"grid",gridTemplateColumns:"1.5fr 1fr 0.8fr 0.6fr 0.8fr",gap:10,padding:"12px 18px",background:"rgba(255,255,255,0.025)",borderBottom:"1px solid rgba(255,255,255,0.05)",fontSize:13,fontWeight:600,letterSpacing:"0.08em",textTransform:"uppercase",color:"var(--pr-text-body)"}},React.createElement("div",null,"Username"),React.createElement("div",null,"Platform"),React.createElement("div",null,"Format"),React.createElement("div",{style:{textAlign:"right"}},"Games"),React.createElement("div",{style:{textAlign:"right"}},"Date")),c.map((v,h)=>{const S=v.platform==="chesscom"?"Chess.com":"Lichess",C=new Date(v.created_at).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"2-digit"});return React.createElement("button",{key:v.id,onClick:()=>a&&a(v.id),style:{display:"grid",gridTemplateColumns:"1.5fr 1fr 0.8fr 0.6fr 0.8fr",gap:10,alignItems:"center",width:"100%",padding:"14px 18px",background:"transparent",border:"none",borderBottom:h===c.length-1?"none":"1px solid rgba(255,255,255,0.04)",color:"var(--pr-text-body)",cursor:"pointer",textAlign:"left",fontFamily:"inherit",fontSize:16,transition:"background 0.12s"},onMouseEnter:M=>M.currentTarget.style.background="rgba(212,164,75,0.05)",onMouseLeave:M=>M.currentTarget.style.background="transparent"},React.createElement("div",{style:{fontWeight:600,color:"#fff",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}},v.username),React.createElement("div",{style:{display:"flex",alignItems:"center",gap:8,color:"var(--pr-text-body)"}},React.createElement(o,{platform:v.platform,size:18,color:v.platform==="chesscom"?"#81B64C":"#F0EBE0"}),React.createElement("span",null,S)),React.createElement("div",{style:{display:"flex",alignItems:"center",gap:8,color:"var(--pr-text-primary)"}},v.format&&g[v.format]?React.createElement(f,{format:v.format,size:16}):null,React.createElement("span",{style:{textTransform:"capitalize"}},v.format||"\u2014")),React.createElement("div",{style:{textAlign:"right",fontVariantNumeric:"tabular-nums",color:"var(--pr-text-primary)"}},v.game_count),React.createElement("div",{style:{textAlign:"right",color:"var(--pr-text-body)",fontSize:14}},C))}))))}function PlayerCard({profile:e,stats:t,analysis:n,platform:a,analysisTime:s}){const i=e||{username:"?",joined:0,country:"",followers:0,league:"",status:""},p=t||{rapid:{},blitz:{},bullet:{},tactics:{}},m=i.joined?new Date(i.joined*1e3).toLocaleDateString("en-US",{month:"short",year:"numeric"}):"?",l=a==="lichess"||i.platform==="lichess";return React.createElement(SectionCard,{delay:.05},React.createElement("div",{className:"pr-row--start",style:{flexDirection:"column",gap:24}},React.createElement("div",{style:{display:"flex",flexDirection:"row",gap:24,alignItems:"flex-start",flexWrap:"wrap"}},React.createElement("div",{className:"pr-avatar",style:{color:"#5DB67D"}},i.username[0].toUpperCase()),React.createElement("div",{className:"pr-flex-1 pr-min-w-0"},React.createElement("div",{className:"pr-row--wrap-3 pr-mb-1"},React.createElement("h1",{className:"pr-heading--2xl"},i.username),i.title&&React.createElement(Badge,{color:"#D4A44B"},i.title),React.createElement(Badge,{color:l?"#6B9FD4":"#5DB67D"},l?"Lichess":"Chess.com"),React.createElement(Badge,{color:n.isHeuristic?"#D4A44B":"#5DB67D"},n.isHeuristic?"Estimated":"Full Analysis"),s&&React.createElement(Badge,{color:"rgba(255,255,255,0.12)"},s>=60?`${Math.floor(s/60)}m ${s%60}s`:`${s}s`)),React.createElement("div",{className:"pr-body pr-text-muted pr-mb-3"},i.country?`${i.country} \xB7 `:"","Member since ",m,i.followers?` \xB7 ${i.followers} followers`:"")))),React.createElement("div",{className:"pr-grid-4 pr-mt-5"},React.createElement(StatBox,{label:"Rapid",value:p.rapid.current||"\u2014",sub:p.rapid.best?`Best: ${p.rapid.best}`:"",color:"#5DB67D",icon:TC_ICONS.rapid}),React.createElement(StatBox,{label:"Blitz",value:p.blitz.current||"\u2014",sub:p.blitz.best?`Best: ${p.blitz.best}`:"",color:"#6B9FD4",icon:TC_ICONS.blitz}),React.createElement(StatBox,{label:"Bullet",value:p.bullet.current||"\u2014",sub:p.bullet.best?`Best: ${p.bullet.best}`:"",color:"#D4A44B",icon:TC_ICONS.bullet}),React.createElement(StatBox,{label:"Tactics",value:p.tactics.highest||"\u2014",sub:"Puzzle rating",color:"#9B8ABF",icon:TC_ICONS.tactics})))}function LockedSectionCard({title:e,onUnlock:t,delay:n=0}){return React.createElement("div",{className:"pr-card pr-animate-section",style:{animationDelay:`${n}s`,display:"flex",flexDirection:"column",overflow:"hidden"}},React.createElement("div",{className:"pr-card__header",style:{marginBottom:0}},React.createElement("h2",{className:"pr-heading",style:{opacity:.6}},e)),React.createElement("button",{type:"button",onClick:t,"aria-label":`Sign in to unlock ${e}`,style:{flex:1,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:10,minHeight:160,background:"transparent",border:"none",color:"rgba(232,228,224,0.42)",cursor:"pointer",padding:"32px 16px",fontFamily:"Satoshi, sans-serif",fontSize:13,letterSpacing:"0.10em",textTransform:"uppercase",fontWeight:600,transition:"color 0.15s ease-out"},onMouseEnter:a=>{a.currentTarget.style.color="rgba(232,228,224,0.72)"},onMouseLeave:a=>{a.currentTarget.style.color="rgba(232,228,224,0.42)"}},React.createElement("svg",{width:"28",height:"28",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},React.createElement("rect",{x:"3",y:"11",width:"18",height:"11",rx:"2",ry:"2"}),React.createElement("path",{d:"M7 11V7a5 5 0 0 1 10 0v4"})),React.createElement("span",null,"Sign in to unlock")))}function LockedPreview(){const e=()=>import("/src/auth/auth-modal.js").then(n=>n.openAuthModal("signup")),t=["Performance Radar","Opening Repertoire","Tactics","Endgame","Advantage Capitalization","Time Management","Resourcefulness","Consistency","Personalized Improvement Plan",{header:"Additional Insights"},"Mental Game & Psychology","Performance by Color","Accuracy by Piece","Game Phases","Castling Analysis","How You Win & How You Lose","Game-by-Game Results"];return React.createElement(React.Fragment,null,React.createElement("div",{className:"pr-card pr-animate-section",style:{padding:"22px 28px",background:"linear-gradient(180deg, rgba(212,164,75,0.12) 0%, rgba(212,164,75,0.04) 100%)",borderColor:"rgba(212,164,75,0.32)",display:"flex",alignItems:"center",gap:20,flexWrap:"wrap",animationDelay:"0.05s"}},React.createElement("div",{style:{flex:"1 1 320px",minWidth:240}},React.createElement("div",{style:{display:"inline-flex",alignItems:"center",gap:6,fontSize:12,letterSpacing:"0.16em",textTransform:"uppercase",color:"#D4A44B",marginBottom:6,fontWeight:700,fontFamily:"Satoshi, sans-serif"}},React.createElement("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},React.createElement("path",{d:"M5 12l5 5L20 7"})),"Free \xB7 No credit card"),React.createElement("h3",{style:{margin:0,fontSize:20,fontWeight:700,color:"#F0EDE8",lineHeight:1.25,letterSpacing:"-0.01em",fontFamily:"Satoshi, sans-serif"}},"Sign in to unlock your full Profile Report")),React.createElement("button",{type:"button",className:"js-auth-open","data-mode":"signup",onClick:e,style:{background:"var(--lumi-accent, #D4A44B)",color:"#1a1612",border:"none",borderRadius:12,padding:"13px 26px",fontFamily:"Satoshi, sans-serif",fontSize:16,fontWeight:700,letterSpacing:"0.01em",cursor:"pointer",boxShadow:"0 8px 24px rgba(212,164,75,0.28)",whiteSpace:"nowrap"}},"Sign in or sign up")),t.map((n,a)=>typeof n=="object"&&n.header?React.createElement("div",{key:`h-${n.header}`,style:{scrollMarginTop:64,padding:"24px 0 8px"}},React.createElement("h2",{style:{margin:0,fontSize:18,fontWeight:700,color:"#fff",opacity:.6}},n.header)):React.createElement(LockedSectionCard,{key:n,title:n,onUnlock:e,delay:.1+a*.025})))}function RatingMomentum({stats:e,analysis:t,username:n,platform:a,format:s,gameCount:i}){const p=e||{rapid:{current:0},blitz:{current:0}},m=t.rapidBlitzGap;if(!t.ratingTrend||!Array.isArray(t.ratingTrend)||t.ratingTrend.length===0)return null;const l=a==="lichess"?"Lichess":"Chess.com",r=s?s.charAt(0).toUpperCase()+s.slice(1):null;return React.createElement(SectionCard,{title:"Rating & Momentum",badge:t.isHeuristic?"estimated":null,delay:.1},n&&React.createElement("div",{style:{display:"flex",flexWrap:"wrap",gap:10,alignItems:"center",fontSize:16,letterSpacing:"-0.011em",color:"var(--pr-text-secondary)",marginTop:-6,marginBottom:20}},React.createElement("span",{style:{color:"var(--pr-text-primary)",fontWeight:600}},n),React.createElement("span",{style:{opacity:.4}},"\xB7"),React.createElement("span",null,l),r&&React.createElement(React.Fragment,null,React.createElement("span",{style:{opacity:.4}},"\xB7"),React.createElement("span",null,r)),Number.isFinite(i)&&i>0&&React.createElement(React.Fragment,null,React.createElement("span",{style:{opacity:.4}},"\xB7"),React.createElement("span",null,i," games"))),React.createElement("div",{className:"pr-grid-2--lg pr-rm-grid"},React.createElement("div",null,(()=>{const c=t.ratingTrend,y=c.length>=2?c[c.length-1].rating-c[0].rating:0,k=y>=0?"+":"",d=y>0?"#5DB67D":y<0?"#CF6E6E":"rgba(255,255,255,0.5)",u=(t.primaryTimeClass||"blitz").charAt(0).toUpperCase()+(t.primaryTimeClass||"blitz").slice(1);return React.createElement("div",{className:"pr-title--white pr-mb-3",style:{display:"flex",alignItems:"center",gap:8}},u," Rating Trend (Last ",c.length," Games)",c.length>=2&&React.createElement("span",{style:{fontSize:16,fontWeight:700,color:d,background:`${d}18`,padding:"1px 7px",borderRadius:4}},k,y))})(),React.createElement("div",{className:"pr-chart-h48"},React.createElement(ResponsiveContainer,{width:"100%",height:"100%"},React.createElement(AreaChart,{data:t.ratingTrend,margin:{top:5,right:10,bottom:0,left:0}},React.createElement("defs",null,React.createElement("linearGradient",{id:"ratingGrad",x1:"0",y1:"0",x2:"0",y2:"1"},React.createElement("stop",{offset:"0%",stopColor:"#6B9FD4",stopOpacity:.3}),React.createElement("stop",{offset:"100%",stopColor:"#6B9FD4",stopOpacity:0}))),React.createElement(CartesianGrid,{strokeDasharray:"3 3"}),React.createElement(XAxis,{dataKey:"game",tick:{fontSize:14,fill:"var(--pr-text-primary)",fontWeight:500}}),React.createElement(YAxis,{domain:["dataMin - 20","dataMax + 20"],tick:{fontSize:14,fill:"var(--pr-text-primary)",fontWeight:500},width:56}),React.createElement(Tooltip,{content:({active:c,payload:y,label:k})=>!c||!y?.length?null:React.createElement("div",{style:{background:"#2a2a25",border:"1px solid rgba(255,255,255,0.15)",borderRadius:8,padding:"5px 12px",fontSize:16,color:"#fff",boxShadow:"0 4px 12px rgba(0,0,0,0.4)"}},"Game ",k," ",React.createElement("span",{style:{color:"#6B9FD4",fontWeight:600}},y[0].value))}),React.createElement(Area,{type:"monotone",dataKey:"rating",stroke:"#6B9FD4",fill:"url(#ratingGrad)",strokeWidth:2,dot:!1}))))),React.createElement("div",{className:"pr-stack--sm"},React.createElement("div",{className:"pr-grid-2"},React.createElement(StatBox,{label:"Avg Accuracy",value:`${t.avgAccuracy}%`,color:"#6B9FD4"}),React.createElement(StatBox,{label:"Win Rate",value:`${t.winRate}%`,color:"#5DB67D"})),React.createElement("div",{className:"pr-grid-3"},React.createElement(StatBox,{label:"Won",value:t.wins,color:"#5DB67D"}),React.createElement(StatBox,{label:"Lost",value:t.losses,color:"#CF6E6E"}),React.createElement(StatBox,{label:"Drawn",value:Math.max(0,t.total-t.wins-t.losses),color:"rgba(240,235,224,0.75)"})),React.createElement("div",{className:"pr-grid-2"},React.createElement(StatBox,{label:"Win % as White",value:`${t.whiteWinRate}%`,sub:`${t.asWhite} games`,color:"#fff"}),React.createElement(StatBox,{label:"Win % as Black",value:`${t.blackWinRate}%`,sub:`${t.asBlack} games`,color:"#fff"})))))}function TacticsConversionInline({analysis:e}){const t=React.useMemo(()=>{try{return window.LumiProfile?.TacticsFoundMissed?.computeFoundMissed(e.analyzedGames||[])}catch(d){return console.warn("[tactics] found-vs-missed compute failed",d),null}},[e]);if(!t||!t.gamesUsed)return null;const{motifs:n}=t,a=["fork","pin","mateIn1"];if(!a.some(d=>n[d]&&n[d].total>0))return null;const i={fork:"Fork",pin:"Pin",mateIn1:"Mate in 1"},p=e.analyzedGames||[],m=(t.misses||[]).slice(0,16),l=a.reduce((d,u)=>d+(n[u]?.found||0),0),r=a.reduce((d,u)=>d+(n[u]?.total||0),0);if(!r)return null;const c=Math.round(l/r*100),y=d=>{if(!d.fen)return;const u="/analysis?fen="+encodeURIComponent(d.fen)+(d.bestUci?"&best="+d.bestUci:"")+(d.playedUci?"&played="+d.playedUci:"");window.open(u,"_blank","noopener")},k=d=>{const u=p[d.gameIdx]||{},o=u.headers?u.playerColor==="w"?u.headers.Black:u.headers.White:null;return{motif:i[d.motif]||d.motif,moveNo:Math.floor(d.ply/2)+1,opp:o}};return React.createElement("div",{style:{gridColumn:"1 / -1"}},React.createElement("div",{className:"pr-label pr-mb-3"},"Tactical Conversion"),React.createElement("div",{style:{display:"flex",alignItems:"center",gap:16,flexWrap:"wrap",background:"rgba(255,255,255,0.04)",borderRadius:10,padding:"14px 18px"}},React.createElement("div",{style:{display:"flex",alignItems:"baseline",gap:8,flexShrink:0}},React.createElement("span",{style:{fontSize:30,fontWeight:800,color:"#5DB67D",lineHeight:1,letterSpacing:"-0.02em",fontVariantNumeric:"tabular-nums"}},c,"%"),React.createElement("span",{style:{fontSize:15,color:"var(--pr-text-primary)",fontWeight:500}},"converted")),React.createElement("div",{style:{flex:1,minWidth:180}},React.createElement("div",{style:{fontSize:14,color:"var(--pr-text-body)",marginBottom:6,lineHeight:1.45}},"You played the winning tactic in ",React.createElement("b",{style:{color:"#fff",fontWeight:700}},l)," of ",React.createElement("b",{style:{color:"#fff",fontWeight:700}},r)," chances across ",t.gamesUsed," games ",React.createElement("span",{style:{color:"var(--pr-text-secondary)"}},"(forks, pins, mate-in-1)"),"."),React.createElement("div",{style:{display:"flex",height:8,borderRadius:4,overflow:"hidden",background:"#CF6E6E"}},React.createElement("div",{style:{width:c+"%",background:"#5DB67D"}})))),m.length>0&&React.createElement("div",{style:{marginTop:14}},React.createElement("div",{style:{display:"flex",flexDirection:"column",gap:6}},m.map((d,u)=>{const o=k(d);return React.createElement("button",{key:u,onClick:()=>y(d),style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,width:"100%",background:"rgba(255,255,255,0.03)",border:"1px solid rgba(255,255,255,0.07)",borderRadius:9,padding:"10px 14px",cursor:"pointer",textAlign:"left",font:"inherit",color:"#ECE8E2"}},React.createElement("span",{style:{display:"flex",alignItems:"center",gap:10,minWidth:0}},React.createElement("span",{style:{color:"#CF6E6E",fontSize:15,flexShrink:0}},"\u2717"),React.createElement("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}},React.createElement("b",{style:{fontWeight:700}},o.motif),React.createElement("span",{style:{color:"var(--pr-text-secondary)",fontSize:14}}," \xB7 move ",o.moveNo,o.opp?` vs ${o.opp}`:""))),React.createElement("span",{style:{color:"#D4A44B",fontWeight:700,fontSize:14,whiteSpace:"nowrap",flexShrink:0}},"Review \u2192"))}))))}function PerformanceRadar({analysis:e,state:t}){const n=e.skillProfile&&e.skillProfile.dimensions,a=["opening","tactical","endgame","capitalization","time_mgmt","resourcefulness"],s={opening:"Opening",tactical:"Tactics",endgame:"Endgame",resourcefulness:"Resourcefulness",capitalization:"Conversion",time_mgmt:"Time Management"},i=n?a.filter(x=>e.skillProfile.dimensions[x]).map(x=>{const v=e.skillProfile.dimensions[x];return{dim:s[x]||x,value:v.score||50,fullMark:100,confidence:v.confidence}}):e.radar;if(!Array.isArray(i)||i.length===0)return null;const p=n?e.skillProfile.confidence:null,m=n?"Skill Profile":"Performance Radar",l=n?"#D4A44B":"#5DB67D",r=i,c=x=>x>=65?{label:"Strong",color:"#5DB67D"}:x>=45?{label:"Develop",color:"#D4A44B"}:{label:"Weak spot",color:"#CF6E6E"},y={Opening:"dim-opening","Opening Prep":"dim-opening",Tactics:"dim-tactical","Tactical Vision":"dim-tactical","Blunder Resist.":"dim-tactical",Endgame:"dim-endgame",Resourcefulness:"dim-resourcefulness",Conversion:"dim-capitalization",Capitalization:"dim-capitalization","Time Management":"dim-time-mgmt"},k=e.profile?.username||t?.username||"",d=t?.format&&t.format!=="all"?t.format:null,u=e.analyzedGames?.length||0,o=i.map(x=>({...x,value:0})),[g,f]=useState(o);return useEffect(()=>{const x=setTimeout(()=>f(i),80);return()=>clearTimeout(x)},[]),React.createElement(SectionCard,{title:m,badge:e.isHeuristic?"estimated":null,delay:.15},React.createElement("div",{className:"pr-grid-2--lg"},React.createElement("div",{className:"pr-chart-h72 pr-row--center"},React.createElement(ResponsiveContainer,{width:"100%",height:"100%"},React.createElement(RadarChart,{data:g,cx:"50%",cy:"50%",outerRadius:typeof window<"u"&&window.innerWidth<640?"58%":"70%"},React.createElement(PolarGrid,null),React.createElement(PolarRadiusAxis,{angle:90,domain:[0,100],tick:!1,axisLine:!1}),React.createElement(PolarAngleAxis,{dataKey:"dim",tick:({payload:x,x:v,y:h,textAnchor:S,cy:C,...M})=>{const R=i.find(I=>I.dim===x.value),b=R?R.value:"",w=typeof window<"u"&&window.innerWidth<640,D=typeof C=="number"&&h>C+4,N=D?h+14:h-12,T=D?h+30:h+6,E={Resourcefulness:"Resource","Time Management":"Time Mgmt","Tactical Vision":"Tactics","Blunder Resist.":"Blunders",Capitalization:"Convert","Opening Prep":"Opening"},L=w&&E[x.value]?E[x.value]:x.value,_=w?11:14;return React.createElement("g",null,React.createElement("text",{x:v,y:N,textAnchor:S,fill:"#F0EDE8",fontSize:_,fontWeight:600},L),React.createElement("text",{x:v,y:T,textAnchor:S,fill:l,fontSize:_,fontWeight:700},b))}}),React.createElement(Radar,{name:"You",dataKey:"value",stroke:l,fill:l,fillOpacity:.15,strokeWidth:2,dot:{r:3,fill:l},isAnimationActive:!0,animationDuration:1500,animationEasing:"ease-out"})))),React.createElement("div",null,React.createElement("div",{className:"pr-interp-list"},r.map(x=>{const v=c(x.value),h=y[x.dim];return React.createElement("div",{key:x.dim,className:"pr-interp-row"},React.createElement("span",{className:"pr-interp-dot",style:{background:v.color}}),React.createElement("span",{className:"pr-interp-name"},x.dim),React.createElement("span",{className:"pr-interp-score",style:{color:v.color}},x.value),React.createElement("span",{className:"pr-interp-badge",style:{background:`${v.color}18`,color:v.color}},v.label),h&&React.createElement("span",{role:"button",tabIndex:0,"aria-label":`Review ${x.dim}`,title:`Review ${x.dim}`,onClick:()=>document.getElementById(h)?.scrollIntoView({behavior:"smooth",block:"start"}),onKeyDown:S=>{(S.key==="Enter"||S.key===" ")&&(S.preventDefault(),document.getElementById(h)?.scrollIntoView({behavior:"smooth",block:"start"}))},style:{marginLeft:"auto",fontSize:16,color:"#D4A44B",opacity:.85,flexShrink:0,cursor:"pointer",userSelect:"none",lineHeight:1}},"\u2192"))})))))}function MoveQualityEngine({analysis:e,username:t}){if(e.isHeuristic||!e.analyzedGames||e.analyzedGames.length===0)return null;const n=e.analyzedGames.flatMap(l=>l.moveAnalysis.filter(r=>r.isPlayerMove&&r.classification!==null));if(n.length===0)return null;const a={};n.forEach(l=>{a[l.classification]=(a[l.classification]||0)+1});const i=["brilliant","best","excellent","good","book","inaccuracy","mistake","blunder"].map(l=>({name:CLASSIFICATION_LABELS[l],count:a[l]||0,color:CLASSIFICATION_COLORS[l]})).filter(l=>l.count>0),p=(t||"").toLowerCase(),m=e.analyzedGames.map((l,r)=>({game:r+1,accuracy:l.playerAccuracy,opponent:(l.headers?.White||"").toLowerCase()===p?l.headers?.Black||`Game ${r+1}`:l.headers?.White||`Game ${r+1}`}));return React.createElement(SectionCard,{title:"Move Quality \u2014 Deep Analysis",badge:"analyzed",delay:.3},React.createElement("div",{className:"pr-grid-2--lg"},React.createElement("div",null,React.createElement("div",{className:"pr-title--white pr-mb-3"},"Move Classification (",n.length," moves)"),React.createElement("div",{className:"pr-chart-h56"},React.createElement(ResponsiveContainer,{width:"100%",height:"100%"},React.createElement(BarChart,{data:i,layout:"vertical"},React.createElement(CartesianGrid,{strokeDasharray:"3 3"}),React.createElement(XAxis,{type:"number",tick:{fontSize:14,fill:"var(--pr-text-primary)",fontWeight:500}}),React.createElement(YAxis,{type:"category",dataKey:"name",width:90,tick:{fontSize:14,fill:"var(--pr-text-primary)",fontWeight:500}}),React.createElement(Tooltip,{contentStyle:{background:"#2a2a25",border:"1px solid rgba(255,255,255,0.15)",borderRadius:8,padding:"5px 12px",fontSize:16,boxShadow:"0 4px 12px rgba(0,0,0,0.4)"}}),React.createElement(Bar,{dataKey:"count",radius:[0,4,4,0]},i.map((l,r)=>React.createElement(Cell,{key:r,fill:l.color}))))))),React.createElement("div",null,React.createElement("div",{className:"pr-title--white pr-mb-3"},"Accuracy Per Game"),React.createElement("div",{className:"pr-chart-h56"},React.createElement(ResponsiveContainer,{width:"100%",height:"100%"},React.createElement(BarChart,{data:m},React.createElement(CartesianGrid,{strokeDasharray:"3 3"}),React.createElement(XAxis,{dataKey:"game",tick:{fontSize:14,fill:"var(--pr-text-primary)",fontWeight:500}}),React.createElement(YAxis,{domain:[40,100],tick:{fontSize:14,fill:"var(--pr-text-primary)",fontWeight:500}}),React.createElement(Tooltip,{contentStyle:{background:"#2a2a25",border:"1px solid rgba(255,255,255,0.15)",borderRadius:8,padding:"5px 12px",fontSize:16,boxShadow:"0 4px 12px rgba(0,0,0,0.4)"},formatter:(l,r,c)=>[`${l}%`,c.payload.opponent]}),React.createElement(Bar,{dataKey:"accuracy",radius:[3,3,0,0]},m.map((l,r)=>React.createElement(Cell,{key:r,fill:l.accuracy>=85?"#5DB67D":l.accuracy>=70?"#6B9FD4":l.accuracy>=55?"#D4A44B":"#CF6E6E"})))))))),React.createElement("div",{className:"pr-grid-3 pr-mt-5"},(()=>{const l=e.analyzedGames,r=Math.round(l.reduce((k,d)=>k+d.openingCpl,0)/l.length*10)/10,c=Math.round(l.reduce((k,d)=>k+d.middlegameCpl,0)/l.length*10)/10,y=Math.round(l.reduce((k,d)=>k+d.endgameCpl,0)/l.length*10)/10;return[{label:"Opening CPL",value:r,color:r<20?"#5DB67D":r<40?"#D4A44B":"#CF6E6E"},{label:"Middlegame CPL",value:c,color:c<30?"#5DB67D":c<50?"#D4A44B":"#CF6E6E"},{label:"Endgame CPL",value:y,color:y<25?"#5DB67D":y<45?"#D4A44B":"#CF6E6E"}].map(k=>React.createElement(StatBox,{key:k.label,label:k.label,value:k.value,sub:"avg centipawn loss",color:k.color}))})()))}function TimeManagement({analysis:e,games:t}){const n=Math.round(e.timeoutLosses/Math.max(1,e.losses)*100),a=Math.round(e.timeTrouble/e.total*100),s=[{range:"0-5s",count:t.filter(i=>i.finalClock!==null&&i.finalClock<5).length,color:"#CF6E6E"},{range:"5-15s",count:t.filter(i=>i.finalClock!==null&&i.finalClock>=5&&i.finalClock<15).length,color:"#D4A44B"},{range:"15-30s",count:t.filter(i=>i.finalClock!==null&&i.finalClock>=15&&i.finalClock<30).length,color:"#D4A44B"},{range:"30-60s",count:t.filter(i=>i.finalClock!==null&&i.finalClock>=30&&i.finalClock<60).length,color:"#6B9FD4"},{range:"1-2min",count:t.filter(i=>i.finalClock!==null&&i.finalClock>=60&&i.finalClock<120).length,color:"#5DB67D"},{range:"2min+",count:t.filter(i=>i.finalClock!==null&&i.finalClock>=120).length,color:"#5DB67D"}];return React.createElement(SectionCard,{title:"Time Management",delay:.2},n>30&&React.createElement("div",{className:"pr-alert pr-alert--danger pr-mb-5"},React.createElement("div",{className:"pr-row pr-mb-2"},React.createElement("span",{className:"pr-text-lg",style:{color:"#CF6E6E"}},"!"),React.createElement("span",{className:"pr-text-sm pr-font-bold",style:{color:"#CF6E6E"}},"Your #1 Improvement Area")),React.createElement("div",{className:"pr-text-sm",style:{color:"#CF6E6E"}},n,"% of your losses are from running out of time. You end ",a,"% of games with less than 15 seconds.")),React.createElement("div",{className:"pr-grid-2--lg"},React.createElement("div",null,React.createElement("div",{className:"pr-title--white pr-mb-3"},"Final Clock Time Distribution"),React.createElement("div",{className:"pr-chart-h48"},React.createElement(ResponsiveContainer,{width:"100%",height:"100%"},React.createElement(BarChart,{data:s},React.createElement(CartesianGrid,{strokeDasharray:"3 3"}),React.createElement(XAxis,{dataKey:"range",tick:{fontSize:14,fill:"var(--pr-text-primary)",fontWeight:500}}),React.createElement(YAxis,{tick:{fontSize:14,fill:"var(--pr-text-primary)",fontWeight:500}}),React.createElement(Tooltip,{contentStyle:{background:"#2a2a25",border:"1px solid rgba(255,255,255,0.15)",borderRadius:8,padding:"5px 12px",fontSize:16,boxShadow:"0 4px 12px rgba(0,0,0,0.4)"}}),React.createElement(Bar,{dataKey:"count",radius:[4,4,0,0]},s.map((i,p)=>React.createElement(Cell,{key:p,fill:i.color}))))))),React.createElement("div",{className:"pr-grid-2"},React.createElement(StatBox,{label:"Timeout Losses",value:e.timeoutLosses,sub:`${n}% of losses`,color:"#CF6E6E",stripe:"#CF6E6E"}),React.createElement(StatBox,{label:"Time Trouble",value:`${a}%`,sub:"games ending <15s",color:"#D4A44B",stripe:"#D4A44B"}),React.createElement(StatBox,{label:"Severe (<5s)",value:e.severeTimeTrouble,sub:"games",color:"#CF6E6E",stripe:"#CF6E6E"}),React.createElement(StatBox,{label:"Timeout Wins",value:e.timeoutWins,sub:"opponent flagged",color:"#5DB67D",stripe:"#5DB67D"}))))}function OpeningRepertoire({analysis:e}){const t=e.openings.map(i=>({name:i.name,wins:i.wins,losses:i.losses,draws:i.draws})),n=t.map(i=>i.wins+i.losses+i.draws),a=n.length>0?Math.max(...n,1):1,s=Math.max(220,t.length*36);return React.createElement(SectionCard,{title:"Opening Repertoire",delay:.25},React.createElement("div",{className:"pr-grid-4 pr-mb-5"},React.createElement(StatBox,{label:"As White",value:`${e.whiteWinRate}%`,sub:`${e.asWhite} games`,color:"#fff"}),React.createElement(StatBox,{label:"As Black",value:`${e.blackWinRate}%`,sub:`${e.asBlack} games`,color:"#fff"}),React.createElement(StatBox,{label:"Openings",value:e.openings.length,sub:"different",color:"#D4A44B"}),React.createElement(StatBox,{label:"Avg Length",value:e.avgMoves,sub:"moves/game",color:"#6B9FD4"})),React.createElement("div",{style:{height:s}},React.createElement(ResponsiveContainer,{width:"100%",height:"100%"},React.createElement(BarChart,{data:t,layout:"vertical"},React.createElement(CartesianGrid,{strokeDasharray:"3 3"}),React.createElement(XAxis,{type:"number",tick:{fontSize:14,fill:"var(--pr-text-primary)",fontWeight:500},allowDecimals:!1,domain:[0,Math.max(a,2)]}),React.createElement(YAxis,{type:"category",dataKey:"name",width:220,tick:{fontSize:13,fill:"var(--pr-text-body)"}}),React.createElement(Tooltip,{contentStyle:{background:"#2a2a25",border:"1px solid rgba(255,255,255,0.15)",borderRadius:8,padding:"5px 12px",fontSize:16,boxShadow:"0 4px 12px rgba(0,0,0,0.4)"}}),React.createElement(Bar,{dataKey:"wins",stackId:"a",fill:"#5DB67D",barSize:18}),React.createElement(Bar,{dataKey:"draws",stackId:"a",fill:"#8A857F",barSize:18}),React.createElement(Bar,{dataKey:"losses",stackId:"a",fill:"#CF6E6E",radius:[0,4,4,0],barSize:18})))))}function WinLossMethods({analysis:e}){const t={checkmate:"Checkmate",resigned:"Resignation",timeout:"Timeout",abandoned:"Abandoned",agreement:"Draw Agreed",checkmated:"Checkmate"},n=Object.entries(e.winMethods).map(([o,g])=>({name:t[o]||o,value:g,key:o})),a=Object.entries(e.lossMethods).map(([o,g])=>({name:t[o]||o,value:g,key:o})),s=["#5DB67D","#7DC89A","#9ED6B2","#BFE5CA"],i=["#CF6E6E","#D98B8B","#E3A8A8","#EDC5C5"],p=(o,g)=>{const f=o.reduce((v,h)=>v+h.value,0);if(f===0)return 0;const x=o.find(v=>v.key===g);return x?Math.round(x.value/f*100):0},m=p(n,"checkmate"),l=p(n,"resignation"),r=p(n,"timeout"),c=p(a,"checkmate"),y=p(a,"resignation"),k=p(a,"timeout"),d=[];c>=35?d.push(`${c}% of your losses end in checkmate \u2014 high for your level. Most players resign once down material; playing on to mate often means you're not recognising lost positions in time.`):c>=20?d.push(`${c}% of losses end in checkmate \u2014 within normal range.`):d.push(`Only ${c}% of losses end in checkmate \u2014 you resign promptly once lost.`),k>=25?d.push(`${k}% of losses are on time \u2014 a clock-management issue, not a chess issue. See Time Management above.`):k>0&&d.push(`${k}% of losses are on time \u2014 not the main loss source.`);const u=[];return l>=55?u.push(`${l}% of wins come from your opponent resigning \u2014 you build winning positions and hold them.`):m>=35&&u.push(`${m}% of wins are by checkmate \u2014 your style is sharp and tactical, finishing games on the board.`),r>=20&&u.push(`${r}% of wins are timeouts \u2014 you flag opponents who get into time pressure.`),React.createElement(SectionCard,{title:"How You Win & How You Lose",delay:.35},React.createElement("div",{className:"pr-grid-2--sm"},React.createElement("div",null,React.createElement("div",{className:"pr-text-sm pr-font-semibold pr-text-center pr-mb-3",style:{color:"#5DB67D"}},"Wins (",e.wins,")"),React.createElement("div",{className:"pr-chart-h48"},React.createElement(ResponsiveContainer,{width:"100%",height:"100%"},React.createElement(PieChart,null,React.createElement(Pie,{data:n,cx:"50%",cy:"50%",innerRadius:45,outerRadius:70,dataKey:"value",label:o=>{const g=typeof window<"u"&&window.innerWidth<640;return React.createElement("text",{x:o.x,y:o.y,fill:"var(--pr-text-primary)",textAnchor:o.textAnchor,dominantBaseline:"central",fontSize:g?11:15,fontWeight:500},`${o.name} ${(o.percent*100).toFixed(0)}%`)},labelLine:!1},n.map((o,g)=>React.createElement(Cell,{key:g,fill:s[g%s.length]}))),React.createElement(Tooltip,{contentStyle:{background:"#2a2a25",border:"1px solid rgba(255,255,255,0.15)",borderRadius:8,padding:"5px 12px",fontSize:16,boxShadow:"0 4px 12px rgba(0,0,0,0.4)"}}))))),React.createElement("div",null,React.createElement("div",{className:"pr-text-sm pr-font-semibold pr-text-center pr-mb-3",style:{color:"#CF6E6E"}},"Losses (",e.losses,")"),React.createElement("div",{className:"pr-chart-h48"},React.createElement(ResponsiveContainer,{width:"100%",height:"100%"},React.createElement(PieChart,null,React.createElement(Pie,{data:a,cx:"50%",cy:"50%",innerRadius:45,outerRadius:70,dataKey:"value",label:o=>{const g=typeof window<"u"&&window.innerWidth<640;return React.createElement("text",{x:o.x,y:o.y,fill:"var(--pr-text-primary)",textAnchor:o.textAnchor,dominantBaseline:"central",fontSize:g?11:15,fontWeight:500},`${o.name} ${(o.percent*100).toFixed(0)}%`)},labelLine:!1},a.map((o,g)=>React.createElement(Cell,{key:g,fill:i[g%i.length]}))),React.createElement(Tooltip,{contentStyle:{background:"#2a2a25",border:"1px solid rgba(255,255,255,0.15)",borderRadius:8,padding:"5px 12px",fontSize:16,boxShadow:"0 4px 12px rgba(0,0,0,0.4)"}})))))),React.createElement("div",{style:{marginTop:16}},React.createElement(DimCoach,{title:"What this measures",body:"How your wins and losses end \u2014 by checkmate, resignation, or timeout. The split reveals style (sharp/tactical vs grinding/positional) and habits (resigning too early or playing on lost positions, clock-management issues)."}),(u.length>0||d.length>0)&&React.createElement(DimCoach,{title:"Your performance",body:[...u,...d].join(" ")})))}function PsychProfile({analysis:e}){const t=(e.games||[]).slice().sort((o,g)=>{const f=o?.date||o?.headers?.Date||"",x=g?.date||g?.headers?.Date||"";return String(f).localeCompare(String(x))});let n=0,a=0,s=0,i=0,p=0,m=0,l=0,r=0;for(let o=0;o<t.length;o++){const g=t[o];if(g?.result==="loss"?(s++,i=0,s>n&&(n=s)):g?.result==="win"?(i++,s=0,i>a&&(a=i)):(s=0,i=0),o+1<t.length){const f=t[o+1]?.accuracy;typeof f=="number"&&(g?.result==="loss"?(p+=f,m++):g?.result==="win"&&(l+=f,r++))}}const c=m>=3?Math.round(p/m*10)/10:null,y=r>=3?Math.round(l/r*10)/10:null,k=c!=null&&y!=null?Math.round((y-c)*10)/10:null,d=new Set(t.map(o=>o?.date||o?.headers?.Date).filter(Boolean)).size,u=[];return e.afterLossWinRate>=55?u.push(`Strong tilt resilience \u2014 you win ${e.afterLossWinRate}% of games right after a loss (>50% is rare; most players drop 5-10pp).`):e.afterLossWinRate>=40?u.push(`Average tilt response \u2014 you win ${e.afterLossWinRate}% of post-loss games, similar to your overall rate.`):u.push(`Only ${e.afterLossWinRate}% of post-loss games are wins \u2014 tilt is real. Step away for a few minutes after losing.`),n>=5?u.push(`Worst stretch: ${n} losses in a row \u2014 that's a serious tilt spiral. The fix is usually a break, not "one more game".`):n>=3?u.push(`Worst stretch: ${n} losses in a row \u2014 survivable but a signal to pause.`):n>0&&u.push(`Worst stretch: only ${n} loss${n===1?"":"es"} back-to-back \u2014 you self-regulate well.`),a>=5?u.push(`Best stretch: ${a} wins in a row \u2014 when you're on, you ride it.`):a>=3&&u.push(`Best stretch: ${a} wins in a row.`),k!=null&&Math.abs(k)>=3?u.push(`Accuracy after a loss (${c}%) vs after a win (${y}%) differs by ${Math.abs(k)} points \u2014 ${k>0?"losses clearly drag your next game down. Reset before the rematch.":"losses sharpen your focus; wins make you sloppy. Stay disciplined when ahead."}`):k!=null&&u.push(`Accuracy is steady regardless of the previous result (${c}% after losses, ${y}% after wins) \u2014 emotionally even-keeled.`),e.longestSession>=10?u.push(`Longest session was ${e.longestSession} games in one day \u2014 fatigue territory; performance typically degrades after 6-8 rated games.`):e.longestSession>=7&&u.push(`Longest session ${e.longestSession} games \u2014 at the edge of where fatigue bites.`),e.avgMoves>=60?u.push(`Average game runs ${e.avgMoves} moves \u2014 you grind long endgames rather than ending in the middlegame.`):e.avgMoves<30&&u.push(`Average game runs ${e.avgMoves} moves \u2014 sharp, decisive style. Many games end via tactics or quick resignations.`),React.createElement(SectionCard,{title:"Mental Game & Psychology",delay:.4},React.createElement("div",{className:"pr-grid-4 pr-mb-5"},React.createElement(StatBox,{label:"After-Loss Recovery",value:`${e.afterLossWinRate}%`,sub:"win rate next game",color:e.afterLossWinRate>=40?"#5DB67D":"#CF6E6E",stripe:e.afterLossWinRate>=40?"#5DB67D":"#CF6E6E"}),React.createElement(StatBox,{label:"Worst Streak",value:n,sub:n===1?"loss in a row":"losses in a row",color:n>=4?"#CF6E6E":"#D4A44B",stripe:n>=4?"#CF6E6E":"#D4A44B"}),React.createElement(StatBox,{label:"Best Streak",value:a,sub:a===1?"win in a row":"wins in a row",color:"#5DB67D",stripe:"#5DB67D"}),React.createElement(StatBox,{label:"Longest Session",value:`${e.longestSession}`,sub:e.longestSession===1?"game in one day":"games in one day",color:e.longestSession>10?"#CF6E6E":"#D4A44B",stripe:e.longestSession>10?"#CF6E6E":"#D4A44B"})),k!=null&&Math.abs(k)>=2&&React.createElement("div",{style:{marginBottom:16,padding:"14px 18px",background:"rgba(212, 164, 75, 0.10)",border:"1px solid rgba(212, 164, 75, 0.30)",borderLeft:"4px solid #D4A44B",borderRadius:8}},React.createElement("div",{style:{fontSize:12,fontWeight:700,letterSpacing:"0.1em",textTransform:"uppercase",color:"#D4A44B",marginBottom:6}},"Mood Tax"),React.createElement("div",{style:{fontSize:16,color:"var(--pr-text-primary)",lineHeight:1.55,fontWeight:500}},"You play at ",React.createElement("strong",null,y,"%")," after a win and ",React.createElement("strong",null,c,"%")," after a loss \u2014 a ",Math.abs(k),"-point swing the previous result alone explains.")),e.marathonDays>0&&React.createElement("div",{className:"pr-alert pr-alert--warning pr-mb-3"},React.createElement("div",{className:"pr-text-sm pr-font-semibold pr-mb-1",style:{color:"#D4A44B"}},"Tilt Risk: High"),React.createElement("div",{className:"pr-text-xs",style:{color:"#D4A44B"}},"You played ",e.longestSession," games in a single session. Performance drops significantly after 6-8 rated games. Consider capping sessions at 6 games.")),React.createElement("div",null,React.createElement(DimCoach,{title:"What this measures",body:`Off-the-board patterns that shape your play \u2014 tilt recovery, win/loss streaks, accuracy after each kind of result, session length, game tempo. Across the analyzed games you played on ${d} different day${d===1?"":"s"}.`}),React.createElement(DimCoach,{title:"Your performance",body:u.join(" ")})))}function ImprovementPlan({analysis:e,stats:t}){const n=t||{rapid:{current:0},blitz:{current:0}},a=e.recommendations||[],s=e.radar||[],i=e.insights||null,p={};if(i?.dimensionInsights)for(const c of i.dimensionInsights)p[c.key]=c;if(a.length>0){const c=a.filter(u=>u.score>=60).slice(0,3),y=a.filter(u=>u.score<50).slice(0,3),k=a.find(u=>u.isPrimary),d=n.blitz?.current||n.rapid?.current||1200;return React.createElement(SectionCard,{title:"Personalized Improvement Plan",badge:"data-driven",delay:.45},i&&(i.headline||i.mainInsight)&&React.createElement("div",{className:"pr-alert--gradient pr-mb-6"},i.headline&&React.createElement("div",{className:"pr-text-lg pr-font-bold pr-text-white pr-mb-2"},i.headline),i.mainInsight&&React.createElement("div",{className:"pr-text-base",style:{color:"var(--pr-text-primary)",fontWeight:500,lineHeight:1.55}},i.mainInsight)),React.createElement("div",{className:"pr-grid-2--lg"},React.createElement("div",null,React.createElement("div",{className:"pr-text-base pr-font-bold pr-mb-3",style:{color:"#5DB67D"}},"Your Strengths"),c.length===0&&React.createElement("div",{className:"pr-text-sm",style:{color:"var(--pr-text-secondary)"}},"Analyze more games to identify strengths."),c.map(u=>React.createElement("div",{key:u.dimension,className:"pr-strength-item"},React.createElement("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"#5DB67D",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0}},React.createElement("polyline",{points:"20 6 9 17 4 12"})),React.createElement("div",null,React.createElement("div",{className:"pr-text-base pr-font-semibold",style:{color:"#9ED6B2"}},u.label," \u2014 Score: ",u.score))))),React.createElement("div",null,React.createElement("div",{className:"pr-text-base pr-font-bold pr-mb-3",style:{color:"#CF6E6E"}},"Priority Improvements"),y.length===0&&React.createElement("div",{className:"pr-text-sm",style:{color:"var(--pr-text-secondary)"}},"No significant weaknesses detected."),y.map(u=>{const o=p[u.dimension];return React.createElement("div",{key:u.dimension,className:"pr-weakness-item"},React.createElement("div",{className:"pr-row--between pr-mb-1"},React.createElement("div",{className:"pr-text-base pr-font-semibold",style:{color:"#E3A8A8"}},u.isPrimary?"! ":"",u.label," \u2014 Score: ",u.score)),React.createElement("div",{className:"pr-text-sm pr-mb-2",style:{color:"#F0D9D9",lineHeight:1.55,fontWeight:500}},o?.text||u.description))}))),k&&React.createElement("div",{className:"pr-alert--gradient pr-mt-6"},React.createElement("div",{className:"pr-text-lg pr-font-bold pr-text-white pr-mb-2"},"Focus Area: ",k.label),React.createElement("div",{className:"pr-text-base",style:{color:"var(--pr-text-primary)",fontWeight:500,lineHeight:1.55}},k.description)),i?.patterns&&i.patterns.length>0&&React.createElement("div",{className:"pr-mt-6"},React.createElement("div",{className:"pr-text-base pr-font-bold pr-mb-3",style:{color:"#D4A44B"}},"Patterns Detected"),i.patterns.map((u,o)=>React.createElement("div",{key:o,className:"pr-weakness-item",style:{background:"rgba(212,164,75,0.08)",borderColor:"rgba(212,164,75,0.15)"}},React.createElement("div",{className:"pr-text-sm",style:{color:"#F5DBA0",fontWeight:500,lineHeight:1.55}},u)))))}const m=[...s].sort((c,y)=>y.value-c.value).slice(0,3),l=[...s].sort((c,y)=>c.value-y.value).slice(0,3),r={"Time Management":"Practice with increment games. Use 80% of time in first 25 moves.","Mental Game":"Limit sessions to 6 games. Take 2-min breaks after losses.","Opening Prep":"Pick ONE opening as White, ONE vs e4, ONE vs d4. Study 10 moves deep.",Endgame:"Study K+P endings (opposition). Practice R+P vs R.",Defense:"Practice defending worse positions. Simplify to holdable endgames.",Conversion:"When ahead material, trade pieces not pawns. Simplify to won endgames.","Blunder Resist.":"Before EVERY move: does this hang a piece? Check/capture/threat?","Tactical Vision":"Do 20 tactics puzzles daily at your rating level."};return React.createElement(SectionCard,{title:"Personalized Improvement Plan",badge:e.isHeuristic?"estimated":"analyzed",delay:.45},React.createElement("div",{className:"pr-grid-2--lg"},React.createElement("div",null,React.createElement("div",{className:"pr-text-sm pr-font-semibold pr-mb-3",style:{color:"#5DB67D"}},"Your Strengths"),m.map(c=>React.createElement("div",{key:c.dim,className:"pr-strength-item"},React.createElement("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"#5DB67D",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",style:{flexShrink:0}},React.createElement("polyline",{points:"20 6 9 17 4 12"})),React.createElement("div",null,React.createElement("div",{className:"pr-text-sm pr-font-semibold",style:{color:"#9ED6B2"}},c.dim," \u2014 Score: ",c.value))))),React.createElement("div",null,React.createElement("div",{className:"pr-text-sm pr-font-semibold pr-mb-3",style:{color:"#CF6E6E"}},"Priority Improvements"),l.map(c=>React.createElement("div",{key:c.dim,className:"pr-weakness-item"},React.createElement("div",{className:"pr-text-sm pr-font-semibold pr-mb-1",style:{color:"#E3A8A8"}},"! ",c.dim," \u2014 Score: ",c.value),React.createElement("div",{className:"pr-text-xs pr-ml-2",style:{color:"#E3A8A8"}},r[c.dim]||"Focus training in this area."))))))}function CorrelationInsights({correlations:e}){return!e||e.length===0?null:React.createElement(SectionCard,{title:"Correlation Insights",badge:"data-driven",delay:.17},React.createElement("div",{className:"pr-grid-2--sm"},e.map((t,n)=>React.createElement("div",{key:n,className:"pr-correlation-card"},React.createElement("div",{className:"pr-row pr-mb-2"},React.createElement("div",{className:"pr-correlation-dot",style:{background:t.color}}),React.createElement("div",{className:"pr-text-sm pr-font-semibold pr-text-secondary"},t.title)),React.createElement("div",{className:"pr-text-xs pr-text-muted"},t.description),t.magnitude&&React.createElement("div",{className:"pr-mt-2 pr-badge--severity",style:{color:t.color}},t.magnitude,"% difference")))))}function PatternDetection({patterns:e}){if(!e||e.length===0)return null;const t={critical:"#CF6E6E",warning:"#D4A44B",info:"#6B9FD4"},n={critical:"rgba(207,110,110,0.08)",warning:"rgba(212,164,75,0.08)",info:"rgba(107,159,212,0.08)"},a={critical:"rgba(207,110,110,0.2)",warning:"rgba(212,164,75,0.2)",info:"rgba(107,159,212,0.2)"};return React.createElement(SectionCard,{title:"Pattern Detection",badge:"data-driven",delay:.19},React.createElement("div",{className:"pr-stack--xs"},e.map((s,i)=>React.createElement("div",{key:i,className:"pr-pattern-card",style:{background:n[s.severity]||n.info,borderColor:a[s.severity]||a.info}},React.createElement("div",{className:"pr-row pr-mb-1"},React.createElement("span",{className:"pr-badge--severity",style:{background:(t[s.severity]||"#6B9FD4")+"25",color:t[s.severity]||"#6B9FD4"}},s.severity),React.createElement("span",{className:"pr-text-sm pr-font-semibold pr-text-secondary"},s.title)),React.createElement("div",{className:"pr-text-xs pr-text-muted"},s.detail)))))}function ProgressTracking({history:e,analysis:t}){if(!e||e.length===0)return React.createElement(SectionCard,{title:"Progress Tracking",delay:.5},React.createElement("div",{className:"pr-text-center pr-py-6"},React.createElement("div",{className:"pr-text-lg pr-font-bold pr-mb-2",style:{color:"#5DB67D"}},"First Snapshot Recorded!"),React.createElement("div",{className:"pr-text-sm pr-text-muted"},"Analyze again in a week to see your progress over time.")));if(e.length<2)return React.createElement(SectionCard,{title:"Progress Tracking",delay:.5},React.createElement("div",{className:"pr-text-center pr-py-6"},React.createElement("div",{className:"pr-text-sm pr-text-muted"},"One snapshot recorded. Analyze again later to see progress.")));const n=e[e.length-1],a=e[e.length-2],s=n.dimensions?Object.keys(n.dimensions):[],i=e.slice(-5).map((m,l)=>({snapshot:l+1,accuracy:m.accuracy||0,score:m.lumiScore||0,date:m.date?new Date(m.date).toLocaleDateString("en-US",{month:"short",day:"numeric"}):`#${l+1}`})),p={opening:"Opening",tactical:"Tactical",endgame:"Endgame",resourcefulness:"Resourcefulness",capitalization:"Conversion",time_mgmt:"Time Management"};return React.createElement(SectionCard,{title:"Progress Tracking",badge:`${e.length} snapshots`,delay:.5},React.createElement("div",{className:"pr-grid-2--lg"},React.createElement("div",null,React.createElement("div",{className:"pr-title--white pr-mb-3"},"Changes Since Last Analysis"),React.createElement("div",{className:"pr-stack--2"},s.map(m=>{const l=n.dimensions?.[m]||0,r=a.dimensions?.[m]||0,c=l-r;return c===0?null:React.createElement("div",{key:m,className:"pr-delta-row"},React.createElement("span",{className:"pr-delta-row__label"},p[m]||m),React.createElement("div",{className:"pr-flex-1"},React.createElement("div",{className:"pr-progress-bar",style:{height:6,background:"rgba(255,255,255,0.04)"}},React.createElement("div",{className:"pr-progress-bar__fill",style:{width:`${Math.min(100,Math.max(5,l))}%`,background:c>0?"#5DB67D":"#CF6E6E"}}))),React.createElement("span",{className:"pr-delta-row__value",style:{color:c>0?"#5DB67D":"#CF6E6E"}},c>=0?"+":"",Math.round(c)))}).filter(Boolean),s.every(m=>(n.dimensions?.[m]||0)-(a.dimensions?.[m]||0)===0)&&React.createElement("div",{className:"pr-text-xs pr-text-dim pr-text-center",style:{padding:"12px 0"}},"No significant changes detected."))),React.createElement("div",null,React.createElement("div",{className:"pr-title--white pr-mb-3"},"Accuracy Trend"),React.createElement("div",{className:"pr-chart-h40"},React.createElement(ResponsiveContainer,{width:"100%",height:"100%"},React.createElement(LineChart,{data:i},React.createElement(CartesianGrid,{strokeDasharray:"3 3"}),React.createElement(XAxis,{dataKey:"date",tick:{fontSize:14,fill:"var(--pr-text-primary)",fontWeight:500}}),React.createElement(YAxis,{domain:[40,100],tick:{fontSize:14,fill:"var(--pr-text-primary)",fontWeight:500}}),React.createElement(Tooltip,{contentStyle:{background:"#2a2a25",border:"1px solid rgba(255,255,255,0.15)",borderRadius:8,padding:"5px 12px",fontSize:16,boxShadow:"0 4px 12px rgba(0,0,0,0.4)"}}),React.createElement(Line,{type:"monotone",dataKey:"accuracy",stroke:"#5DB67D",strokeWidth:2,dot:{r:4,fill:"#5DB67D"}})))))))}function AccuracyOverview({analysis:e,games:t}){if(e.isHeuristic||!e.analyzedGames?.length)return null;const n=computeAccuracyByResult(e.analyzedGames),a=computeAccuracyByMoveNumber(e.analyzedGames),s=e.analyzedGames.every(m=>!m||m.isQuickMode),i={win:"#5DB67D",draw:"#8A857F",loss:"#CF6E6E"},p={win:"When You Win",draw:"When You Draw",loss:"When You Lose"};return React.createElement(SectionCard,{title:"Accuracy Insights",badge:s?"instant":"engine",delay:.15},React.createElement("div",{className:"pr-grid-3 pr-mb-6"},["win","draw","loss"].map(m=>React.createElement("div",{key:m,className:"pr-acc-result-card"},React.createElement("div",{className:"pr-text-xs pr-text-muted pr-mb-1"},p[m]),React.createElement("div",{className:"pr-text-2xl pr-font-bold",style:{color:i[m]}},n[m]?.avg||"\u2014"),React.createElement("div",{className:"pr-text-xs pr-text-dim pr-mt-1"},n[m]?.count||0," games")))),a.length>5&&React.createElement("div",null,React.createElement("div",{className:"pr-title--white pr-mb-3"},"Accuracy by Move Number"),React.createElement("div",{className:"pr-chart-h52"},React.createElement(ResponsiveContainer,{width:"100%",height:"100%"},React.createElement(AreaChart,{data:a},React.createElement("defs",null,React.createElement("linearGradient",{id:"accGrad",x1:"0",y1:"0",x2:"0",y2:"1"},React.createElement("stop",{offset:"5%",stopColor:"#6B9FD4",stopOpacity:.3}),React.createElement("stop",{offset:"95%",stopColor:"#6B9FD4",stopOpacity:0}))),React.createElement(CartesianGrid,{strokeDasharray:"3 3"}),React.createElement(XAxis,{dataKey:"move",tick:{fontSize:14,fill:"var(--pr-text-primary)",fontWeight:500},label:{value:"Move",position:"insideBottomRight",offset:-5,fontSize:13,fill:"var(--pr-text-body)"}}),React.createElement(YAxis,{domain:[40,100],tick:{fontSize:14,fill:"var(--pr-text-primary)",fontWeight:500}}),React.createElement(Tooltip,{contentStyle:{background:"#2a2a25",border:"1px solid rgba(255,255,255,0.15)",borderRadius:8,padding:"5px 12px",fontSize:16,boxShadow:"0 4px 12px rgba(0,0,0,0.4)"},formatter:(m,l,r)=>[`${m}%`,`Move ${r.payload.move} (${r.payload.games} games)`]}),React.createElement(ReferenceLine,{y:e.avgAccuracy,stroke:"rgba(255,191,0,0.3)",strokeDasharray:"4 4"}),React.createElement(Area,{type:"monotone",dataKey:"accuracy",stroke:"#6B9FD4",strokeWidth:2,fill:"url(#accGrad)",dot:!1})))),React.createElement("div",{className:"pr-text-xs pr-text-dim pr-text-center pr-mt-1"},"Dashed line = overall average (",e.avgAccuracy,"%)")))}function GamePhaseDeepDive({analysis:e,games:t}){if(e.isHeuristic||!e.analyzedGames?.length)return null;const n=computeGamePhaseStats(e.analyzedGames),a={opening:"Opening",middlegame:"Middlegame",endgame:"Endgame"},s={opening:"\u2654",middlegame:"\u2658",endgame:"\u2656"},i={opening:"#D4A44B",middlegame:"#6B9FD4",endgame:"#5DB67D"},p=Object.entries(n).map(([m,l])=>({name:a[m],accuracy:l.accuracy,games:l.games,winRate:l.winRate,color:i[m]}));return React.createElement(SectionCard,{title:"Game Phases",delay:.2},React.createElement("div",{className:"pr-rate-tile-grid",style:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:12,marginBottom:20}},Object.entries(n).map(([m,l])=>{const r=i[m],c=l.accuracy>=80?"#5DB67D":l.accuracy>=65?"#D4A44B":"#CF6E6E",y=l.winRate>=50?"#5DB67D":"#CF6E6E";return React.createElement("div",{key:m,style:{background:"rgba(255,255,255,0.04)",borderRadius:10,padding:"16px 18px",borderTop:`3px solid ${r}`}},React.createElement("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:14}},React.createElement("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:16,fontWeight:700,color:r}},React.createElement("span",null,s[m]),React.createElement("span",null,a[m])),React.createElement("div",{style:{fontSize:14,color:"var(--pr-text-secondary)",textTransform:"uppercase",letterSpacing:"0.06em",fontWeight:600}},l.games," ",l.games===1?"game":"games")),React.createElement("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:12}},React.createElement("div",{style:{fontSize:32,fontWeight:800,color:"#fff",lineHeight:1,letterSpacing:"-0.02em"}},l.accuracy,"%"),React.createElement("div",{style:{fontSize:15,color:"var(--pr-text-primary)",fontWeight:500}},"accuracy")),React.createElement("div",{style:{display:"flex",justifyContent:"space-between",fontSize:15,fontVariantNumeric:"tabular-nums",alignItems:"baseline"}},React.createElement("span",{style:{color:"var(--pr-text-primary)",fontWeight:500}},"Win rate"),React.createElement("span",{style:{fontWeight:700,color:y,fontSize:17}},l.winRate,"%")))})),React.createElement("div",{className:"pr-chart-h44"},React.createElement(ResponsiveContainer,{width:"100%",height:"100%"},React.createElement(BarChart,{data:p},React.createElement(CartesianGrid,{strokeDasharray:"3 3"}),React.createElement(XAxis,{dataKey:"name",tick:{fontSize:14,fill:"var(--pr-text-primary)",fontWeight:500}}),React.createElement(YAxis,{domain:[0,100],tick:{fontSize:14,fill:"var(--pr-text-primary)",fontWeight:500}}),React.createElement(Tooltip,{contentStyle:{background:"#2a2a25",border:"1px solid rgba(255,255,255,0.15)",borderRadius:8,padding:"5px 12px",fontSize:16,boxShadow:"0 4px 12px rgba(0,0,0,0.4)"},formatter:(m,l)=>[`${m}%`,l==="accuracy"?"Accuracy":"Win Rate"]}),React.createElement(Bar,{dataKey:"accuracy",name:"Accuracy",radius:[4,4,0,0]},p.map((m,l)=>React.createElement(Cell,{key:l,fill:m.color}))),React.createElement(Bar,{dataKey:"winRate",name:"Win Rate",radius:[4,4,0,0],fill:"rgba(255,255,255,0.15)"})))))}function PieceAccuracyChart({analysis:e}){if(e.isHeuristic||!e.analyzedGames?.length)return null;const t=computePieceAccuracy(e.analyzedGames);if(t.length===0)return null;const n=t.reduce((m,l)=>m.accuracy>l.accuracy?m:l),a=t.reduce((m,l)=>m.accuracy<l.accuracy?m:l),s={Pawn:"Pawn \u2014 pawn breaks and structure decisions.",Knight:"Knight \u2014 outpost choice and forking geometry.",Bishop:"Bishop \u2014 long-diagonal tactics and good-vs-bad bishop trades.",Rook:"Rook \u2014 open-file timing and endgame technique.",Queen:"Queen \u2014 tactical calculation and avoiding early trades.",King:"King \u2014 endgame activity and safety calls."},i=n.accuracy-a.accuracy,p=i<4?`Your accuracy is balanced across pieces (${a.accuracy}-${n.accuracy}%). No single piece is dragging you down \u2014 your decisions are evenly weighted regardless of which piece is moving.`:`Your ${n.name.toLowerCase()} play is ${i.toFixed(1)} points sharper than your ${a.name.toLowerCase()} play (${n.accuracy}% vs ${a.accuracy}%). ${s[a.name]||`${a.name} accuracy`} is where the points are leaking.`;return React.createElement(SectionCard,{title:"Accuracy by Piece",delay:.25},React.createElement("div",{className:"pr-grid-2--lg"},React.createElement("div",null,React.createElement("div",{className:"pr-title--white pr-mb-3"},"Average Accuracy per Piece"),React.createElement("div",{className:"pr-chart-h52"},React.createElement(ResponsiveContainer,{width:"100%",height:"100%"},React.createElement(BarChart,{data:t,layout:"vertical"},React.createElement(CartesianGrid,{strokeDasharray:"3 3"}),React.createElement(XAxis,{type:"number",domain:[50,100],tick:{fontSize:14,fill:"var(--pr-text-primary)",fontWeight:500}}),React.createElement(YAxis,{type:"category",dataKey:"name",width:65,tick:{fontSize:14,fill:"var(--pr-text-primary)",fontWeight:500}}),React.createElement(Tooltip,{contentStyle:{background:"#2a2a25",border:"1px solid rgba(255,255,255,0.15)",borderRadius:8,padding:"5px 12px",fontSize:16,boxShadow:"0 4px 12px rgba(0,0,0,0.4)"},formatter:(m,l,r)=>[`${m}% (${r.payload.moves} moves)`,r.payload.name]}),React.createElement(Bar,{dataKey:"accuracy",radius:[0,4,4,0]},t.map((m,l)=>React.createElement(Cell,{key:l,fill:m.color}))))))),React.createElement("div",{className:"pr-stack--xs"},React.createElement("div",{className:"pr-title--white pr-mb-3"},"Moves per Piece"),t.map(m=>{const l=Math.max(...t.map(c=>c.moves)),r=Math.round(m.moves/l*100);return React.createElement("div",{key:m.piece,className:"pr-piece-bar"},React.createElement("div",{className:"pr-piece-bar__label"},m.name),React.createElement("div",{className:"pr-piece-bar__track"},React.createElement("div",{className:"pr-piece-bar__fill",style:{width:`${r}%`,background:m.color}}),React.createElement("span",{className:"pr-piece-bar__count"},m.moves)))}),React.createElement("div",{className:"pr-grid-2 pr-mt-4"},React.createElement("div",{className:"pr-piece-best"},React.createElement("div",{className:"pr-text-xs",style:{color:"#5DB67D"}},"Best Piece"),React.createElement("div",{className:"pr-text-sm pr-font-bold",style:{color:"#9ED6B2"}},n.name," (",n.accuracy,"%)")),React.createElement("div",{className:"pr-piece-worst"},React.createElement("div",{className:"pr-text-xs",style:{color:"#CF6E6E"}},"Weakest Piece"),React.createElement("div",{className:"pr-text-sm pr-font-bold",style:{color:"#E3A8A8"}},a.name," (",a.accuracy,"%)"))))),React.createElement("div",{style:{marginTop:16}},React.createElement(DimCoach,{title:"What this measures",body:"How accurately you move each piece type. Big gaps point to where your geometry breaks down \u2014 rook accuracy reflects endgame technique, knight reflects positional vision, queen reflects tactical calculation."}),React.createElement(DimCoach,{title:"Your performance",body:p})))}function CastlingAnalysis({analysis:e,games:t}){if(e.isHeuristic||!e.analyzedGames?.length)return null;const n=computeCastlingStats(e.analyzedGames);if(n.total===0)return null;const a=r=>{const c=r.win+r.loss+r.draw;return c>0?Math.round(r.win/c*100):0},s=[n.kingSide>0&&{name:"Kingside (O-O)",value:n.kingSide,fill:"#6B9FD4"},n.queenSide>0&&{name:"Queenside (O-O-O)",value:n.queenSide,fill:"#D4A44B"},n.noCastle>0&&{name:"No Castle",value:n.noCastle,fill:"#8A857F"}].filter(Boolean),i=a({win:n.castleResults.kingside.win+n.castleResults.queenside.win,loss:n.castleResults.kingside.loss+n.castleResults.queenside.loss,draw:n.castleResults.kingside.draw+n.castleResults.queenside.draw}),p=a(n.castleResults.none),m=i-p,l=[];return n.castledPct>=90?l.push(`You castle in ${n.castledPct}% of games \u2014 strong king-safety habit.`):n.castledPct>=70?l.push(`You castle in ${n.castledPct}% of games \u2014 acceptable, but the ${100-n.castledPct}% where you skip it are where the king is exposed.`):l.push(`You castle in only ${n.castledPct}% of games \u2014 the king stays in the centre too often. Aim for >85%.`),n.avgCastleMove&&(n.avgCastleMove<=9?l.push(`Average castle move ${n.avgCastleMove} \u2014 early, by-the-book opening play.`):n.avgCastleMove<=13?l.push(`Average castle move ${n.avgCastleMove} \u2014 on schedule.`):l.push(`Average castle move ${n.avgCastleMove} \u2014 late castling exposes you to king-side attacks. Aim for move 7-10.`)),m>=10?l.push(`You win ${i}% when you castle vs ${p}% when you don't \u2014 clearly better when the king is safe.`):m<=-10?l.push(`You actually win more often when you DON'T castle (${p}% vs ${i}% castled). That's unusual \u2014 probably small sample noise on the no-castle games, but worth watching.`):l.push(`You win at a similar rate whether you castle or not (${i}% castled vs ${p}% not) \u2014 in this sample, castling isn't what decides games.`),React.createElement(SectionCard,{title:"Castling Analysis",delay:.3},React.createElement("div",{className:"pr-grid-2--lg"},React.createElement("div",null,React.createElement("div",{className:"pr-title--white pr-mb-3"},"Castling Frequency"),React.createElement("div",{className:"pr-chart-h48"},React.createElement(ResponsiveContainer,{width:"100%",height:"100%"},React.createElement(PieChart,null,React.createElement(Pie,{data:s,cx:"50%",cy:"50%",innerRadius:40,outerRadius:70,dataKey:"value",label:r=>{const c=typeof window<"u"&&window.innerWidth<640,y=c?r.name.replace(/\s*\([^)]*\)/g,""):r.name;return React.createElement("text",{x:r.x,y:r.y,fill:"var(--pr-text-primary)",textAnchor:r.textAnchor,dominantBaseline:"central",fontSize:c?11:15,fontWeight:500},`${y} ${(r.percent*100).toFixed(0)}%`)},labelLine:!1},s.map((r,c)=>React.createElement(Cell,{key:c,fill:r.fill}))),React.createElement(Tooltip,{contentStyle:{background:"#2a2a25",border:"1px solid rgba(255,255,255,0.15)",borderRadius:8,padding:"5px 12px",fontSize:16,boxShadow:"0 4px 12px rgba(0,0,0,0.4)"}}))))),React.createElement("div",{className:"pr-grid-2"},React.createElement(StatBox,{label:"Castled",value:`${n.castledPct}%`,sub:`${n.kingSide+n.queenSide} of ${n.total} games`,color:"#6B9FD4",stripe:"#6B9FD4"}),React.createElement(StatBox,{label:"Avg Castle Move",value:n.avgCastleMove||"\u2014",sub:"move number",color:"#D4A44B",stripe:"#D4A44B"}),React.createElement(StatBox,{label:"Win% with Castle",value:`${i}%`,sub:"when castled",color:"#5DB67D",stripe:"#5DB67D"}),React.createElement(StatBox,{label:"Win% without",value:`${p}%`,sub:"when not castled",color:"#CF6E6E",stripe:"#CF6E6E"}))),React.createElement("div",{style:{marginTop:16}},React.createElement(DimCoach,{title:"What this measures",body:"How often you castle, on which side, when (move number), and whether castling correlates with winning. Late or skipped castling exposes the king; a big win-rate gap between castled and uncastled games shows how much king safety drives your results."}),React.createElement(DimCoach,{title:"Your performance",body:l.join(" ")})))}function OpeningDeepDive({analysis:e,games:t}){if(e.isHeuristic||!e.analyzedGames?.length)return null;const n=computeOpeningDeepDive(e.analyzedGames);return n.length===0?null:React.createElement(SectionCard,{title:"Opening Performance",badge:"detailed",delay:.3},React.createElement("div",{className:"pr-overflow-x"},React.createElement("table",{className:"pr-table"},React.createElement("thead",null,React.createElement("tr",null,React.createElement("th",null,"Opening"),React.createElement("th",{className:"text-center"},"Games"),React.createElement("th",{className:"text-center"},"Win%"),React.createElement("th",{className:"text-center"},"Accuracy"),React.createElement("th",{className:"text-center"},"Book Depth"),React.createElement("th",null,"Result"))),React.createElement("tbody",null,n.map((a,s)=>React.createElement("tr",{key:s},React.createElement("td",null,React.createElement("div",{className:"pr-table__name"},a.name)),React.createElement("td",{className:"text-center"},React.createElement("span",{className:"pr-text-xs pr-text-muted"},a.total)),React.createElement("td",{className:"text-center"},React.createElement("span",{className:"pr-text-xs pr-font-semibold",style:{color:a.winRate>=55?"#5DB67D":a.winRate>=45?"#D4A44B":"#CF6E6E"}},a.winRate,"%")),React.createElement("td",{className:"text-center"},React.createElement("span",{className:"pr-text-xs pr-font-semibold",style:{color:a.avgAccuracy>=80?"#5DB67D":a.avgAccuracy>=70?"#6B9FD4":"#D4A44B"}},a.avgAccuracy)),React.createElement("td",{className:"text-center"},React.createElement("span",{className:"pr-text-xs pr-text-muted"},a.avgBookDepth!==null?`${a.avgBookDepth} moves`:"\u2014")),React.createElement("td",null,React.createElement("div",{className:"pr-row",style:{gap:6}},React.createElement("span",{className:"pr-text-xs",style:{color:"#5DB67D"}},a.wins,"W"),React.createElement("span",{className:"pr-text-xs pr-text-dim"},a.draws,"D"),React.createElement("span",{className:"pr-text-xs",style:{color:"#CF6E6E"}},a.losses,"L")))))))))}function MoveQualityDistribution({analysis:e}){if(e.isHeuristic||!e.analyzedGames?.length)return null;const t=e.totalClassifications||{},n=Object.values(t).reduce((s,i)=>s+i,0);if(n===0)return null;const a=[{key:"brilliant",label:"Brilliant",color:"#14e6e6"},{key:"best",label:"Best",color:"#7bcc18"},{key:"excellent",label:"Excellent",color:"#7bcc18"},{key:"good",label:"Good",color:"#088a28"},{key:"book",label:"Book",color:"#d5a47d"},{key:"inaccuracy",label:"Inaccuracy",color:"#ddd015"},{key:"mistake",label:"Mistake",color:"#e5820d"},{key:"blunder",label:"Blunder",color:"#d44242"}].map(s=>({...s,count:t[s.key]||0,pct:Math.round((t[s.key]||0)/n*1e3)/10})).filter(s=>s.count>0);return React.createElement(SectionCard,{title:"Move Quality Distribution",delay:.2},React.createElement("div",{className:"pr-grid-2--lg"},React.createElement("div",{className:"pr-stack--2"},a.map(s=>React.createElement("div",{key:s.key,className:"pr-quality-row"},React.createElement("div",{className:"pr-quality-row__label",style:{color:s.color}},s.label),React.createElement("div",{className:"pr-quality-row__bar"},React.createElement("div",{style:{height:"100%",borderRadius:"var(--lumi-radius-xs)",width:`${Math.max(2,s.pct)}%`,background:s.color,opacity:.7}}),React.createElement("span",{className:"pr-piece-bar__pct"},s.pct,"%"),React.createElement("span",{className:"pr-piece-bar__count",style:{color:"var(--lumi-text-muted)"}},s.count.toLocaleString()))))),React.createElement("div",{className:"pr-row--center"},React.createElement("div",{className:"pr-chart-h56 pr-w-full"},React.createElement(ResponsiveContainer,{width:"100%",height:"100%"},React.createElement(PieChart,null,React.createElement(Pie,{data:a.slice(0,6),cx:"50%",cy:"50%",innerRadius:50,outerRadius:80,dataKey:"count",label:s=>React.createElement("text",{x:s.x,y:s.y,fill:"var(--pr-text-primary)",textAnchor:s.textAnchor,dominantBaseline:"central",fontSize:15,fontWeight:500},`${s.payload.pct}%`),labelLine:!1},a.slice(0,6).map((s,i)=>React.createElement(Cell,{key:i,fill:s.color}))),React.createElement(Tooltip,{contentStyle:{background:"#2a2a25",border:"1px solid rgba(255,255,255,0.15)",borderRadius:8,padding:"5px 12px",fontSize:16,boxShadow:"0 4px 12px rgba(0,0,0,0.4)"},formatter:(s,i,p)=>[`${s.toLocaleString()} (${p.payload.pct}%)`,p.payload.label]})))))))}function GameDrillDown({gameAnalysis:e,gameMetadata:t,onBack:n}){if(!e)return null;if(e.isQuickMode)return React.createElement("div",{className:"pr-container",style:{paddingTop:24}},React.createElement("button",{onClick:n,className:"pr-drilldown-back--blue"},"\u2190 Back to report"),React.createElement(SectionCard,{title:"Game Details"},React.createElement("div",{className:"pr-text-center",style:{padding:"32px 0"}},React.createElement("div",{className:"pr-text-sm pr-text-muted pr-mb-2"},"This game was analyzed in Instant mode (Chess.com API accuracy)."),React.createElement("div",{className:"pr-text-xs pr-text-dim"},"Run a deep analysis (depth 5+) to see the evaluation graph and per-move breakdown."))));const{moveAnalysis:a,playerAccuracy:s,opponentAccuracy:i,headers:p}=e,m=a.map((r,c)=>({move:c+1,moveLabel:r.moveNumber,label:`${r.moveNumber}${r.turn==="w"?".":"..."} ${r.san}`,eval:Math.max(-500,Math.min(500,r.whiteEval))/100,cpl:r.isPlayerMove?r.cpl:null,classification:r.classification,san:r.san,turn:r.turn,isPlayer:r.isPlayerMove})),l=a.filter(r=>r.isPlayerMove);return React.createElement("div",{className:"pr-stack pr-animate-section"},React.createElement("button",{onClick:n,className:"pr-drilldown-back"},"\u2190 Back to Report"),React.createElement(SectionCard,null,React.createElement("div",{className:"pr-row--between pr-mb-4"},React.createElement("div",null,React.createElement("h2",{className:"pr-heading--lg"},p?.White||"?"," vs ",p?.Black||"?"),React.createElement("div",{className:"pr-text-xs pr-text-muted pr-mt-1"},p?.Date," \xB7 ",p?.TimeControl," \xB7 ",p?.Result)),React.createElement("div",{className:"pr-row--4"},React.createElement("div",{className:"pr-text-center"},React.createElement("div",{className:"pr-text-xs pr-text-muted"},"Your Accuracy"),React.createElement("div",{className:"pr-text-2xl pr-font-extrabold",style:{color:"#5DB67D"}},s,"%")),React.createElement("div",{className:"pr-text-center"},React.createElement("div",{className:"pr-text-xs pr-text-muted"},"Opponent"),React.createElement("div",{className:"pr-text-2xl pr-font-extrabold pr-text-dim"},i,"%")))),React.createElement("div",{className:"pr-title--white pr-mb-3"},"Evaluation Graph"),React.createElement("div",{className:"pr-chart-h48 pr-mb-6"},React.createElement(ResponsiveContainer,{width:"100%",height:"100%"},React.createElement(AreaChart,{data:m},React.createElement("defs",null,React.createElement("linearGradient",{id:"evalGrad",x1:"0",y1:"0",x2:"0",y2:"1"},React.createElement("stop",{offset:"0%",stopColor:"#5DB67D",stopOpacity:.35}),React.createElement("stop",{offset:"50%",stopColor:"#5DB67D",stopOpacity:0}),React.createElement("stop",{offset:"50%",stopColor:"#CF6E6E",stopOpacity:0}),React.createElement("stop",{offset:"100%",stopColor:"#CF6E6E",stopOpacity:.35}))),React.createElement(CartesianGrid,{strokeDasharray:"3 3"}),React.createElement(XAxis,{dataKey:"move",tick:{fontSize:14,fill:"var(--pr-text-primary)",fontWeight:500},tickFormatter:r=>Math.ceil(r/2),interval:Math.max(1,Math.floor(m.length/20))}),React.createElement(YAxis,{domain:[-5,5],tick:{fontSize:14,fill:"var(--pr-text-primary)",fontWeight:500},tickFormatter:r=>r>0?`+${r}`:`${r}`}),React.createElement(ReferenceLine,{y:0,stroke:"rgba(255,255,255,0.15)",strokeWidth:1.5}),React.createElement(Tooltip,{contentStyle:{background:"#2a2a25",border:"1px solid rgba(255,255,255,0.15)",borderRadius:8,padding:"5px 12px",fontSize:16,boxShadow:"0 4px 12px rgba(0,0,0,0.4)"},formatter:(r,c,y)=>{const k=y.payload;return[`${r>0?"+":""}${r.toFixed(1)}`,k.label]}}),React.createElement(Area,{type:"monotone",dataKey:"eval",stroke:"rgba(255,255,255,0.5)",fill:"url(#evalGrad)",strokeWidth:1.5,dot:!1})))),React.createElement("div",{className:"pr-title--white pr-mb-3"},"Key Moments"),React.createElement("div",{className:"pr-moments pr-stack--1"},l.filter(r=>r.cpl>20).sort((r,c)=>c.cpl-r.cpl).slice(0,10).map((r,c)=>React.createElement("div",{key:c,className:"pr-moment-row",style:{background:CLASSIFICATION_COLORS[r.classification]+"10"}},React.createElement("span",{className:"pr-text-xs pr-text-dim",style:{fontFamily:"monospace",width:32}},r.moveNumber,"."),React.createElement("span",{className:"pr-text-sm pr-font-semibold pr-text-white",style:{width:64}},r.san),React.createElement("span",{className:"pr-badge--pill",style:{background:CLASSIFICATION_COLORS[r.classification]+"25",color:CLASSIFICATION_COLORS[r.classification]}},CLASSIFICATION_LABELS[r.classification]),React.createElement("span",{className:"pr-text-xs pr-text-dim pr-ml-auto"},"-",Math.round(r.cpl)," cp"))),l.filter(r=>r.cpl>20).length===0&&React.createElement("div",{className:"pr-text-sm pr-text-muted pr-text-center",style:{padding:"16px 0"}},"No significant inaccuracies found \u2014 great game!"))))}function GamesList({analysis:e,games:t,onSelectGame:n}){const a=!e.isHeuristic&&e.analyzedGames&&e.analyzedGames.length>0,s=a&&e.analyzedGames.every(i=>!i||i.isQuickMode);return React.createElement(SectionCard,{title:"Game-by-Game Results",badge:a?s?"instant":"analyzed":null,delay:.5},React.createElement("div",{className:"pr-game-list pr-stack--1"},t.map((i,p)=>{const m=a?e.analyzedGames[p]:null,l=m?m.playerAccuracy:i.accuracy,r=i.result==="win"?"W":i.result==="loss"?"L":"D",c=i.result==="win"?"#5DB67D":i.result==="loss"?"#CF6E6E":"#8A857F",y=i.color==="white"?i.black:i.white;return React.createElement("div",{key:p,className:`pr-game-list__item ${a?"pr-game-list__item--clickable":""}`,onClick:()=>a&&m&&n(p)},React.createElement("span",{className:"pr-game-list__result",style:{background:c}},r),React.createElement("div",{className:"pr-game-list__info"},React.createElement("div",{className:"pr-game-list__name"},y),React.createElement("div",{className:"pr-game-list__detail"},i.opening," \xB7 ",i.moves," moves")),l!==null&&React.createElement("div",{className:"pr-game-list__acc"},React.createElement("div",{className:"pr-text-sm pr-font-bold",style:{color:l>=85?"#5DB67D":l>=70?"#6B9FD4":"#D4A44B"}},l,"%"),React.createElement("div",{className:"pr-meta--10"},"Accuracy")),a&&m&&React.createElement("span",{className:"pr-text-xs pr-text-dim"},"\u2192"))})))}function ChessProfileReport(){const[e,t]=useReducer(reducer,void 0,()=>{try{const u=location.pathname||"";if(/^\/profile-report\/[^/?#]+/.test(u)||new URLSearchParams(location.search).get("id"))return{...initialState,phase:"fetching"}}catch{}let d=null;try{const u=sessionStorage.getItem("lumichess_pr_resume");u&&(d=JSON.parse(u))}catch{}if(d&&d.username)return{...initialState,phase:"fetching",username:d.username,platform:d.platform||initialState.platform,format:d.format||initialState.format,gameCount:d.gameCount||initialState.gameCount};try{const u=localStorage.getItem("lumichess_pr_last_form");if(u){const o=JSON.parse(u);return{...initialState,platform:o.platform||initialState.platform,username:o.username||initialState.username,format:o.format||initialState.format,gameCount:o.gameCount||initialState.gameCount,depth:o.depth||initialState.depth}}}catch{}return initialState});useEffect(()=>{try{localStorage.setItem("lumichess_pr_last_form",JSON.stringify({platform:e.platform,username:e.username,format:e.format,gameCount:e.gameCount,depth:e.depth}))}catch{}},[e.platform,e.username,e.format,e.gameCount,e.depth]);const n=useRef(null),a=useRef(!1);useEffect(()=>{if(a.current||e.signedIn===null)return;let d=null;try{const o=(location.pathname||"").match(/^\/profile-report\/([^/?#]+)/);o&&(d=decodeURIComponent(o[1])),d||(d=new URLSearchParams(location.search).get("id"))}catch{}d&&(a.current=!0,s(d))},[e.signedIn]),useEffect(()=>{(async()=>{try{const d=await window.LumiProfile?.Auth?.getProfile?.();t({type:"SET_SIGNED_IN",value:!!d})}catch{t({type:"SET_SIGNED_IN",value:!1})}})()},[]),useEffect(()=>{(async()=>{try{try{if(sessionStorage.getItem("lumichess_pr_resume"))return;const g=location.pathname||"";if(/^\/profile-report\/[^/?#]+/.test(g)||new URLSearchParams(location.search).get("id"))return}catch{}await ProfileCache.init();const d=await ProfileCache.getLastUsed();if(d){const{platform:g,username:f}=d,x=await ProfileCache.getFullReport(g,f);if(x){t({type:"RESTORE_STATE",p:{...x,platform:g,username:f}});return}}const u=[];try{const g=await window.LumiProfile?.Auth?.getProfile?.();g?.chess_com_username&&u.push({platform:"chesscom",username:g.chess_com_username}),g?.lichess_username&&u.push({platform:"lichess",username:g.lichess_username})}catch{}if(u.length===0)try{const g=localStorage.getItem("lumichess_accounts_local");if(g){const f=JSON.parse(g);Array.isArray(f)&&u.push(...f)}}catch{}const o=u.find(g=>g.platform==="chesscom")||u[0];o&&o.username&&(t({type:"SET_PLATFORM",value:o.platform}),t({type:"SET_USERNAME",value:o.username}))}catch(d){console.warn("Restore failed:",d.message)}})()},[]),useEffect(()=>{(async()=>{try{const d=window.LumiProfile?.ProfileReportHistory;if(!d)return;const u=await d.list(20);u&&u.length>0&&t({type:"SET_HISTORY_LIST",rows:u})}catch(d){console.warn("History list failed:",d.message)}})()},[]);const s=useCallback(async d=>{try{const u=window.LumiProfile?.ProfileReportHistory;if(!u||!d){t({type:"RESET"});return}let o=null;if(d.length<36)try{const f=(await u.list(50)||[]).find(x=>String(x.id).startsWith(d));f&&(o=await u.get(f.id))}catch{}else o=await u.get(d);if(!o){try{window.history.replaceState(null,"","/profile-report")}catch{}t({type:"RESET"});return}t({type:"LOAD_HISTORICAL_REPORT",p:{id:o.id,platform:o.platform,username:o.username,format:o.format,depth:o.depth,gameCount:o.game_count,aggregates:o.aggregates,insights:o.insights}})}catch(u){console.warn("History load failed:",u.message)}},[]);useEffect(()=>{const d=()=>{e.selectedGameIdx!==null&&t({type:"BACK_TO_REPORT"})};return window.addEventListener("popstate",d),()=>window.removeEventListener("popstate",d)},[e.selectedGameIdx]);const i=useRef(!1),p=useRef(null);useEffect(()=>{if(i.current||e.signedIn===null)return;try{if(/^\/profile-report\/[^/?#]+/.test(location.pathname)||new URLSearchParams(location.search).get("id"))return}catch{}let d=null;try{d=sessionStorage.getItem("lumichess_pr_resume")}catch{}if(!d)return;let u;try{u=JSON.parse(d)}catch{return}sessionStorage.removeItem("lumichess_pr_resume"),i.current=!0,setTimeout(()=>{const o=p.current;o&&o(u)},50)},[e.signedIn]);const m=useCallback(async(d=null)=>{t({type:"START_FETCH"});const u=(d?.username||e.username).trim().toLowerCase(),o=d?.depth||e.depth,g=d?.platform||e.platform,f=d?.gameCount||e.gameCount,x=d?.format||e.format;let v=e.signedIn;if(v===null){try{v=!!await window.LumiProfile?.Auth?.getProfile?.()}catch{v=!1}t({type:"SET_SIGNED_IN",value:v})}try{await ProfileCache.init()}catch(C){console.warn("Cache init failed:",C.message)}let h=null,S=null;if(g==="lichess"){try{const b=await fetchLichessProfile(u);h=b.profile,S=b.stats}catch(b){t({type:"FETCH_FALLBACK",profile:null,stats:null,error:b.message||"Could not load Lichess profile."});return}let C=[];try{C=await fetchLichessGames(u,f,x,b=>{t({type:"ANALYSIS_PROGRESS",progress:{currentGame:`Streaming games... (${b})`}})})}catch(b){t({type:"FETCH_FALLBACK",profile:h,stats:S,error:b.message||"Could not load Lichess games."});return}if(C.length===0){t({type:"FETCH_FALLBACK",profile:h,stats:S,error:`No games found for "${u}" on Lichess.`});return}const M=C.map(b=>lichessGameToMetadata(b,u)).filter(Boolean);if(t({type:"FETCH_SUCCESS",profile:h,stats:S,games:M,apiGames:C}),!v){try{sessionStorage.setItem("lumichess_pr_resume",JSON.stringify({username:u,platform:g,format:x,gameCount:f}))}catch{}t({type:"FREE_TIER_COMPLETE"});return}try{const b=window.LumiProfile?.OpeningBook;b&&!b.loaded&&await b.load()}catch(b){console.warn("Opening book load failed:",b.message)}let R=null;try{R=new StockfishEngine,await R.init(),n.current=R}catch{t({type:"ENGINE_FALLBACK",error:"Analysis engine failed to load. Showing estimated analysis."});return}for(let b=0;b<C.length;b++){const w=M[b];if(!w){t({type:"GAME_ANALYZED",result:null});continue}const D=w.lichessId||`lichess_${b}`;t({type:"ANALYSIS_PROGRESS",progress:{gameIndex:b,moveIndex:0,totalGames:C.length,totalMoves:0,currentGame:`${w.white} vs ${w.black}`}});let N=null;if(w.pgn)try{N=await analyzeGameWithEngine(w.pgn,R,o,(T,E)=>{t({type:"ANALYSIS_PROGRESS",progress:{moveIndex:T,totalMoves:E,gameIndex:b,totalGames:C.length,currentGame:`${w.white} vs ${w.black}`}})},u)}catch(T){console.warn(`Failed to analyze Lichess game ${b}:`,T.message)}N&&await ProfileCache.saveGameAnalysis("lichess",D,o,N),t({type:"GAME_ANALYZED",result:N})}R.destroy(),n.current=null}else{try{const D=await fetch(`https://api.chess.com/pub/player/${u}`,{headers:{Accept:"application/json"}});if(!D.ok){t({type:"FETCH_FALLBACK",profile:null,stats:null,error:D.status===404?`User "${u}" not found on Chess.com. Check the spelling.`:`Chess.com API returned ${D.status}. Try again later.`});return}const N=await D.json();h={username:N.username||u,country:N.country?.split("/").pop()||"??",status:N.status||"basic",joined:N.joined||0,lastOnline:N.last_online||0,followers:N.followers||0,league:N.league||"",title:N.title||""};const T=await fetch(`https://api.chess.com/pub/player/${u}/stats`,{headers:{Accept:"application/json"}});if(T.ok){const E=await T.json();S={rapid:{current:E.chess_rapid?.last?.rating||0,best:E.chess_rapid?.best?.rating||0,wins:E.chess_rapid?.record?.win||0,losses:E.chess_rapid?.record?.loss||0,draws:E.chess_rapid?.record?.draw||0},blitz:{current:E.chess_blitz?.last?.rating||0,best:E.chess_blitz?.best?.rating||0,wins:E.chess_blitz?.record?.win||0,losses:E.chess_blitz?.record?.loss||0,draws:E.chess_blitz?.record?.draw||0},bullet:{current:E.chess_bullet?.last?.rating||0,best:E.chess_bullet?.best?.rating||0,wins:E.chess_bullet?.record?.win||0,losses:E.chess_bullet?.record?.loss||0,draws:E.chess_bullet?.record?.draw||0},daily:{current:E.chess_daily?.last?.rating||0,best:E.chess_daily?.best?.rating||0,wins:E.chess_daily?.record?.win||0,losses:E.chess_daily?.record?.loss||0,draws:E.chess_daily?.record?.draw||0},tactics:{highest:E.tactics?.highest?.rating||0},puzzleRush:{best:E.puzzle_rush?.best?.score||0}}}}catch(D){t({type:"FETCH_FALLBACK",profile:null,stats:null,error:`Network error: ${D.message}. Check your internet connection.`});return}const C=x;let M=[];try{M=await fetchChessComGames(u,f,C)}catch(D){console.warn("Game fetch failed:",D.message)}if(M.length===0){const D=C==="all"?"":` ${C}`;t({type:"FETCH_FALLBACK",profile:h,stats:S,error:`No${D} games found for "${h?.username||u}".`});return}const R=M.map(D=>apiGameToMetadata(D,u));if(t({type:"FETCH_SUCCESS",profile:h,stats:S,games:R,apiGames:M}),!v){try{sessionStorage.setItem("lumichess_pr_resume",JSON.stringify({username:u,platform:g,format:x,gameCount:f}))}catch{}t({type:"FREE_TIER_COMPLETE"});return}try{const D=window.LumiProfile?.OpeningBook;D&&!D.loaded&&await D.load()}catch(D){console.warn("Opening book load failed:",D.message)}const b=M;let w=null;try{w=new StockfishEngine,await w.init(),n.current=w}catch{t({type:"ENGINE_FALLBACK",error:"Analysis engine failed to load. Showing estimated analysis."});return}for(let D=0;D<b.length;D++){const N=b[D],T=parsePGNHeaders(N.pgn),E=`${u}_${T.Date||""}_${D}`.replace(/[^a-zA-Z0-9_]/g,"");t({type:"ANALYSIS_PROGRESS",progress:{gameIndex:D,moveIndex:0,totalGames:b.length,totalMoves:0,currentGame:`${T.White||"?"} vs ${T.Black||"?"}`}});try{const L=await analyzeGameWithEngine(N.pgn,w,o,(_,I)=>{t({type:"ANALYSIS_PROGRESS",progress:{moveIndex:_,totalMoves:I,gameIndex:D,totalGames:b.length,currentGame:`${T.White||"?"} vs ${T.Black||"?"}`}})},u);L&&await ProfileCache.saveGameAnalysis("chesscom",E,o,L),t({type:"GAME_ANALYZED",result:L})}catch(L){console.warn(`Failed to analyze game ${D}:`,L.message),t({type:"GAME_ANALYZED",result:null})}}w.destroy(),n.current=null}t({type:"ANALYSIS_COMPLETE",correlations:null,patterns:null,progressHistory:[]})},[e.username,e.depth,e.format,e.platform,e.gameCount,e.signedIn]);useEffect(()=>{p.current=m},[m]);const l=useMemo(()=>{if(e.phase!=="complete")return null;if(e._loadedAnalysis)return e._loadedAnalysis;if(e.isHeuristic)return analyzeGamesHeuristic(e.games,e.stats);const d=buildAnalysisFromEngine(e.analyzedGames,e.games,e.stats);d.correlations=computeCorrelations(e.analyzedGames,e.games),d.patterns=detectPatterns(e.analyzedGames,e.games);const u=e.analyzedGames.filter(o=>o!==null);if(u.length>0){const o=u.map((g,f)=>convertToCoachingRecord(g,e.games[f])).filter(Boolean);if(o.length>0){const g=e.stats?.blitz?.current||e.stats?.rapid?.current||1200;try{const f=computeInlineSkillProfile(o,g);d.skillProfile=f,d.recommendations=computeInlineRecommendations(f,g);const x=window.LumiProfile?.CoachingInsights;if(x)try{d.insights=x.generate(o,f,g)}catch(v){console.warn("CoachingInsights.generate failed:",v.message)}}catch(f){console.warn("SkillProfile computation failed:",f.message)}}}return d},[e.phase,e.isHeuristic,e.analyzedGames,e.games,e.stats,e._loadedAnalysis,e._loadedReportId]),[r,c]=useState([]);useEffect(()=>{if(e.phase!=="complete"||!l||e.isHeuristic||e._loadedReportId)return;const d=e.platform,u=e.username.trim().toLowerCase();(async()=>{try{await ProfileCache.init();const o={};l.skillProfile?.dimensions?Object.entries(l.skillProfile.dimensions).forEach(([v,h])=>{o[v]=h.score||0}):l.radar&&l.radar.forEach(v=>{o[v.dim]=v.value});const g={accuracy:l.avgAccuracy,lumiScore:l.lumiScore,dimensions:o};await ProfileCache.appendHistory(d,u,g),await ProfileCache.saveSnapshot(d,u,g),await ProfileCache.saveFullReport(d,u,{profile:e.profile,stats:e.stats,games:e.games,analyzedGames:e.analyzedGames,depth:e.depth,format:e.format,gameCount:e.gameCount,correlations:e.correlations,patterns:e.patterns}),await ProfileCache.saveLastUsed(d,u);const f=await ProfileCache.getHistory(d,u);c(f);const x=window.LumiProfile?.ProfileReportHistory;if(x){const v=(e.games||[]).map(R=>({headers:R?.headers||null,url:R?.url||null,platform:R?.platform||null,timeControl:R?.timeControl||null,opening:R?.opening||null,date:R?.date||null,finalClock:R?.finalClock??null,result:R?.result??null,method:R?.method??null,moves:R?.moves??null,accuracy:R?.accuracy??null,color:R?.color??null,eco:R?.eco??null,timeClass:R?.timeClass??null,wRating:R?.wRating??null,bRating:R?.bRating??null,white:R?.white??null,black:R?.black??null})),{insights:h,...S}=l,C={...S,profile:e.profile||null,stats:e.stats||null,games:v},M=await x.save({platform:d,username:u,format:e.format,gameCount:e.gameCount,depth:e.depth,aggregates:C,insights:h||null});if(M?.id)try{window.LumiProfile?.Analytics?.track("profile_report_created",{platform:d,format:e.format,game_count:e.gameCount,depth:e.depth})}catch{}if(M?.id){const R=String(M.id).slice(0,8);try{window.history.replaceState(null,"",`/profile-report/${R}`)}catch{}}}}catch(o){console.warn("Snapshot save failed:",o.message)}})()},[e.phase,l,e.isHeuristic,e.platform,e.username]),useEffect(()=>()=>{n.current&&n.current.destroy()},[]);const y=e.phase==="fetching"||e.phase==="analyzing";if(useEffect(()=>{const d=document.getElementById("pr-vanilla-selection"),u=document.getElementById("root"),o=document.getElementById("prs-card-formfields"),g=document.getElementById("prs-card-loading"),f=document.getElementById("prs-card-loading-static");if(!d||!u)return;if((()=>{try{const v=location.pathname||"";if(/^\/profile-report\/[^/?#]+/.test(v)||new URLSearchParams(location.search).get("id"))return!0}catch{}return!1})()&&e.phase!=="complete"&&e.phase!=="error"){document.documentElement?.classList.add("pr-report-active"),document.body?.classList.add("pr-report-active"),d.hidden=!0,u.hidden=!1,o&&(o.style.visibility=""),g&&(g.hidden=!0),f&&(f.style.display="");return}if(y)document.documentElement?.classList.remove("pr-report-active"),document.body?.classList.remove("pr-report-active"),d.hidden=!1,u.hidden=!0,o&&(o.style.visibility="hidden"),g&&(g.hidden=!1),f&&(f.style.display="none");else if(e.phase==="complete"||e.phase==="error")document.documentElement?.classList.add("pr-report-active"),document.body?.classList.add("pr-report-active"),d.hidden=!0,u.hidden=!1,o&&(o.style.visibility=""),g&&(g.hidden=!0),f&&(f.style.display="");else if(e.phase==="ready"&&d.hidden){document.documentElement?.classList.remove("pr-report-active"),document.body?.classList.remove("pr-report-active"),u.hidden=!0,o&&(o.style.visibility=""),g&&(g.hidden=!0),f&&(f.style.display=""),d.hidden=!1;const v=[d,...d.querySelectorAll(".prs-hero, .prs-sub, .prs-card, .prs-past")];v.forEach(h=>{h.style.animation="none"}),d.offsetWidth,v.forEach(h=>{h.style.animation=""})}},[y,e.phase]),e.selectedGameIdx!==null&&l){const d=l.analyzedGames?.[e.selectedGameIdx]||null;return React.createElement("div",{className:"pr-page"},React.createElement("div",{className:"pr-container"},React.createElement(GameDrillDown,{gameAnalysis:d,gameMetadata:e.games[e.selectedGameIdx],onBack:()=>{try{window.history.back()}catch{t({type:"BACK_TO_REPORT"})}}})))}const k=e.phase==="complete"&&l;return React.createElement("div",{className:"pr-page"},e.phase==="ready"&&React.createElement(SelectionScreen,{state:e,dispatch:t,onStart:m,onLoadHistory:s}),y&&(()=>{const d=document.getElementById("prs-card-loading-react");return d?ReactDOM.createPortal(React.createElement(InlineProgressInner,{state:e}),d):React.createElement("div",{className:"pr-container"},React.createElement(InlineProgress,{state:e}))})(),e.phase==="error"&&React.createElement("div",{className:"pr-container"},React.createElement(InlineError,{error:e.error,onRetry:()=>t({type:"RESET"})})),k&&React.createElement("div",{className:"pr-container pr-stack",style:{position:"relative"}},React.createElement("button",{onClick:()=>{try{window.history.replaceState(null,"","/profile-report")}catch{}t({type:"BACK_TO_SELECTION"})},"aria-label":"Back to selection",title:"Back to selection",style:{position:"absolute",left:-8,top:30,transform:"translateX(-100%)",display:"inline-flex",alignItems:"center",justifyContent:"center",width:32,height:32,background:"none",border:"none",color:"var(--pr-text-body)",cursor:"pointer",zIndex:2},onMouseEnter:d=>d.currentTarget.style.color="rgba(240,235,224,0.9)",onMouseLeave:d=>d.currentTarget.style.color="var(--pr-text-secondary)"},React.createElement("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"},React.createElement("path",{d:"M19 12H5M12 19l-7-7 7-7"}))),React.createElement(RatingMomentum,{stats:e.stats,analysis:l,username:e.username,platform:e.platform,format:e.format,gameCount:e.games?.length??e.gameCount}),e.freeTier?React.createElement(LockedPreview,null):React.createElement(React.Fragment,null,React.createElement(PerformanceRadar,{analysis:l,state:e}),React.createElement(OpeningDimension,{analysis:l,games:e.games}),React.createElement(SkillDimensionSections,{analysis:l,games:e.games,username:e.username,skipOpening:!0}),React.createElement(ImprovementPlan,{analysis:l,stats:e.stats}),React.createElement(AdditionalInsights,{analysis:l,games:e.games}),React.createElement(GamesList,{analysis:l,games:e.games,onSelectGame:d=>{try{window.history.pushState({pr:"drilldown",idx:d},"")}catch{}t({type:"SELECT_GAME",idx:d})}}))))}function DimSectionCard({id:e,title:t,children:n}){return React.createElement("div",{id:e,className:"pr-card pr-card--p8",style:{scrollMarginTop:64}},React.createElement("div",{style:{display:"flex",alignItems:"center",gap:10,marginBottom:22}},React.createElement("h3",{style:{margin:0,fontSize:22,fontWeight:700,color:"#fff",letterSpacing:"-0.01em"}},t)),React.createElement("div",{className:"pr-grid-2--lg"},n))}function DimCoach({title:e,body:t}){return React.createElement("div",{style:{marginBottom:14}},React.createElement("div",{style:{fontWeight:700,color:"#fff",fontSize:16,marginBottom:4}},e),React.createElement("div",{style:{color:"var(--pr-text-primary)",fontSize:16,lineHeight:1.55,fontWeight:500}},t))}function OpeningDimension({analysis:e,games:t}){const[n,a]=useState(!1),s=(e.analyzedGames||[]).filter(w=>!w.isQuickMode);if(s.length===0)return null;const i=s.filter(w=>w.evalGraph&&w.evalGraph.length>=29).map(w=>{const D=w.playerColor==="w"?1:-1;return w.evalGraph[28]*D/100}),p=s.filter(w=>w.playerColor==="w"&&w.evalGraph&&w.evalGraph.length>=29).map(w=>w.evalGraph[28]/100),m=s.filter(w=>w.playerColor==="b"&&w.evalGraph&&w.evalGraph.length>=29).map(w=>-w.evalGraph[28]/100),l=i.length>0?+(i.reduce((w,D)=>w+D,0)/i.length).toFixed(1):null,r=p.length>0?+(p.reduce((w,D)=>w+D,0)/p.length).toFixed(1):null,c=m.length>0?+(m.reduce((w,D)=>w+D,0)/m.length).toFixed(1):null,y=[],k=[];s.forEach(w=>{const D=w.moveAnalysis.filter(E=>E.isPlayerMove);let N=0;for(const E of D)if(E.classification==="book"||E.classification==="best"||E.classification==="excellent")N++;else break;y.push(N);const T=D.findIndex(E=>E.classification!=="book");k.push(T===-1?D.length:T+1)});const d=y.length>0?+(y.reduce((w,D)=>w+D,0)/y.length).toFixed(1):null,u=k.length>0?+(k.reduce((w,D)=>w+D,0)/k.length).toFixed(1):null,o=s.filter(w=>w.playerColor==="w"),g={};o.forEach(w=>{const D=w.moveAnalysis.find(N=>N.isPlayerMove);if(D){const N=D.san||"?";g[N]=(g[N]||0)+1}});const f=Object.entries(g).sort((w,D)=>D[1]-w[1]).slice(0,4),x=s.filter(w=>w.playerColor==="b"),v={};x.forEach(w=>{const D=w.moveAnalysis.find(N=>N.isPlayerMove);if(D){const N=D.san||"?";v[N]=(v[N]||0)+1}});const h=Object.entries(v).sort((w,D)=>D[1]-w[1]).slice(0,4),S={};s.forEach(w=>{const D=openingNameFromHeaders(w.headers||{}),N=w.playerColor;S[D]||(S[D]={wins:0,losses:0,draws:0,total:0,accs:[],evalAt15:[]}),S[D].total++;const T=w.headers?.Result;if(N==="w"&&T==="1-0"||N==="b"&&T==="0-1"?S[D].wins++:T==="1/2-1/2"?S[D].draws++:S[D].losses++,S[D].accs.push(w.playerAccuracy),w.evalGraph&&w.evalGraph.length>=29){const L=N==="w"?1:-1;S[D].evalAt15.push(w.evalGraph[28]*L/100)}});const C=([w,D])=>({name:w,...D,winRate:Math.round(D.wins/D.total*100),avgAcc:Math.round(D.accs.reduce((N,T)=>N+T,0)/D.accs.length),avgEv15:D.evalAt15.length>0?+(D.evalAt15.reduce((N,T)=>N+T,0)/D.evalAt15.length).toFixed(1):null}),M=Object.entries(S).map(C).sort((w,D)=>D.total-w.total),R=w=>w>=.3?"#5DB67D":w<=-.3?"#CF6E6E":"#D4A44B",b=w=>w>=60?"#5DB67D":w>=40?"#D4A44B":"#CF6E6E";return React.createElement(DimSectionCard,{id:"dim-opening",title:"Opening"},React.createElement("div",null,l!==null&&React.createElement(React.Fragment,null,React.createElement("div",{className:"pr-label pr-mb-3"},"How you stand after opening end (at move 15)"),React.createElement("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr 1fr",gap:10}},React.createElement("div",{style:{background:"rgba(255,255,255,0.04)",borderRadius:8,padding:"10px 12px",textAlign:"center"}},React.createElement("div",{style:{fontSize:13,color:"var(--pr-text-body)",marginBottom:3}},"Overall"),React.createElement("div",{style:{fontSize:24,fontWeight:700,color:R(l)}},l>=0?"+":"",l)),r!==null&&React.createElement("div",{style:{background:"rgba(255,255,255,0.04)",borderRadius:8,padding:"10px 12px",textAlign:"center"}},React.createElement("div",{style:{fontSize:13,color:"var(--pr-text-body)",marginBottom:3}},"As White"),React.createElement("div",{style:{fontSize:24,fontWeight:700,color:R(r)}},r>=0?"+":"",r)),c!==null&&React.createElement("div",{style:{background:"rgba(255,255,255,0.04)",borderRadius:8,padding:"10px 12px",textAlign:"center"}},React.createElement("div",{style:{fontSize:13,color:"var(--pr-text-body)",marginBottom:3}},"As Black"),React.createElement("div",{style:{fontSize:24,fontWeight:700,color:R(c)}},c>=0?"+":"",c))))),React.createElement("div",null,React.createElement("div",{style:{fontSize:16,color:"var(--pr-text-primary)",lineHeight:1.6,marginBottom:12}},React.createElement("strong",{style:{color:"#fff"}},"Repertoire:")," ",e.openings.length," openings across ",s.length," games.",u!==null&&React.createElement(React.Fragment,null," You stay in book theory for ",React.createElement("strong",{style:{color:"#fff"}},"~",Math.round(u)," moves")," on average.")),React.createElement("div",{style:{fontSize:16,color:"var(--pr-text-primary)",lineHeight:1.6,marginBottom:12}},React.createElement("strong",{style:{color:"#fff"}},"Win rate:")," ",e.whiteWinRate,"% as White (",e.asWhite," games), ",e.blackWinRate,"% as Black (",e.asBlack," games)."),l!==null&&React.createElement("div",{style:{fontSize:16,color:"var(--pr-text-primary)",lineHeight:1.6}},React.createElement("strong",{style:{color:"#fff"}},"Position at move 15:")," ",l>=.3?"You consistently emerge from the opening with an advantage \u2014 your preparation is paying off.":l<=-.3?"You tend to leave the opening at a disadvantage. Focus on studying your opening repertoire.":"You come out of the opening roughly equal \u2014 solid, but finding ways to get an edge will boost results.",r!==null&&c!==null&&Math.abs(r-c)>.5&&` Your ${r>c?"White":"Black"} openings are stronger (${r>c?`+${r}`:`${c>=0?"+":""}${c}`} vs ${r>c?(c>=0?"+":"")+c:"+"+r}).`)),React.createElement("div",null,o.length>0&&f.length>0&&React.createElement(React.Fragment,null,React.createElement("div",{className:"pr-label pr-mb-3"},"First Move as White"),React.createElement("div",{style:{display:"flex",flexDirection:"column",gap:6}},f.map(([w,D])=>{const N=Math.round(D/o.length*100);return React.createElement("div",{key:w,style:{display:"flex",alignItems:"center",gap:8}},React.createElement("span",{style:{fontSize:14,fontWeight:600,color:"#fff",width:36}},w),React.createElement("div",{style:{flex:1,height:14,background:"rgba(255,255,255,0.06)",borderRadius:4,overflow:"hidden"}},React.createElement("div",{style:{width:`${N}%`,height:"100%",background:"#D4A44B",borderRadius:4}})),React.createElement("span",{style:{fontSize:13,color:"var(--pr-text-body)",width:50,textAlign:"right"}},N,"%"))})))),React.createElement("div",null,x.length>0&&h.length>0&&React.createElement(React.Fragment,null,React.createElement("div",{className:"pr-label pr-mb-3"},"First Move as Black"),React.createElement("div",{style:{display:"flex",flexDirection:"column",gap:6}},h.map(([w,D])=>{const N=Math.round(D/x.length*100);return React.createElement("div",{key:w,style:{display:"flex",alignItems:"center",gap:8}},React.createElement("span",{style:{fontSize:14,fontWeight:600,color:"#fff",width:36}},w),React.createElement("div",{style:{flex:1,height:14,background:"rgba(255,255,255,0.06)",borderRadius:4,overflow:"hidden"}},React.createElement("div",{style:{width:`${N}%`,height:"100%",background:"#6B9FD4",borderRadius:4}})),React.createElement("span",{style:{fontSize:13,color:"var(--pr-text-body)",width:50,textAlign:"right"}},N,"%"))})))),React.createElement("div",{style:{gridColumn:"1 / -1"}},React.createElement("div",{className:"pr-label pr-mb-3"},"Most-Played Openings"),(()=>{const w=M,D=B=>B.name;let N;if(n)N=[...w].sort((B,W)=>W.total-B.total).map(B=>({...B,tag:null}));else{const B=[...w].sort((F,K)=>K.total-F.total).slice(0,5),W=new Set(B.map(D)),$=[...w.filter(F=>!W.has(D(F))&&F.total>=2)].sort((F,K)=>K.winRate-F.winRate||K.total-F.total).slice(0,2);$.forEach(F=>W.add(D(F)));const O=[...w.filter(F=>!W.has(D(F))&&F.total>=2)].sort((F,K)=>F.winRate-K.winRate||K.total-F.total).slice(0,2);N=[...B.map(F=>({...F,tag:null})),...$.map(F=>({...F,tag:"Bright spot"})),...O.map(F=>({...F,tag:"Needs work"}))]}const T=B=>B>=55?"#5DB67D":B>=40?"#D4A44B":"#CF6E6E",E=B=>B==="Bright spot"?"rgba(93,182,125,0.18)":B==="Needs work"?"rgba(207,110,110,0.18)":null,L=B=>B==="Bright spot"?"#9ED6B2":B==="Needs work"?"#E3A8A8":null,_=B=>{const W=B.avgEv15;return W!==null&&W>=.3&&B.winRate>=55?`You leave the opening with a ${W>=0?"+":""}${W} advantage and win ${B.winRate}% of the time. This opening is working \u2014 keep it in your repertoire.`:W!==null&&W>=.3&&B.winRate<45?`You leave the opening with a ${W>=0?"+":""}${W} advantage but only win ${B.winRate}%. The opening is fine; you're losing these games in the middlegame.`:W!==null&&W<=-.3&&B.winRate>=55?`You leave the opening at ${W} pawns but win ${B.winRate}%. Your defense is strong, though better preparation would make these games easier.`:W!==null&&W<=-.3?`You leave the opening at ${W} pawns. Study the theory or switch to an opening you know better.`:B.winRate>=55?`${B.winRate}% wins, ${B.avgAcc}% accuracy. This opening is working for you.`:B.winRate<40?`${B.winRate}% wins, ${B.avgAcc}% accuracy. This opening isn't producing results. Study the main ideas or switch to one you're more comfortable with.`:`${B.winRate}% wins, ${B.avgAcc}% accuracy. Results are average. Deeper preparation would help.`},I=B=>{const W=[];return B.wins&&W.push(`${B.wins} won`),B.draws&&W.push(`${B.draws} drawn`),B.losses&&W.push(`${B.losses} lost`),W.join(", ")},P=w.length,z=P>N.length||n;return React.createElement(React.Fragment,null,N.map(B=>{const W=T(B.winRate);return React.createElement("div",{key:D(B)+(B.tag||""),style:{marginBottom:18,paddingLeft:14,borderLeft:`2px solid ${W}`}},React.createElement("div",{style:{fontSize:16,lineHeight:1.5,color:"var(--pr-text-body)",display:"flex",alignItems:"center",flexWrap:"wrap",gap:8}},React.createElement("em",{style:{color:"#fff",fontWeight:600,fontStyle:"normal"}},B.name),React.createElement("span",{style:{color:"var(--pr-text-secondary)",fontSize:14}},"(",B.total," game",B.total!==1?"s":""," \xB7 ",I(B),")"),B.tag&&React.createElement("span",{style:{fontSize:13,fontWeight:600,padding:"2px 8px",borderRadius:10,background:E(B.tag),color:L(B.tag)}},B.tag)),React.createElement("div",{style:{fontSize:16,color:"var(--pr-text-primary)",lineHeight:1.55,marginTop:6,fontWeight:500}},_(B)))}),z&&React.createElement("button",{type:"button",onClick:()=>a(B=>!B),style:{background:"transparent",border:"1px solid rgba(255,255,255,0.15)",borderRadius:8,color:"var(--pr-text-body)",fontSize:16,fontWeight:600,padding:"8px 14px",cursor:"pointer",marginTop:4,transition:"background 0.15s, border-color 0.15s"},onMouseEnter:B=>{B.currentTarget.style.background="rgba(255,255,255,0.04)",B.currentTarget.style.borderColor="rgba(255,255,255,0.25)"},onMouseLeave:B=>{B.currentTarget.style.background="transparent",B.currentTarget.style.borderColor="rgba(255,255,255,0.15)"}},n?"Show fewer \u2191":`Show all ${P} openings \u2193`))})()))}function TacticsDimension({analysis:e,username:t}){const n=e.analyzedGames||[];if(n.length===0)return null;const a=e.totalClassifications||{},s=Object.values(a).reduce((C,M)=>C+M,0)||1,i=n.flatMap(C=>C.moveAnalysis.filter(M=>M.isPlayerMove)),p=["inaccuracy","mistake","blunder"],m=((a.blunder||0)/n.length).toFixed(1),l=Math.round(((a.best||0)+(a.excellent||0)+(a.good||0))/s*100),r=[{key:"brilliant",label:"Brilliant",color:"#14e6e6"},{key:"best",label:"Best",color:"#7bcc18"},{key:"excellent",label:"Excellent",color:"#7bcc18"},{key:"good",label:"Good",color:"#088a28"},{key:"book",label:"Book",color:"#d5a47d"},{key:"inaccuracy",label:"Inaccuracy",color:"#ddd015"},{key:"mistake",label:"Mistake",color:"#e5820d"},{key:"blunder",label:"Blunder",color:"#d44242"}].map(C=>({...C,count:a[C.key]||0,pct:Math.round((a[C.key]||0)/s*1e3)/10})).filter(C=>C.count>0),c=n.flatMap(C=>C.moveAnalysis.filter(M=>!M.isPlayerMove)),y={inaccuracy:0,mistake:0,blunder:0},k={inaccuracy:0,mistake:0,blunder:0};i.forEach(C=>{p.includes(C.classification)&&y[C.classification]++}),c.forEach(C=>{p.includes(C.classification)&&k[C.classification]++});const d=n.length,u=[{type:"Blunders",you:+(y.blunder/d).toFixed(1),opponents:+(k.blunder/d).toFixed(1),fill:"#CF6E6E"},{type:"Mistakes",you:+(y.mistake/d).toFixed(1),opponents:+(k.mistake/d).toFixed(1),fill:"#ffa459"},{type:"Inaccuracies",you:+(y.inaccuracy/d).toFixed(1),opponents:+(k.inaccuracy/d).toFixed(1),fill:"#f7c631"}],o=u.reduce((C,M)=>C+M.you,0),g=u.reduce((C,M)=>C+M.opponents,0),f={opening:0,middlegame:0,endgame:0},x={opening:{inaccuracy:0,mistake:0,blunder:0},middlegame:{inaccuracy:0,mistake:0,blunder:0},endgame:{inaccuracy:0,mistake:0,blunder:0}};i.forEach(C=>{const M=C.gamePhase;M&&f[M]!==void 0&&p.includes(C.classification)&&(f[M]++,x[M][C.classification]++)});const v=f.opening+f.middlegame+f.endgame,h=[{phase:"Opening",errors:f.opening,pct:v>0?Math.round(f.opening/v*100):0,fill:"#D4A44B",...x.opening},{phase:"Middlegame",errors:f.middlegame,pct:v>0?Math.round(f.middlegame/v*100):0,fill:"#CF6E6E",...x.middlegame},{phase:"Endgame",errors:f.endgame,pct:v>0?Math.round(f.endgame/v*100):0,fill:"#6B9FD4",...x.endgame}],S={background:"#2a2a25",border:"1px solid rgba(255,255,255,0.15)",borderRadius:8,padding:"5px 12px",fontSize:16,boxShadow:"0 4px 12px rgba(0,0,0,0.4)"};return React.createElement(DimSectionCard,{id:"dim-tactical",title:"Tactics"},React.createElement("div",null,React.createElement("div",{className:"pr-label pr-mb-3"},"Move Quality"),React.createElement("div",{className:"pr-stack--2"},r.map(C=>React.createElement("div",{key:C.key,className:"pr-quality-row"},React.createElement("div",{className:"pr-quality-row__label",style:{color:C.color}},C.label),React.createElement("div",{className:"pr-quality-row__bar"},React.createElement("div",{style:{height:"100%",borderRadius:"var(--lumi-radius-xs)",width:`${Math.max(2,C.pct)}%`,background:C.color,opacity:.7}}),React.createElement("span",{className:"pr-piece-bar__pct"},C.pct,"%"),React.createElement("span",{className:"pr-piece-bar__count",style:{color:"var(--lumi-text-muted)"}},C.count.toLocaleString())))))),React.createElement("div",null,React.createElement(DimCoach,{title:"Move quality",body:`${l}% of your moves were good, excellent, or best across ${n.length} games.`}),React.createElement(DimCoach,{title:"Blunder rate",body:`You average ${m} blunders per game. ${parseFloat(m)>2?"Reducing blunders is the single biggest lever for rating improvement.":parseFloat(m)>1?"You're within normal range \u2014 eliminating the remaining blunders will unlock your next rating tier.":"Excellent blunder control \u2014 strong tactical awareness."}`})),React.createElement(TacticsConversionInline,{analysis:e}),React.createElement("div",{style:{gridColumn:"1 / -1"}},React.createElement("div",{className:"pr-label pr-mb-3"},"Error Fingerprint"),(()=>{const C=[{key:"inaccuracy",label:"Inaccuracies",color:"#f7c631"},{key:"mistake",label:"Mistakes",color:"#ffa459"},{key:"blunder",label:"Blunders",color:"#CF6E6E"}];let M=0,R=null;h.forEach(I=>C.forEach(P=>{const z=I[P.key]||0;z>M&&(M=z,R={phase:I.phase,sev:P})}));const b=h.reduce((I,P)=>I+P.errors,0),w=I=>{const P=parseInt(I.slice(1),16);return`${P>>16&255},${P>>8&255},${P&255}`},D=o-g,N=(D>=0?"+":"")+D.toFixed(1),T=D>.05,E=D<-.05,L=T?"#CF6E6E":E?"#5DB67D":"#D4A44B",_=Math.max(o,g,.1);return React.createElement(React.Fragment,null,React.createElement("div",{style:{display:"flex",alignItems:"center",gap:16,flexWrap:"wrap",background:"rgba(255,255,255,0.04)",borderRadius:10,padding:"12px 16px",marginBottom:14}},React.createElement("div",{style:{fontSize:15,color:"var(--pr-text-body)",fontWeight:500}},"Errors / game \u2014 ",React.createElement("b",{style:{color:"#fff",fontWeight:700}},"You ",o.toFixed(1))," vs ",React.createElement("b",{style:{color:"var(--pr-text-primary)",fontWeight:700}},"Opp ",g.toFixed(1))," ",React.createElement("span",{style:{color:L,fontWeight:700,fontVariantNumeric:"tabular-nums"}},"(",N,")")),React.createElement("div",{style:{flex:1,minWidth:160,display:"flex",flexDirection:"column",gap:5}},React.createElement("div",{style:{display:"flex",alignItems:"center",gap:8}},React.createElement("span",{style:{fontSize:12,color:"var(--pr-text-body)",width:30,flexShrink:0,textTransform:"uppercase",letterSpacing:"0.06em"}},"You"),React.createElement("div",{style:{flex:1,height:6,background:"rgba(255,255,255,0.06)",borderRadius:3,overflow:"hidden"}},React.createElement("div",{style:{height:"100%",width:`${o/_*100}%`,background:T?"#CF6E6E":"var(--pr-text-primary)",borderRadius:3}}))),React.createElement("div",{style:{display:"flex",alignItems:"center",gap:8}},React.createElement("span",{style:{fontSize:12,color:"var(--pr-text-secondary)",width:30,flexShrink:0,textTransform:"uppercase",letterSpacing:"0.06em"}},"Opp"),React.createElement("div",{style:{flex:1,height:6,background:"rgba(255,255,255,0.06)",borderRadius:3,overflow:"hidden"}},React.createElement("div",{style:{height:"100%",width:`${g/_*100}%`,background:"rgba(255,255,255,0.45)",borderRadius:3}}))))),React.createElement("div",{style:{overflowX:"auto"}},React.createElement("div",{style:{display:"grid",gridTemplateColumns:"minmax(96px, 1.2fr) repeat(3, minmax(72px, 1fr))",gap:6,minWidth:320}},React.createElement("div",null),C.map(I=>React.createElement("div",{key:I.key,style:{textAlign:"center",fontSize:12,fontWeight:700,color:I.color,textTransform:"uppercase",letterSpacing:"0.04em",paddingBottom:2,borderBottom:`2px solid ${I.color}`}},I.label)),h.map(I=>React.createElement(React.Fragment,{key:I.phase},React.createElement("div",{style:{display:"flex",alignItems:"center",fontSize:15,fontWeight:600,color:"#fff"}},I.phase),C.map(P=>{const z=I[P.key]||0,B=M>0?z/M:0,W=R&&R.phase===I.phase&&R.sev.key===P.key&&z>0;return React.createElement("div",{key:P.key,style:{position:"relative",display:"flex",alignItems:"center",justifyContent:"center",minHeight:44,borderRadius:8,background:`rgba(${w(P.color)}, ${(.08+B*.55).toFixed(3)})`,border:W?`2px solid ${P.color}`:"1px solid rgba(255,255,255,0.05)",boxShadow:W?`0 0 0 2px rgba(${w(P.color)},0.25)`:"none"}},React.createElement("span",{style:{fontSize:18,fontWeight:800,lineHeight:1,color:z===0?"var(--pr-text-secondary)":"#fff",fontVariantNumeric:"tabular-nums"}},z),W&&React.createElement("span",{style:{position:"absolute",top:3,right:5,fontSize:11}},"\u{1F525}"))}))))),b>0&&R&&(()=>{const I={inaccuracy:"inaccuracies",mistake:"mistakes",blunder:"blunders"},P=`${R.phase} ${I[R.sev.key]}`,z=T?` You also make more errors per game than your opponents (${N}).`:E?` Overall you're the cleaner player (${N} vs opponents).`:"";return React.createElement("div",{style:{marginTop:16,padding:"14px 18px",background:"rgba(212, 164, 75, 0.10)",border:"1px solid rgba(212, 164, 75, 0.30)",borderLeft:"4px solid #D4A44B",borderRadius:8}},React.createElement("div",{style:{fontSize:12,fontWeight:700,letterSpacing:"0.1em",textTransform:"uppercase",color:"#D4A44B",marginBottom:6}},"Biggest leak"),React.createElement("div",{style:{fontSize:16,color:"var(--pr-text-primary)",lineHeight:1.55,fontWeight:500}},React.createElement("b",{style:{color:"#fff",fontWeight:700,textTransform:"capitalize"}},P)," are your biggest leak \u2014 focus your training there.",z))})())})()))}function EndgameDimension({analysis:e}){const t=(e.analyzedGames||[]).filter(r=>!r.isQuickMode);if(t.length<3)return null;const n=t.map((r,c)=>{const y=r.moveAnalysis||[],d=y.filter(C=>C.isPlayerMove&&C.accuracy!=null).filter(C=>C.gamePhase==="endgame");if(d.length===0)return null;const u=Math.round(d.reduce((C,M)=>C+M.accuracy,0)/d.length*10)/10,o=y.find(C=>C.gamePhase==="endgame"),g=o?r.playerColor==="w"?o.evalBefore:-o.evalBefore:0,f=r.headers?.Result,x=r.playerColor==="w"&&f==="1-0"||r.playerColor==="b"&&f==="0-1",v=f==="1/2-1/2",h=r.playerColor==="w"&&f==="0-1"||r.playerColor==="b"&&f==="1-0";let S="equal";return g>=150?S="advantage":g<=-150&&(S="disadvantage"),{game:c+1,acc:u,category:S,won:x,drew:v,lost:h,entryEval:g,egMoveCount:d.length}}).filter(Boolean);if(n.length===0)return null;const a=Math.round(n.reduce((r,c)=>r+c.acc,0)/n.length*10)/10,s=a-e.avgAccuracy,i=["advantage","equal","disadvantage"],p={advantage:"With Advantage",equal:"Equal Endgames",disadvantage:"With Disadvantage"},m={advantage:"#5DB67D",equal:"#6B9FD4",disadvantage:"#CF6E6E"},l=i.map(r=>{const c=n.filter(o=>o.category===r);if(c.length===0)return null;const y=c.filter(o=>o.won).length,k=c.filter(o=>o.drew).length,d=c.filter(o=>o.lost).length,u=Math.round(c.reduce((o,g)=>o+g.acc,0)/c.length*10)/10;return{key:r,label:p[r],color:m[r],total:c.length,wins:y,draws:k,losses:d,acc:u}}).filter(Boolean);return React.createElement(DimSectionCard,{id:"dim-endgame",title:"Endgame"},React.createElement("div",null,React.createElement("div",{className:"pr-chart-h48"},React.createElement(ResponsiveContainer,{width:"100%",height:"100%"},React.createElement(BarChart,{data:n,margin:{top:4,right:8,bottom:0,left:0}},React.createElement(XAxis,{dataKey:"game",tick:{fontSize:14,fill:"var(--pr-text-primary)",fontWeight:500}}),React.createElement(YAxis,{domain:[0,100],tick:{fontSize:14,fill:"var(--pr-text-primary)",fontWeight:500}}),React.createElement(CartesianGrid,{strokeDasharray:"3 3",vertical:!1}),React.createElement(Tooltip,{contentStyle:{background:"#2a2a25",border:"1px solid rgba(255,255,255,0.15)",borderRadius:8,padding:"5px 12px",fontSize:16,boxShadow:"0 4px 12px rgba(0,0,0,0.4)"},formatter:r=>[`${r}%`,"Endgame Acc."]}),React.createElement(ReferenceLine,{y:e.avgAccuracy,stroke:"#D4A44B",strokeDasharray:"4 4"}),React.createElement(Bar,{dataKey:"acc",radius:[3,3,0,0]},n.map((r,c)=>React.createElement(Cell,{key:c,fill:r.acc>=e.avgAccuracy?"#5DB67D":"#CF6E6E"})))))),React.createElement("div",{style:{fontSize:13,color:"var(--pr-text-body)",marginTop:6}},"Amber line = overall average. Green = above average endgame, red = below.")),React.createElement("div",null,React.createElement(DimCoach,{title:"Endgame accuracy",body:`Your average endgame accuracy is ${a}%, vs your overall ${e.avgAccuracy}%.`}),React.createElement(DimCoach,{title:"What this means",body:s>=5?"Your endgame is a strength \u2014 you play more accurately as positions simplify.":s<=-5?"Your endgame lags behind your overall play. Studying basic endgame technique (K+P, rook endings) will have a direct impact on your results.":"Your endgame level is consistent with your overall game."})),l.length>0&&React.createElement("div",{style:{gridColumn:"1 / -1"}},React.createElement("div",{className:"pr-label pr-mb-3"},"Endgame by Position Type"),React.createElement("div",{className:"pr-rate-tile-grid",style:{display:"grid",gridTemplateColumns:`repeat(${l.length}, 1fr)`,gap:12}},l.map(r=>{const c=r.total>0?r.wins/r.total*100:0,y=r.total>0?r.draws/r.total*100:0,k=r.total>0?r.losses/r.total*100:0;return React.createElement("div",{key:r.key,style:{background:"rgba(255,255,255,0.04)",borderRadius:10,padding:"16px 18px",borderTop:`3px solid ${r.color}`}},React.createElement("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:14}},React.createElement("div",{style:{fontSize:16,fontWeight:700,color:r.color}},r.label),React.createElement("div",{style:{fontSize:14,color:"var(--pr-text-secondary)",textTransform:"uppercase",letterSpacing:"0.06em",fontWeight:600}},r.total," ",r.total===1?"game":"games")),React.createElement("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:14}},React.createElement("div",{style:{fontSize:32,fontWeight:800,color:"#fff",lineHeight:1,letterSpacing:"-0.02em"}},r.acc,"%"),React.createElement("div",{style:{fontSize:15,color:"var(--pr-text-primary)",fontWeight:500}},"accuracy")),React.createElement("div",{style:{display:"flex",height:6,borderRadius:3,background:"rgba(255,255,255,0.06)",overflow:"hidden",marginBottom:8}},c>0&&React.createElement("div",{style:{width:`${c}%`,background:"#5DB67D"}}),y>0&&React.createElement("div",{style:{width:`${y}%`,background:"rgba(240,235,224,0.45)"}}),k>0&&React.createElement("div",{style:{width:`${k}%`,background:"#CF6E6E"}})),React.createElement("div",{style:{display:"flex",justifyContent:"space-between",fontSize:14,fontVariantNumeric:"tabular-nums"}},React.createElement("span",{style:{color:r.wins>0?"#5DB67D":"rgba(255,255,255,0.6)"}},React.createElement("span",{style:{fontWeight:700}},r.wins)," won"),React.createElement("span",{style:{color:r.draws>0?"var(--pr-text-primary)":"rgba(255,255,255,0.6)"}},React.createElement("span",{style:{fontWeight:700}},r.draws)," drawn"),React.createElement("span",{style:{color:r.losses>0?"#CF6E6E":"rgba(255,255,255,0.6)"}},React.createElement("span",{style:{fontWeight:700}},r.losses)," lost")))}))))}function ConversionDimension({analysis:e}){const t=(e.analyzedGames||[]).filter(r=>!r.isQuickMode);if(t.length===0)return null;const n=t.filter(r=>r.maxAdvantage>=150);if(n.length===0)return null;const a=n.filter(r=>{const c=r.headers?.Result;return r.playerColor==="w"&&c==="1-0"||r.playerColor==="b"&&c==="0-1"}),s=Math.round(a.length/n.length*100),i=s>=65?"#5DB67D":s>=50?"#D4A44B":"#CF6E6E",p=[{name:"Converted",value:a.length,fill:"#5DB67D"},{name:"Let slip",value:n.length-a.length,fill:"#CF6E6E"}],l=[150,200,300,400].map(r=>{const c=`+${(r/100).toFixed(1)}`,y=t.filter(d=>{if(!d.evalGraph||d.evalGraph.length===0)return!1;const u=d.playerColor==="w"?1:-1;return d.evalGraph.some(o=>o*u>r)}),k=y.filter(d=>{const u=d.headers?.Result;return d.playerColor==="w"&&u==="1-0"||d.playerColor==="b"&&u==="0-1"});return{label:c,total:y.length,converted:k.length,rate:y.length>0?Math.round(k.length/y.length*100):0}}).filter(r=>r.total>0);return React.createElement(DimSectionCard,{id:"dim-capitalization",title:"Advantage Capitalization"},React.createElement("div",{style:{display:"flex",alignItems:"center",gap:20,flexWrap:"wrap"}},React.createElement("div",{style:{textAlign:"center",flexShrink:0}},React.createElement("div",{style:{fontSize:44,fontWeight:800,color:i,lineHeight:1}},s,"%"),React.createElement("div",{style:{fontSize:13,color:"var(--pr-text-body)",marginTop:4}},"conversion rate"),React.createElement("div",{style:{fontSize:13,color:"var(--pr-text-body)"}},a.length,"/",n.length," games")),React.createElement("div",{style:{flex:1}},React.createElement(ResponsiveContainer,{width:"100%",height:120},React.createElement(BarChart,{data:p,layout:"vertical",margin:{left:0,right:8,top:0,bottom:0}},React.createElement(XAxis,{type:"number",tick:{fontSize:14,fill:"var(--pr-text-primary)",fontWeight:500}}),React.createElement(YAxis,{type:"category",dataKey:"name",tick:{fontSize:14,fill:"var(--pr-text-primary)",fontWeight:500},width:72}),React.createElement(Tooltip,{contentStyle:{background:"#2a2a25",border:"1px solid rgba(255,255,255,0.15)",borderRadius:8,padding:"5px 12px",fontSize:16,boxShadow:"0 4px 12px rgba(0,0,0,0.4)"}}),React.createElement(Bar,{dataKey:"value",radius:[0,3,3,0]},p.map((r,c)=>React.createElement(Cell,{key:c,fill:r.fill}))))))),React.createElement("div",null,React.createElement(DimCoach,{title:"What this measures",body:"How often you convert a winning position (\u22651.5 pawn advantage) into an actual win."}),React.createElement(DimCoach,{title:"Your performance",body:`In ${n.length} games where you had a significant advantage, you won ${a.length} (${s}%). ${s>=65?"Strong conversion \u2014 you close out winning positions effectively.":s>=50?"Room to improve. Study technique for converting advantages and avoiding counterplay.":"This is a critical weakness. You get winning positions but give them away. Study endgame technique and calculation."}`})),l.length>=2&&React.createElement("div",{style:{gridColumn:"1 / -1"}},React.createElement("div",{className:"pr-label pr-mb-3"},"Conversion by Advantage Size"),React.createElement("div",{className:"pr-rate-tile-grid",style:{display:"grid",gridTemplateColumns:`repeat(${l.length}, 1fr)`,gap:12}},l.map(r=>{const c=r.rate>=65?"#5DB67D":r.rate>=50?"#D4A44B":"#CF6E6E",y=r.total-r.converted,k=r.total>0?r.converted/r.total*100:0,d=r.total>0?y/r.total*100:0;return React.createElement("div",{key:r.label,style:{background:"rgba(255,255,255,0.04)",borderRadius:10,padding:"16px 18px",borderTop:`3px solid ${c}`}},React.createElement("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:14}},React.createElement("div",{style:{fontSize:16,fontWeight:700,color:c}},"Advantage ",r.label),React.createElement("div",{style:{fontSize:14,color:"var(--pr-text-secondary)",textTransform:"uppercase",letterSpacing:"0.06em",fontWeight:600}},r.total," ",r.total===1?"game":"games")),React.createElement("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:14}},React.createElement("div",{style:{fontSize:32,fontWeight:800,color:"#fff",lineHeight:1,letterSpacing:"-0.02em"}},r.rate,"%"),React.createElement("div",{style:{fontSize:15,color:"var(--pr-text-primary)",fontWeight:500}},"conversion")),React.createElement("div",{style:{display:"flex",height:6,borderRadius:3,background:"rgba(255,255,255,0.06)",overflow:"hidden",marginBottom:8}},k>0&&React.createElement("div",{style:{width:`${k}%`,background:"#5DB67D"}}),d>0&&React.createElement("div",{style:{width:`${d}%`,background:"#CF6E6E"}})),React.createElement("div",{style:{display:"flex",justifyContent:"space-between",fontSize:14,fontVariantNumeric:"tabular-nums"}},React.createElement("span",{style:{color:r.converted>0?"#5DB67D":"rgba(255,255,255,0.6)"}},React.createElement("span",{style:{fontWeight:700}},r.converted)," converted"),React.createElement("span",{style:{color:y>0?"#CF6E6E":"rgba(255,255,255,0.6)"}},React.createElement("span",{style:{fontWeight:700}},y)," let slip")))})),l.length>=2&&l[0].rate-l[l.length-1].rate>=10&&React.createElement("div",{style:{fontSize:16,color:"var(--pr-text-primary)",marginTop:12,lineHeight:1.55,fontWeight:500}},"You convert ",l[l.length-1].rate,"% with large advantages (",l[l.length-1].label,") but only ",l[0].rate,"% with small ones (",l[0].label,") \u2014 focus on pressing small edges.")))}function ResourcefulnessDimension({analysis:e}){const t=(e.analyzedGames||[]).filter(c=>!c.isQuickMode);if(t.length===0)return null;const n=e.resourcefulness;if(!n||n.total===0)return null;const{total:a,saved:s,rate:i}=n,p=i>=40?"#5DB67D":i>=25?"#D4A44B":"#CF6E6E",m=[{name:"Saved",value:s,fill:"#5DB67D"},{name:"Lost",value:a-s,fill:"#CF6E6E"}],r=[150,200,300,400].map(c=>{const y=`-${(c/100).toFixed(1)}`,k=t.filter(u=>{if(!u.evalGraph||u.evalGraph.length===0)return!1;const o=u.playerColor==="w"?1:-1;return u.evalGraph.some(g=>g*o<-c)}),d=k.filter(u=>{const o=u.headers?.Result;return o==="1/2-1/2"||u.playerColor==="w"&&o==="1-0"||u.playerColor==="b"&&o==="0-1"});return{label:y,total:k.length,saved:d.length,rate:k.length>0?Math.round(d.length/k.length*100):0}}).filter(c=>c.total>0);return React.createElement(DimSectionCard,{id:"dim-resourcefulness",title:"Resourcefulness"},React.createElement("div",{style:{display:"flex",alignItems:"center",gap:20,flexWrap:"wrap"}},React.createElement("div",{style:{textAlign:"center",flexShrink:0}},React.createElement("div",{style:{fontSize:44,fontWeight:800,color:p,lineHeight:1}},i,"%"),React.createElement("div",{style:{fontSize:13,color:"var(--pr-text-body)",marginTop:4}},"save rate"),React.createElement("div",{style:{fontSize:13,color:"var(--pr-text-body)"}},s,"/",a," games")),React.createElement("div",{style:{flex:1}},React.createElement(ResponsiveContainer,{width:"100%",height:120},React.createElement(BarChart,{data:m,layout:"vertical",margin:{left:0,right:8,top:0,bottom:0}},React.createElement(XAxis,{type:"number",tick:{fontSize:14,fill:"var(--pr-text-primary)",fontWeight:500}}),React.createElement(YAxis,{type:"category",dataKey:"name",tick:{fontSize:14,fill:"var(--pr-text-primary)",fontWeight:500},width:50}),React.createElement(Tooltip,{contentStyle:{background:"#2a2a25",border:"1px solid rgba(255,255,255,0.15)",borderRadius:8,padding:"5px 12px",fontSize:16,boxShadow:"0 4px 12px rgba(0,0,0,0.4)"}}),React.createElement(Bar,{dataKey:"value",radius:[0,3,3,0]},m.map((c,y)=>React.createElement(Cell,{key:y,fill:c.fill}))))))),React.createElement("div",null,React.createElement(DimCoach,{title:"What this measures",body:"Your ability to win or draw games where your opponent held a significant advantage (\u22651.5 pawns) at some point \u2014 a measure of fighting spirit and defensive skill."}),React.createElement(DimCoach,{title:"Your performance",body:`You were in a difficult position in ${a} games and saved ${s} of them (${i}%). ${i>=40?"Excellent fighting spirit \u2014 you rarely surrender lost positions.":i>=25?"Reasonable counterplay, but there's room to improve your defensive technique.":"Don't resign too early. Improving your defensive play and creating counterplay will gain you rating points even from worse positions."}`})),r.length>=2&&React.createElement("div",{style:{gridColumn:"1 / -1"}},React.createElement("div",{className:"pr-label pr-mb-3"},"How Deep Did You Fall?"),React.createElement("div",{className:"pr-rate-tile-grid",style:{display:"grid",gridTemplateColumns:`repeat(${r.length}, 1fr)`,gap:12}},r.map(c=>{const y=c.rate>=40?"#5DB67D":c.rate>=25?"#D4A44B":"#CF6E6E",k=c.total-c.saved,d=c.total>0?c.saved/c.total*100:0,u=c.total>0?k/c.total*100:0;return React.createElement("div",{key:c.label,style:{background:"rgba(255,255,255,0.04)",borderRadius:10,padding:"16px 18px",borderTop:`3px solid ${y}`}},React.createElement("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:14}},React.createElement("div",{style:{fontSize:16,fontWeight:700,color:y}},"Fell behind ",c.label),React.createElement("div",{style:{fontSize:14,color:"var(--pr-text-secondary)",textTransform:"uppercase",letterSpacing:"0.06em",fontWeight:600}},c.total," ",c.total===1?"game":"games")),React.createElement("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:14}},React.createElement("div",{style:{fontSize:32,fontWeight:800,color:"#fff",lineHeight:1,letterSpacing:"-0.02em"}},c.rate,"%"),React.createElement("div",{style:{fontSize:15,color:"var(--pr-text-primary)",fontWeight:500}},"saved")),React.createElement("div",{style:{display:"flex",height:6,borderRadius:3,background:"rgba(255,255,255,0.06)",overflow:"hidden",marginBottom:8}},d>0&&React.createElement("div",{style:{width:`${d}%`,background:"#5DB67D"}}),u>0&&React.createElement("div",{style:{width:`${u}%`,background:"#CF6E6E"}})),React.createElement("div",{style:{display:"flex",justifyContent:"space-between",fontSize:14,fontVariantNumeric:"tabular-nums"}},React.createElement("span",{style:{color:c.saved>0?"#5DB67D":"rgba(255,255,255,0.6)"}},React.createElement("span",{style:{fontWeight:700}},c.saved)," saved"),React.createElement("span",{style:{color:k>0?"#CF6E6E":"rgba(255,255,255,0.6)"}},React.createElement("span",{style:{fontWeight:700}},k)," lost")))}))))}function ConsistencyDimension({analysis:e,games:t}){const n=(e.analyzedGames||[]).filter(p=>!p.isQuickMode);if(n.length<3)return null;const a=n.map((p,m)=>({game:m+1,acc:p.playerAccuracy})),s=e.avgAccuracy,i=Math.round(Math.sqrt(a.reduce((p,m)=>p+(m.acc-s)**2,0)/a.length)*10)/10;return React.createElement(DimSectionCard,{id:"dim-consistency",title:"Consistency"},React.createElement("div",null,React.createElement("div",{className:"pr-chart-h48"},React.createElement(ResponsiveContainer,{width:"100%",height:"100%"},React.createElement(LineChart,{data:a,margin:{top:4,right:12,bottom:0,left:0}},React.createElement(XAxis,{dataKey:"game",tick:{fontSize:14,fill:"var(--pr-text-primary)",fontWeight:500}}),React.createElement(YAxis,{domain:[Math.max(0,s-30),Math.min(100,s+30)],tick:{fontSize:14,fill:"var(--pr-text-primary)",fontWeight:500},tickFormatter:p=>Math.round(p),width:32}),React.createElement(CartesianGrid,{strokeDasharray:"3 3",vertical:!1}),React.createElement(Tooltip,{contentStyle:{background:"#2a2a25",border:"1px solid rgba(255,255,255,0.15)",borderRadius:8,padding:"5px 12px",fontSize:16,boxShadow:"0 4px 12px rgba(0,0,0,0.4)"},formatter:p=>[`${p}%`,"Accuracy"]}),React.createElement(ReferenceLine,{y:s,stroke:"#D4A44B",strokeDasharray:"4 4"}),React.createElement(Line,{type:"monotone",dataKey:"acc",stroke:"#6B9FD4",strokeWidth:2,dot:{r:3,fill:"#6B9FD4"}}))))),React.createElement("div",null,React.createElement(DimCoach,{title:"Accuracy variance",body:`Standard deviation: ${i}%. ${i<=5?"Very consistent \u2014 you play at a similar level every game.":i<=10?"Moderate variance \u2014 some games are significantly better than others. Watch for tilt and fatigue.":"High variance \u2014 your performance fluctuates a lot. Focus on pre-game routine and staying focused through losses."}`}),React.createElement(DimCoach,{title:"Average accuracy",body:`${s}% across ${n.length} games.`})),(()=>{const p=computeAccuracyByResult(n),m=computeAccuracyByMoveNumber(n),l={win:"#5DB67D",draw:"#8A857F",loss:"#CF6E6E"},r={win:"When You Win",draw:"When You Draw",loss:"When You Lose"};return React.createElement(React.Fragment,null,React.createElement("div",{style:{gridColumn:"1 / -1"}},React.createElement("div",{className:"pr-label pr-mb-3"},"Accuracy by Result"),React.createElement("div",{className:"pr-rate-tile-grid",style:{display:"grid",gridTemplateColumns:"repeat(3, 1fr)",gap:12}},["win","draw","loss"].map(c=>{const y=l[c],k=p[c]?.avg,d=p[c]?.count||0;return React.createElement("div",{key:c,style:{background:"rgba(255,255,255,0.04)",borderRadius:10,padding:"16px 18px",borderTop:`3px solid ${y}`,opacity:d===0?.5:1}},React.createElement("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:14}},React.createElement("div",{style:{fontSize:16,fontWeight:700,color:y}},r[c]),React.createElement("div",{style:{fontSize:14,color:"var(--pr-text-secondary)",textTransform:"uppercase",letterSpacing:"0.06em",fontWeight:600}},d," ",d===1?"game":"games")),React.createElement("div",{style:{display:"flex",alignItems:"baseline",gap:8}},React.createElement("div",{style:{fontSize:32,fontWeight:800,color:"#fff",lineHeight:1,letterSpacing:"-0.02em"}},k??"\u2014",k?"%":""),React.createElement("div",{style:{fontSize:15,color:"var(--pr-text-primary)",fontWeight:500}},"accuracy")))}))),m.length>5&&React.createElement("div",{style:{gridColumn:"1 / -1"}},React.createElement("div",{className:"pr-label pr-mb-3"},"Accuracy by Move Number"),React.createElement("div",{className:"pr-chart-h52"},React.createElement(ResponsiveContainer,{width:"100%",height:"100%"},React.createElement(AreaChart,{data:m},React.createElement("defs",null,React.createElement("linearGradient",{id:"accGrad",x1:"0",y1:"0",x2:"0",y2:"1"},React.createElement("stop",{offset:"5%",stopColor:"#6B9FD4",stopOpacity:.3}),React.createElement("stop",{offset:"95%",stopColor:"#6B9FD4",stopOpacity:0}))),React.createElement(CartesianGrid,{strokeDasharray:"3 3"}),React.createElement(XAxis,{dataKey:"move",tick:{fontSize:14,fill:"var(--pr-text-primary)",fontWeight:500},label:{value:"Move",position:"insideBottomRight",offset:-5,fontSize:13,fill:"var(--pr-text-body)"}}),React.createElement(YAxis,{domain:[40,100],tick:{fontSize:14,fill:"var(--pr-text-primary)",fontWeight:500}}),React.createElement(Tooltip,{contentStyle:{background:"#2a2a25",border:"1px solid rgba(255,255,255,0.15)",borderRadius:8,padding:"5px 12px",fontSize:16,boxShadow:"0 4px 12px rgba(0,0,0,0.4)"},formatter:(c,y,k)=>[`${c}%`,`Move ${k.payload.move} (${k.payload.games} games)`]}),React.createElement(ReferenceLine,{y:e.avgAccuracy,stroke:"rgba(255,191,0,0.3)",strokeDasharray:"4 4"}),React.createElement(Area,{type:"monotone",dataKey:"accuracy",stroke:"#6B9FD4",strokeWidth:2,fill:"url(#accGrad)",dot:!1})))),React.createElement("div",{className:"pr-text-xs pr-text-dim pr-text-center pr-mt-1"},"Dashed line = overall average (",e.avgAccuracy,"%)")))})())}function TimeManagementDimension({analysis:e,games:t}){const n=Math.round(e.timeoutLosses/Math.max(1,e.losses)*100),a=Math.round(e.timeTrouble/e.total*100),s=(e.analyzedGames||[]).filter(b=>!b.isQuickMode),i=[];s.forEach(b=>{const w=(b.moveAnalysis||[]).filter(E=>E.isPlayerMove),N=(b.headers?.TimeControl||"").match(/\+(\d+)/),T=N?parseInt(N[1]):0;for(let E=0;E<w.length;E++){const L=w[E];if(L.clock==null)continue;const _=E>0?w[E-1]:null;if(_&&_.clock!=null){const I=Math.max(0,_.clock-L.clock+T);i.push({...L,timeSpent:I})}}});const p=i.map(b=>b.timeSpent).sort((b,w)=>b-w),m=p.length>0?p[Math.floor(p.length/2)]:10,l=Math.max(m*2,15),r=i.filter(b=>b.timeSpent>=l),c=r.length>=5,y=["blunder","mistake","inaccuracy","good","excellent","best"],k={blunder:"#CF6E6E",mistake:"#D4A44B",inaccuracy:"#E8C44B",good:"#8B8B8B",excellent:"#6B9FD4",best:"#5DB67D"},d={blunder:"Blunder",mistake:"Mistake",inaccuracy:"Inaccuracy",good:"Good",excellent:"Excellent",best:"Best"},u=y.map(b=>{const w=r.filter(D=>D.classification===b).length;return{name:d[b],count:w,pct:r.length>0?Math.round(w/r.length*100):0,fill:k[b]}}).filter(b=>b.count>0),o=r.length>0?Math.round(r.filter(b=>["blunder","mistake"].includes(b.classification)).length/r.length*100):0,g=i.filter(b=>b.clock!=null&&b.clock<30),f=i.filter(b=>b.clock!=null&&b.clock>=60),x=g.length>=3?Math.round(g.reduce((b,w)=>b+w.accuracy,0)/g.length*10)/10:null,v=f.length>=3?Math.round(f.reduce((b,w)=>b+w.accuracy,0)/f.length*10)/10:null,h=x!=null&&v!=null?Math.round((v-x)*10)/10:null,S=[{range:"0-5s",count:t.filter(b=>b.finalClock!==null&&b.finalClock<5).length,color:"#CF6E6E"},{range:"5-15s",count:t.filter(b=>b.finalClock!==null&&b.finalClock>=5&&b.finalClock<15).length,color:"#D4A44B"},{range:"15-30s",count:t.filter(b=>b.finalClock!==null&&b.finalClock>=15&&b.finalClock<30).length,color:"#D4A44B"},{range:"30-60s",count:t.filter(b=>b.finalClock!==null&&b.finalClock>=30&&b.finalClock<60).length,color:"#6B9FD4"},{range:"1-2min",count:t.filter(b=>b.finalClock!==null&&b.finalClock>=60&&b.finalClock<120).length,color:"#5DB67D"},{range:"2min+",count:t.filter(b=>b.finalClock!==null&&b.finalClock>=120).length,color:"#5DB67D"}],C=n>=25?"#CF6E6E":n>=12?"#D4A44B":"#5DB67D",M=n>=25?"Clock is the main thing costing you games":n>=12?"Clock costs you some games \u2014 fixable":"Strong clock discipline",R=[];return n>=25?R.push(`${n}% of your losses are timeouts (${e.timeoutLosses} of ${e.losses}) \u2014 the chess part of your game is mostly fine, the clock isn't.`):n>=12?R.push(`${n}% of your losses are timeouts (${e.timeoutLosses} of ${e.losses}). Not a crisis, but the leak adds up over a session.`):R.push(`Only ${n}% of your losses are timeouts \u2014 you almost always lose on the board, not the clock.`),e.severeTimeTrouble>=5&&R.push(`You finish ${e.severeTimeTrouble} games with under 5 seconds \u2014 bullet-time finishes are leaving you no margin for error.`),h!=null&&h>8?R.push(`Your accuracy drops ${h} points when low on time \u2014 a meaningful pressure leak.`):h!=null&&h>3?R.push(`Accuracy drops ${h} points under pressure \u2014 small, manageable.`):h!=null&&R.push(`Accuracy barely changes under pressure (${h} pt drop) \u2014 you play almost as sharply low on time as fresh.`),e.timeoutWins>0&&R.push(`On the other side: ${e.timeoutWins} wins came from flagging your opponent.`),React.createElement(DimSectionCard,{id:"dim-time-mgmt",title:"Time Management"},React.createElement("div",{style:{gridColumn:"1 / -1",display:"flex",alignItems:"center",gap:16,padding:"16px 18px",background:`${C}14`,border:`1px solid ${C}40`,borderRadius:12}},React.createElement("div",{style:{fontSize:38,fontWeight:800,color:C,lineHeight:1,letterSpacing:"-0.02em",flexShrink:0}},n,"%"),React.createElement("div",null,React.createElement("div",{style:{fontSize:17,fontWeight:700,color:C,marginBottom:2}},M),React.createElement("div",{style:{fontSize:14,color:"var(--pr-text-secondary)"}},"of your losses are timeouts"))),React.createElement("div",{style:{gridColumn:"1 / -1"}},React.createElement(DimCoach,{title:"What this measures",body:"How well you spend your clock. Strong time management means few timeout losses, your accuracy doesn't crash when seconds tick down, and the moves you stop to calculate are the right ones."}),React.createElement(DimCoach,{title:"Your performance",body:R.join(" ")})),React.createElement("div",{className:"pr-grid-2",style:{gridColumn:"1 / -1"}},React.createElement(StatBox,{label:"Games Lost to Clock",value:e.timeoutLosses,sub:`${n}% of all losses`,color:"#CF6E6E",stripe:"#CF6E6E"}),React.createElement(StatBox,{label:"Games in Time Trouble",value:`${a}%`,sub:"finished with <15s left",color:"#D4A44B",stripe:"#D4A44B"}),React.createElement(StatBox,{label:"Bullet-Time Finishes",value:e.severeTimeTrouble,sub:"games ending under 5s",color:"#CF6E6E",stripe:"#CF6E6E"}),React.createElement(StatBox,{label:"Wins by Flag",value:e.timeoutWins,sub:"opponent ran out of time",color:"#5DB67D",stripe:"#5DB67D"})),h!=null&&React.createElement("div",{style:{gridColumn:"1 / -1"}},React.createElement("div",{className:"pr-label pr-mb-3"},"Do you stay sharp under pressure?"),React.createElement("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12}},[{stripe:"#5DB67D",label:"With time (>60s)",acc:v,count:f.length,sub:"comfort zone"},{stripe:h>5?"#CF6E6E":"#D4A44B",label:"Time trouble (<30s)",acc:x,count:g.length,sub:"pressure zone"}].map((b,w)=>React.createElement("div",{key:w,style:{background:"rgba(255,255,255,0.04)",borderRadius:10,padding:"16px 18px",borderTop:`3px solid ${b.stripe}`}},React.createElement("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:14}},React.createElement("div",{style:{fontSize:16,fontWeight:700,color:b.stripe}},b.label),React.createElement("div",{style:{fontSize:14,color:"var(--pr-text-secondary)",textTransform:"uppercase",letterSpacing:"0.06em",fontWeight:600}},b.count," ",b.count===1?"move":"moves")),React.createElement("div",{style:{display:"flex",alignItems:"baseline",gap:8}},React.createElement("div",{style:{fontSize:32,fontWeight:800,color:"#fff",lineHeight:1,letterSpacing:"-0.02em"}},b.acc,"%"),React.createElement("div",{style:{fontSize:14,color:"var(--pr-text-body)"}},b.sub))))),React.createElement("div",{style:{fontSize:16,color:"var(--pr-text-primary)",marginTop:12,lineHeight:1.55,fontWeight:500}},h>10?`Your accuracy drops ${h}% under time pressure \u2014 a major leak. Try to keep more time on the clock for critical decisions.`:h>5?`Your accuracy drops ${h}% when low on time. Consider playing faster in the opening to save time for complex positions.`:`Your accuracy only drops ${h}% under time pressure \u2014 solid clock management.`)),c&&React.createElement("div",{style:{gridColumn:"1 / -1"}},React.createElement("div",{className:"pr-label pr-mb-3"},"When you stop to calculate, does it pay off?"),React.createElement("div",{style:{fontSize:16,color:"var(--pr-text-primary)",marginBottom:10,fontWeight:500,lineHeight:1.55}},"What happens on the ",r.length," moves where you spent more than ",Math.round(l)," seconds thinking."),React.createElement("div",{className:"pr-chart-h48"},React.createElement(ResponsiveContainer,{width:"100%",height:"100%"},React.createElement(BarChart,{data:u,margin:{top:4,right:8,bottom:0,left:0}},React.createElement(XAxis,{dataKey:"name",tick:{fontSize:14,fill:"var(--pr-text-primary)",fontWeight:500}}),React.createElement(YAxis,{tick:{fontSize:14,fill:"var(--pr-text-primary)",fontWeight:500},unit:"%"}),React.createElement(CartesianGrid,{strokeDasharray:"3 3",vertical:!1}),React.createElement(Tooltip,{contentStyle:{background:"#2a2a25",border:"1px solid rgba(255,255,255,0.15)",borderRadius:8,padding:"5px 12px",fontSize:16,boxShadow:"0 4px 12px rgba(0,0,0,0.4)"},formatter:(b,w,D)=>[`${D.payload.pct}% (${b} moves)`,D.payload.name]}),React.createElement(Bar,{dataKey:"count",radius:[3,3,0,0]},u.map((b,w)=>React.createElement(Cell,{key:w,fill:b.fill})))))),React.createElement("div",{style:{fontSize:16,color:"var(--pr-text-primary)",marginTop:8,lineHeight:1.55,fontWeight:500}},o>=30?`${o}% of your long thinks result in a mistake or blunder \u2014 your calculation may be leading you astray. Practice complex positions to improve decision-making.`:o>=15?`${o}% of long thinks end in errors. Mostly your extra thinking time pays off.`:`Only ${o}% of long thinks result in errors \u2014 your extra thinking time is well spent.`)),React.createElement("div",{style:{gridColumn:"1 / -1"}},React.createElement("div",{className:"pr-label pr-mb-3"},"How you finish on the clock"),React.createElement("div",{style:{fontSize:16,color:"var(--pr-text-primary)",marginBottom:10,fontWeight:500,lineHeight:1.55}},"Seconds remaining when each game ended. Red = scrambling, green = comfortable."),React.createElement("div",{className:"pr-chart-h48"},React.createElement(ResponsiveContainer,{width:"100%",height:"100%"},React.createElement(BarChart,{data:S},React.createElement(CartesianGrid,{strokeDasharray:"3 3",vertical:!1}),React.createElement(XAxis,{dataKey:"range",tick:{fontSize:14,fill:"var(--pr-text-primary)",fontWeight:500}}),React.createElement(YAxis,{tick:{fontSize:14,fill:"var(--pr-text-primary)",fontWeight:500}}),React.createElement(Tooltip,{contentStyle:{background:"#2a2a25",border:"1px solid rgba(255,255,255,0.15)",borderRadius:8,padding:"5px 12px",fontSize:16,boxShadow:"0 4px 12px rgba(0,0,0,0.4)"}}),React.createElement(Bar,{dataKey:"count",radius:[4,4,0,0]},S.map((b,w)=>React.createElement(Cell,{key:w,fill:b.color})))))),React.createElement("div",{style:{fontSize:13,color:"var(--pr-text-body)",marginTop:4}},"How much time you had left when each game ended.")))}function ColorAsymmetry({analysis:e}){const t=(e.analyzedGames||[]).filter(o=>!o.isQuickMode);if(t.length<4)return null;const n=["inaccuracy","mistake","blunder"],a=t.filter(o=>o.playerColor==="w"),s=t.filter(o=>o.playerColor==="b");if(a.length<2||s.length<2)return null;const i=o=>{let g=0;return o.forEach(f=>f.moveAnalysis.filter(x=>x.isPlayerMove).forEach(x=>{n.includes(x.classification)&&g++})),g},p=(i(a)/a.length).toFixed(1),m=(i(s)/s.length).toFixed(1),l=Math.round(a.reduce((o,g)=>o+g.playerAccuracy,0)/a.length*10)/10,r=Math.round(s.reduce((o,g)=>o+g.playerAccuracy,0)/s.length*10)/10,c=[{side:"White",acc:l,errors:p,count:a.length,stripe:"#E8E4E0"},{side:"Black",acc:r,errors:m,count:s.length,stripe:"#6B9FD4"}],y=Math.abs(l-r),k=l>r?"Black":"White",d=l>r?"White":"Black",u=y<1?`Your accuracy is essentially identical with both colours (${l}% vs ${r}%). That's rare \u2014 most players are 2-4pp better with one side. Suggests your opening repertoire is balanced and you adapt well to both colour rhythms.`:y<3?`You're slightly stronger as ${d} (${d==="White"?l:r}% vs ${d==="White"?r:l}%) but the gap is small. Both sides are working; no urgent opening fix needed.`:`Your ${k} play is ${y.toFixed(1)} accuracy points weaker (${d==="White"?l:r}% vs ${d==="White"?r:l}%). The gap is meaningful \u2014 focus opening study on your ${k} repertoire.`;return React.createElement(DimSectionCard,{title:"Performance by Color"},React.createElement("div",{className:"pr-pbc-grid",style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12,gridColumn:"1 / -1"}},c.map(o=>React.createElement("div",{key:o.side,style:{background:"rgba(255,255,255,0.04)",borderRadius:10,padding:"16px 18px",borderTop:`3px solid ${o.stripe}`}},React.createElement("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:14}},React.createElement("div",{style:{fontSize:16,fontWeight:700,color:o.stripe}},"As ",o.side),React.createElement("div",{style:{fontSize:14,color:"var(--pr-text-secondary)",textTransform:"uppercase",letterSpacing:"0.06em",fontWeight:600}},o.count," ",o.count===1?"game":"games")),React.createElement("div",{style:{display:"flex",alignItems:"baseline",gap:8,marginBottom:8}},React.createElement("div",{style:{fontSize:32,fontWeight:800,color:"#fff",lineHeight:1,letterSpacing:"-0.02em"}},o.acc,"%"),React.createElement("div",{style:{fontSize:15,color:"var(--pr-text-primary)",fontWeight:500}},"accuracy")),React.createElement("div",{style:{fontSize:14,color:"var(--pr-text-body)",fontVariantNumeric:"tabular-nums"}},React.createElement("span",{style:{fontWeight:700,color:"var(--pr-text-body)"}},o.errors)," errors per game")))),React.createElement("div",{style:{gridColumn:"1 / -1"}},React.createElement(DimCoach,{title:"What this measures",body:"Accuracy and error rate playing each colour separately. A gap of 3+ accuracy points usually signals an opening-preparation weakness on the weaker side \u2014 the engine punishes positions you don't know."}),React.createElement(DimCoach,{title:"Your performance",body:u})))}function AccuracyByPieceInsight({analysis:e}){const t=(e.analyzedGames||[]).filter(l=>!l.isQuickMode);if(t.length===0)return null;const n=computePieceAccuracy(t);if(n.length===0)return null;const a=n.reduce((l,r)=>l.accuracy>r.accuracy?l:r),s=n.reduce((l,r)=>l.accuracy<r.accuracy?l:r),i={Pawn:"Pawn \u2014 pawn breaks and structure decisions.",Knight:"Knight \u2014 outpost choice and forking geometry.",Bishop:"Bishop \u2014 long-diagonal tactics and good-vs-bad bishop trades.",Rook:"Rook \u2014 open-file timing and endgame technique.",Queen:"Queen \u2014 tactical calculation and avoiding early trades.",King:"King \u2014 endgame activity and safety calls."},p=a.accuracy-s.accuracy,m=p<4?`Your accuracy is balanced across pieces (${s.accuracy}-${a.accuracy}%). No single piece is dragging you down \u2014 your decisions are evenly weighted regardless of which piece is moving.`:`Your ${a.name.toLowerCase()} play is ${p.toFixed(1)} points sharper than your ${s.name.toLowerCase()} play (${a.accuracy}% vs ${s.accuracy}%). ${i[s.name]||`${s.name} accuracy`} is where the points are leaking.`;return React.createElement(DimSectionCard,{title:"Accuracy by Piece"},React.createElement("div",null,React.createElement("div",{className:"pr-chart-h52"},React.createElement(ResponsiveContainer,{width:"100%",height:"100%"},React.createElement(BarChart,{data:n,layout:"vertical"},React.createElement(CartesianGrid,{strokeDasharray:"3 3"}),React.createElement(XAxis,{type:"number",domain:[50,100],tick:{fontSize:14,fill:"var(--pr-text-primary)",fontWeight:500}}),React.createElement(YAxis,{type:"category",dataKey:"name",width:65,tick:{fontSize:14,fill:"var(--pr-text-primary)",fontWeight:500}}),React.createElement(Tooltip,{contentStyle:{background:"#2a2a25",border:"1px solid rgba(255,255,255,0.15)",borderRadius:8,padding:"5px 12px",fontSize:16,boxShadow:"0 4px 12px rgba(0,0,0,0.4)"},formatter:(l,r,c)=>[`${l}% (${c.payload.moves} moves)`,c.payload.name]}),React.createElement(Bar,{dataKey:"accuracy",radius:[0,4,4,0]},n.map((l,r)=>React.createElement(Cell,{key:r,fill:l.color}))))))),React.createElement("div",{className:"pr-grid-2"},React.createElement("div",null,React.createElement("div",{className:"pr-text-xs",style:{color:"#5DB67D"}},"Best Piece"),React.createElement("div",{className:"pr-text-sm pr-font-bold",style:{color:"#9ED6B2"}},a.name," (",a.accuracy,"%)")),React.createElement("div",null,React.createElement("div",{className:"pr-text-xs",style:{color:"#CF6E6E"}},"Weakest Piece"),React.createElement("div",{className:"pr-text-sm pr-font-bold",style:{color:"#E3A8A8"}},s.name," (",s.accuracy,"%)"))),React.createElement("div",{style:{gridColumn:"1 / -1",marginTop:8}},React.createElement(DimCoach,{title:"What this measures",body:"How accurately you move each piece type. Big gaps point to where your geometry breaks down \u2014 rook accuracy reflects endgame technique, knight reflects positional vision, queen reflects tactical calculation."}),React.createElement(DimCoach,{title:"Your performance",body:m})))}function AdditionalInsights({analysis:e,games:t}){return!e||e.isHeuristic||(e.analyzedGames||[]).filter(a=>!a.isQuickMode).length===0?null:React.createElement(React.Fragment,null,React.createElement("div",{style:{scrollMarginTop:64,padding:"24px 0 8px"}},React.createElement("h2",{style:{margin:0,fontSize:18,fontWeight:700,color:"#fff"}},"Additional Insights")),React.createElement(PsychProfile,{analysis:e}),React.createElement(ColorAsymmetry,{analysis:e}),React.createElement(AccuracyByPieceInsight,{analysis:e}),React.createElement(GamePhaseDeepDive,{analysis:e,games:t}),React.createElement(CastlingAnalysis,{analysis:e,games:t}),React.createElement(WinLossMethods,{analysis:e}))}function SkillDimensionSections({analysis:e,games:t,username:n,skipOpening:a=!1}){return!e||e.isHeuristic||(e.analyzedGames||[]).filter(i=>!i.isQuickMode).length===0?null:React.createElement(React.Fragment,null,!a&&React.createElement(OpeningDimension,{analysis:e,games:t}),React.createElement(TacticsDimension,{analysis:e,username:n}),React.createElement(EndgameDimension,{analysis:e}),React.createElement(ConversionDimension,{analysis:e}),React.createElement(TimeManagementDimension,{analysis:e,games:t}),React.createElement(ResourcefulnessDimension,{analysis:e}),React.createElement(ConsistencyDimension,{analysis:e,games:t}))}ReactDOM.createRoot(document.getElementById("root")).render(React.createElement(ChessProfileReport,null));
