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,__prCore=()=>window.LumiProfile.ProfileReportCore,parsePGNHeaders=(...e)=>__prCore().parsePGNHeaders(...e),openingNameFromHeaders=(...e)=>__prCore().openingNameFromHeaders(...e),extractClockTimes=(...e)=>__prCore().extractClockTimes(...e),getFenPhase=(...e)=>__prCore().getFenPhase(...e),classifyMoveByWinDrop=(...e)=>__prCore().classifyMoveByWinDrop(...e),cpToWinPct=(...e)=>__prCore().cpToWinPct(...e),moveAccuracy=(...e)=>__prCore().moveAccuracy(...e),capEval=(...e)=>__prCore().capEval(...e),uciFromVerboseMove=(...e)=>__prCore().uciFromVerboseMove(...e),computeRadarFromAnalysis=(...e)=>__prCore().computeRadarFromAnalysis(...e),computeHeuristicRadar=(...e)=>__prCore().computeHeuristicRadar(...e),analyzeGamesHeuristic=(...e)=>__prCore().analyzeGamesHeuristic(...e),computeCorrelations=(...e)=>__prCore().computeCorrelations(...e),detectPatterns=(...e)=>__prCore().detectPatterns(...e),fetchChessComGames=(...e)=>__prCore().fetchChessComGames(...e),fetchLichessProfile=(...e)=>__prCore().fetchLichessProfile(...e),fetchLichessGames=(...e)=>__prCore().fetchLichessGames(...e),_interpolateBenchmark=(...e)=>__prCore()._interpolateBenchmark(...e),_makeDimension=(...e)=>__prCore()._makeDimension(...e),_mean=(...e)=>__prCore()._mean(...e),_stdDev=(...e)=>__prCore()._stdDev(...e),computeInlineSkillProfile=(...e)=>__prCore().computeInlineSkillProfile(...e),computeInlineRecommendations=(...e)=>__prCore().computeInlineRecommendations(...e);class StockfishEngine{constructor(){this.worker=null,this.ready=!1}async init(){return new Promise((t,a)=>{try{const n=window.LumiAssets?.stockfishSingleWorkerUrl?.();if(!n)throw new Error("Stockfish asset loader unavailable");this.worker=new Worker(n)}catch(n){a(new Error("Failed to create Stockfish worker: "+n.message));return}const r=setTimeout(()=>a(new Error("Stockfish init timeout")),15e3),o=n=>{if((typeof n.data=="string"?n.data:n.data?.data||"").includes("uciok")){clearTimeout(r),this.ready=!0,this.worker.removeEventListener("message",o),this.worker.postMessage("setoption name Hash value 16"),this.worker.postMessage("isready");const i=s=>{(typeof s.data=="string"?s.data:"").includes("readyok")&&(this.worker.removeEventListener("message",i),t())};this.worker.addEventListener("message",i)}};this.worker.addEventListener("message",o),this.worker.postMessage("uci")})}newGame(){return this.ready?new Promise(t=>{this.worker.postMessage("ucinewgame"),this.worker.postMessage("isready");const a=r=>{(typeof r.data=="string"?r.data:"").includes("readyok")&&(this.worker.removeEventListener("message",a),t())};this.worker.addEventListener("message",a)}):Promise.resolve()}analyze(t,a=10){return new Promise((r,o)=>{let n={depth:0,score:0,type:"cp",raw:0,bestMove:null},c=!1;const i=setTimeout(()=>{if(!c){c=!0;try{this.worker?.removeEventListener("message",s)}catch{}try{this.worker?.postMessage("stop")}catch{}this.ready=!1,o(new Error("analyze timeout"))}},15e3),s=l=>{const d=typeof l.data=="string"?l.data:"";if(d.startsWith("info")&&d.includes("score")){const u=d.match(/\bdepth (\d+)/),g=d.match(/\bscore (cp|mate) (-?\d+)/),p=d.match(/\bpv (.+)/);if(u&&g){const h=parseInt(u[1]),w=g[1],S=parseInt(g[2]),x=w==="mate"?S>0?1e4-Math.abs(S)*10:-1e4+Math.abs(S)*10:S;h>=n.depth&&(n={depth:h,score:x,type:w,raw:S,bestMove:p?p[1].split(" ")[0]:null})}}if(d.startsWith("bestmove")){if(c)return;c=!0,clearTimeout(i),this.worker.removeEventListener("message",s);const u=d.split(" ")[1];u&&!n.bestMove&&(n.bestMove=u),r(n)}};this.worker.addEventListener("message",s),this.worker.postMessage("position fen "+t),this.worker.postMessage("go depth "+a)})}stop(){this.worker&&this.worker.postMessage("stop")}destroy(){this.worker&&(this.worker.postMessage("quit"),this.worker.terminate(),this.worker=null,this.ready=!1)}}function replayGame(e){if(!window.Chess)return null;const t=new Chess,a=e.replace(/\{[\s\S]*?\}/g,"").replace(/\$\d+/g,"").replace(/\d+\.\.\./g,"");try{t.loadPgn(a)}catch{return null}const r=t.history({verbose:!0});if(!r||r.length===0)return null;t.reset();const o=[t.fen()],n=[];for(const c of r)t.move(c.san),o.push(t.fen()),n.push(c.san);return{moves:r,positions:o,sanMoves:n}}const CLASSIFICATION_COLORS={brilliant:"#14e6e6",best:"#7bcc18",excellent:"#7bcc18",good:"#088a28",book:"#d5a47d",inaccuracy:"#ddd015",mistake:"#e5820d",blunder:"#d44242"},CLASSIFICATION_LABELS={brilliant:"Brilliancy",best:"Best",excellent:"Excellent",good:"Good",book:"Book",inaccuracy:"Inaccuracy",mistake:"Mistake",blunder:"Blunder"};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))))}const ProfileCache={_db:null,_ready:!1,async init(){if(!this._ready)try{this._db=await new Promise((e,t)=>{const a=indexedDB.open("lumichess-profile",1);a.onupgradeneeded=r=>{const o=r.target.result;o.objectStoreNames.contains("cache")||o.createObjectStore("cache",{keyPath:"key"})},a.onsuccess=()=>e(a.result),a.onerror=()=>t(a.error)}),this._ready=!0}catch(e){console.warn("ProfileCache init failed:",e.message)}},async _get(e){return this._ready?new Promise(t=>{try{const r=this._db.transaction("cache","readonly").objectStore("cache").get(e);r.onsuccess=()=>t(r.result||null),r.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(a){console.warn("ProfileCache write failed:",a.message)}},_key(e,...t){return`profile_${e}_${t.join("_")}`},async getGameAnalysis(e,t,a){return(await this._get(this._key("game",e,t,a)))?.data||null},async saveGameAnalysis(e,t,a,r){await this._put(this._key("game",e,t,a),{data:r,ts:Date.now()})},async getSnapshot(e,t){return(await this._get(this._key("snapshot",e,t)))?.data||null},async saveSnapshot(e,t,a){await this._put(this._key("snapshot",e,t),{data:a,ts:Date.now()})},async getFullReport(e,t){return(await this._get(this._key("full",e,t)))?.data||null},async saveFullReport(e,t,a){await this._put(this._key("full",e,t),{data:a,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,a){const r=await this.getHistory(e,t);r.push({...a,date:new Date().toISOString()});const o=r.slice(-20);await this._put(this._key("history",e,t),{entries:o,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"};async function analyzeGameWithEngine(e,t,a,r,o){const n=replayGame(e);if(!n)return null;const{positions:c,sanMoves:i,moves:s}=n,l=parsePGNHeaders(e),d=extractClockTimes(e),u=(l.White||"").toLowerCase()===o.toLowerCase()?"w":"b",g=window.LumiProfile?.MoveClassifier,p=window.LumiProfile?.Classification;await t.newGame();const h=[];let w=null;w=await t.analyze(c[0],a);let S=p?p.BOOKMOVE:null;for(let N=0;N<i.length;N++){const R=c[N],I=c[N+1],z=await t.analyze(I,a),W=Math.max(0,Math.min(300,capEval(w.score)+capEval(z.score))),P=N%2===0?"w":"b",G=P==="w"?-z.score:z.score,O=cpToWinPct(capEval(w.score)),K=cpToWinPct(capEval(-z.score)),j=Math.max(0,O-K),Z=moveAccuracy(j),J=R.includes(" b ")?-w.score:w.score,X=I.includes(" b ")?-z.score:z.score;let U="good",H=null;if(g&&p){const V=s[N]?uciFromVerboseMove(s[N]):null,te={fen:I,uciMove:V,san:i[N],lines:[{id:1,score:X,type:z.type||"cp",uciMove:z.bestMove||null}]},ae={fen:R,classification:S,lines:[{id:1,score:J,type:w.type||"cp",uciMove:w.bestMove||null}]};try{H=g.classifyMove(te,ae,i.slice(0,N+1)),S=H;const Y=H?.type||"good";U=MC_TYPE_TO_LEGACY[Y]||"good"}catch(Y){console.warn("[profile-report] classifyMove threw; falling back to good:",Y?.message||Y),U="good"}}const Q=H?.type,ee=Q==="bookmove"||Q==="forced";let q;if(ee)q=100;else{const V=(H?.accuracy??.84)*100;q=.25*Z+.75*V}h.push({moveNumber:Math.floor(N/2)+1,san:i[N],turn:P,cpl:W,classification:U,gamePhase:getFenPhase(I,N),evalBefore:w.score,evalAfter:z.score,whiteEval:G,bestMove:w.bestMove,clock:d[N]||null,isPlayerMove:P===u,accuracy:q}),w=z,r&&r(N+1,i.length)}const x=h.filter(N=>N.isPlayerMove),f=h.filter(N=>!N.isPlayerMove),v=x.length>0?x.reduce((N,R)=>N+R.cpl,0)/x.length:0,y=f.length>0?f.reduce((N,R)=>N+R.cpl,0)/f.length:0,m=x.length>0?x.reduce((N,R)=>N+R.accuracy,0)/x.length:0,b=f.length>0?f.reduce((N,R)=>N+R.accuracy,0)/f.length:0,k={};for(const N of x)k[N.classification]=(k[N.classification]||0)+1;const A=x.filter(N=>N.gamePhase==="opening"),E=x.filter(N=>N.gamePhase==="middlegame"),M=x.filter(N=>N.gamePhase==="endgame"),T=A.length>0?A.reduce((N,R)=>N+R.cpl,0)/A.length:0,D=E.length>0?E.reduce((N,R)=>N+R.cpl,0)/E.length:0,_=M.length>0?M.reduce((N,R)=>N+R.cpl,0)/M.length:0,C=h.map(N=>N.whiteEval),B=C.some(N=>(u==="w"?N:-N)>=150),L=C.some(N=>(u==="w"?N:-N)<=-150),$=C.map(N=>u==="w"?N:-N),F=$.length>0?Math.max(...$):0;return{pgn:e,headers:l,playerColor:u,totalMoves:i.length,moveAnalysis:h,playerAccuracy:Math.round(m*10)/10,opponentAccuracy:Math.round(b*10)/10,playerAvgCpl:Math.round(v*10)/10,classifications:k,openingCpl:Math.round(T*10)/10,middlegameCpl:Math.round(D*10)/10,endgameCpl:Math.round(_*10)/10,wasWinning:B,wasLosing:L,maxAdvantage:Math.round(F),evalGraph:C,clocks:d}}function analyzeGameFromChessComAccuracy(e,t,a){const r=replayGame(e);if(!r)return null;const{sanMoves:o}=r,n=parsePGNHeaders(e),c=extractClockTimes(e),i=(n.White||"").toLowerCase()===a.toLowerCase()?"w":"b",s=o.map((l,d)=>{const u=d%2===0?"w":"b";return{moveNumber:Math.floor(d/2)+1,san:l,turn:u,cpl:null,classification:null,evalBefore:null,evalAfter:null,whiteEval:null,bestMove:null,clock:c[d]||null,isPlayerMove:u===i,accuracy:null}});return{pgn:e,headers:n,playerColor:i,totalMoves:o.length,moveAnalysis:s,playerAccuracy:t||0,opponentAccuracy:0,playerAvgCpl:0,classifications:null,openingCpl:0,middlegameCpl:0,endgameCpl:0,wasWinning:!1,wasLosing:!1,maxAdvantage:0,evalGraph:null,clocks:c,isQuickMode:!0}}function buildAnalysisFromEngine(e,t,a){const r=analyzeGamesHeuristic(t,a),o=e.filter(y=>y!==null);if(o.length===0)return r;const n=o.reduce((y,m)=>y+m.playerAccuracy,0)/o.length,c={};o.forEach(y=>{Object.entries(y.classifications||{}).forEach(([m,b])=>{c[m]=(c[m]||0)+b})});const i=computeRadarFromAnalysis(e,t,a),s=Math.round(i.reduce((y,m)=>y+m.value,0)/i.length);let l="Balanced Player";const d=c.blunder||0,u=o.reduce((y,m)=>y+m.moveAnalysis.filter(b=>b.isPlayerMove).length,0),g=d/Math.max(1,u);n>85?l="Precision Player":g>.08?l="Tactical Risk-Taker":r.timeoutLosses>r.losses*.4?l="Time Scrambler":r.avgMoves<25&&(l="Aggressive Attacker");let p=null,h=[],w=null,S=s;try{const y=window.LumiProfile?.SkillProfile,m=window.LumiProfile?.Recommendations,b=window.LumiProfile?.CoachingInsights;if(y&&m){const k=o.map((A,E)=>convertToCoachingRecord(A,t[E])).filter(Boolean);if(k.length>0){const A=a?.blitz?.current||a?.rapid?.current||a?.bullet?.current||1200;if(p=y.compute(k,A),h=m.generate(p,A),b)try{w=b.generate(k,p,A)}catch(M){console.warn("CoachingInsights.generate failed:",M.message)}const E=Object.values(p.dimensions).filter(M=>M.score!=null);E.length>0&&(S=Math.round(E.reduce((M,T)=>M+T.score,0)/E.length))}}}catch(y){console.warn("6D coaching computation failed, using 8D fallback:",y.message)}const x=o.filter(y=>!y.isQuickMode&&y.wasLosing),f=x.filter(y=>{const m=y.headers?.Result;return y.playerColor==="w"&&m==="1-0"||y.playerColor==="b"&&m==="0-1"||m==="1/2-1/2"}),v=x.length>0?{total:x.length,saved:f.length,rate:Math.round(f.length/x.length*100)}:null;return{...r,avgAccuracy:Math.round(n*10)/10,radar:i,lumiScore:S,personality:l,totalClassifications:c,analyzedGames:o,isHeuristic:!1,skillProfile:p,recommendations:h,insights:w,resourcefulness:v}}function convertToCoachingRecord(e,t){if(!e||e.isQuickMode)return null;const a=e.moveAnalysis.filter(z=>z.isPlayerMove),r=a.length;if(r===0)return null;let o=0,n=null;const c=window.LumiProfile?.OpeningBook;if(c&&c.loaded&&e.pgn)try{const z=replayGame(e.pgn);if(z){const W=c.getDeviation(z.positions);if(o=W.inBookMoves,W.deviationIndex>0&&W.deviationIndex<e.moveAnalysis.length){const P=e.moveAnalysis[W.deviationIndex];P&&(n=e.playerColor==="w"?P.whiteEval:-P.whiteEval,n=n/100)}}}catch{}if(o===0)for(const z of a)if(z.classification==="book"||z.classification==="best"||z.classification==="excellent")o++;else break;const i=Math.ceil(o/2),s=a.slice(i,i+6),l=s.length>0?s.reduce((z,W)=>z+W.accuracy,0)/s.length:50;let d=!1,u=!1,g=15;const p=e.pgn?replayGame(e.pgn):null,h=e.moveAnalysis;for(let z=0;z<h.length;z++){const W=h[z],P=W.moveNumber||Math.floor(z/2)+1;if(P>15)break;if(W.san&&(W.san==="O-O"||W.san==="O-O-O")&&(d=!0),!u&&p&&p.positions&&p.positions[z+1]){const G=p.positions[z+1].split(" ")[0];!G.includes("Q")&&!G.includes("q")&&(u=!0)}if(d&&u){g=P;break}}const w=a.filter(z=>(z.moveNumber||1)<=g),S=w.length>0?w.reduce((z,W)=>z+(W.accuracy||0),0)/w.length:50,x=["mistake","blunder"],f=["brilliant","best","excellent","good"];let v=0,y=0;const m=e.moveAnalysis.filter(z=>!z.isPlayerMove);for(const z of m)if(x.includes(z.classification)){v++;const W=a.find(P=>P.moveNumber>=z.moveNumber&&(z.turn==="w"?P.turn==="b":P.turn==="w"));W&&f.includes(W.classification)&&y++}const b=e.moveAnalysis.map(z=>{const W=z.whiteEval;return e.playerColor==="w"?W:-W}),k=b.length>0?Math.max(...b):0,A=b.length>0?Math.min(...b):0,E=k>=150,M=A<=-150,T=e.headers?.Result,D=e.playerColor==="w"&&T==="1-0"||e.playerColor==="b"&&T==="0-1",_=T==="1/2-1/2",C=E&&D,B=M&&(D||_),L=a.filter(z=>z.gamePhase==="endgame"),$=L.length>0?L.reduce((z,W)=>z+(W.accuracy||0),0)/L.length:50,F=a.filter(z=>z.clock!==null&&z.clock<30).length,N=E?1:0,R=E&&(D||_)?1:0,I=E&&!D&&!_?1:0;return{book_depth:o,post_book_accuracy:l,opening_accuracy:S,exit_eval:n,tactical_found:y,tactical_moments:Math.max(1,v),endgame_positions:L.length,had_advantage:E?1:0,converted:C?1:0,was_losing:M?1:0,saved:B?1:0,winning_positions:N,advantage_held:R,advantage_lost:I,eg_accuracy:$,overall_accuracy:e.playerAccuracy,time_trouble_moves:F,total_moves:r}}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(a=>{if(!a)return;const r=a.headers?.Result,o=a.playerColor;let n;r==="1/2-1/2"?n="draw":o==="w"&&r==="1-0"||o==="b"&&r==="0-1"?n="win":(r==="1-0"||r==="0-1")&&(n="loss"),n&&a.playerAccuracy!=null&&t[n].push(a.playerAccuracy)}),Object.fromEntries(Object.entries(t).map(([a,r])=>[a,{count:r.length,avg:r.length>0?Math.round(r.reduce((o,n)=>o+n,0)/r.length*10)/10:null}]))}function computeAccuracyByMoveNumber(e){const t={};e.forEach(o=>{!o||o.isQuickMode||o.moveAnalysis.filter(n=>n.isPlayerMove&&n.accuracy!==null).forEach(n=>{t[n.moveNumber]||(t[n.moveNumber]=[]),t[n.moveNumber].push(n.accuracy)})});const a=Math.min(60,Math.max(...Object.keys(t).map(Number),1)),r=[];for(let o=1;o<=a;o++){const n=t[o]||[];n.length>=2&&r.push({move:o,accuracy:Math.round(n.reduce((c,i)=>c+i,0)/n.length*10)/10,games:n.length})}return r}function computePieceAccuracy(e){const t={};return PIECE_ORDER.forEach(a=>{t[a]={totalAcc:0,count:0}}),e.forEach(a=>{!a||a.isQuickMode||a.moveAnalysis.filter(r=>r.isPlayerMove&&r.accuracy!==null).forEach(r=>{const o=pieceFromSan(r.san);o&&t[o]&&(t[o].totalAcc+=r.accuracy,t[o].count++)})}),PIECE_ORDER.map(a=>({piece:a,name:PIECE_NAMES[a],accuracy:t[a].count>0?Math.round(t[a].totalAcc/t[a].count*10)/10:0,moves:t[a].count,color:PIECE_COLORS[a]})).filter(a=>a.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}},a={opening:[],middlegame:[],endgame:[]};return e.forEach(r=>{if(!r)return;const o=r.totalMoves||r.moveAnalysis?.length||40,n=o<=20?"opening":o<=40?"middlegame":"endgame";t[n].games++;const c=r.headers?.Result,i=r.playerColor;i==="w"&&c==="1-0"||i==="b"&&c==="0-1"?t[n].wins++:(c==="1-0"||c==="0-1")&&c!=="1/2-1/2"&&t[n].losses++,r.isQuickMode?a[n].push(r.playerAccuracy):(r.openingCpl!==void 0&&a.opening.push(Math.max(0,100-r.openingCpl*1.2)),r.middlegameCpl!==void 0&&a.middlegame.push(Math.max(0,100-r.middlegameCpl*.8)),r.endgameCpl!==void 0&&a.endgame.push(Math.max(0,100-r.endgameCpl*1)))}),Object.fromEntries(Object.entries(t).map(([r,o])=>{const n=a[r];return[r,{...o,draws:o.games-o.wins-o.losses,winRate:o.games>0?Math.round(o.wins/o.games*100):0,accuracy:n.length>0?Math.round(n.reduce((c,i)=>c+i,0)/n.length*10)/10:0,accSamples:n.length}]}))}function computeCastlingStats(e){let t=0,a=0,r=0;const o={kingside:{win:0,loss:0,draw:0},queenside:{win:0,loss:0,draw:0},none:{win:0,loss:0,draw:0}},n=[],c=l=>{const d=l.headers?.Result,u=l.playerColor;return d==="1/2-1/2"?"draw":u==="w"&&d==="1-0"||u==="b"&&d==="0-1"?"win":d==="1-0"||d==="0-1"?"loss":null};e.forEach(l=>{if(!l)return;const u=l.moveAnalysis.filter(p=>p.isPlayerMove).find(p=>p.san&&p.san.startsWith("O-O")),g=c(l);g&&(u?(u.san==="O-O-O"?(a++,o.queenside[g]++):(t++,o.kingside[g]++),n.push(u.moveNumber)):(r++,o.none[g]++))});const i=t+a+r,s=n.length>0?Math.round(n.reduce((l,d)=>l+d,0)/n.length*10)/10:0;return{kingSide:t,queenSide:a,noCastle:r,total:i,avgCastleMove:s,castleResults:o,castledPct:i>0?Math.round((t+a)/i*100):0}}function computeOpeningDeepDive(e){const t={};return e.forEach(a=>{if(!a)return;const r=openingNameFromHeaders(a.headers||{}),o=a.headers?.Result,n=a.playerColor,c=n==="w"&&o==="1-0"||n==="b"&&o==="0-1",i=o==="1/2-1/2",s=(o==="1-0"||o==="0-1")&&!c;if(!(!c&&!i&&!s)&&(t[r]||(t[r]={wins:0,losses:0,draws:0,accuracies:[],bookDepths:[],color:n}),c?t[r].wins++:s?t[r].losses++:t[r].draws++,a.playerAccuracy!=null&&t[r].accuracies.push(a.playerAccuracy),!a.isQuickMode)){const l=a.moveAnalysis.filter(u=>u.isPlayerMove);let d=0;for(const u of l)if(u.classification==="book"||u.classification==="best"||u.classification==="excellent")d++;else break;t[r].bookDepths.push(d)}}),Object.entries(t).map(([a,r])=>{const o=r.wins+r.losses+r.draws;return{name:a,total:o,wins:r.wins,losses:r.losses,draws:r.draws,winRate:o>0?Math.round(r.wins/o*100):0,avgAccuracy:r.accuracies.length>0?Math.round(r.accuracies.reduce((n,c)=>n+c,0)/r.accuracies.length*10)/10:null,avgBookDepth:r.bookDepths.length>0?Math.round(r.bookDepths.reduce((n,c)=>n+c,0)/r.bookDepths.length*10)/10:null}}).sort((a,r)=>r.total-a.total)}function gamesFromSlimRows(e){return(e||[]).map(t=>({result:t.r,color:t.c,eco:t.eco,moves:t.mv,accuracy:t.a,finalClock:t.fc,timeClass:t.tc,opening:t.op,white:t.w,black:t.b,wRating:t.wr,bRating:t.br,date:t.dt,url:t.url}))}function withOpeningNames(e){const t=window.LumiProfile?.ProfileReportCore?.formatOpeningName;if(!e||!t)return e;const a=e.metrics||{},r=o=>Array.isArray(o)?o.map(n=>n&&n.name?{...n,name:t(n.name)}:n):o;return{...e,metrics:{...a,sc:a.sc?{...a.sc,openings:r(a.sc.openings)}:a.sc,openingDeep:r(a.openingDeep),openingDim:a.openingDim?{...a.openingDim,allOpeningsList:r(a.openingDim.allOpeningsList)}:a.openingDim},games:(e.games||[]).map(o=>o&&o.op?{...o,op:t(o.op)}:o)}}function rehydrateInsights(e){const t=window.LumiProfile?.CoachingInsights;try{return t?.rehydrate?t.rehydrate(e||null):e||null}catch(a){return console.warn("[insights] rehydrate failed:",a?.message||a),e||null}}function buildSlimAnalysis(e,t){const a=t&&t.metrics||{};return{...a.sc||{},analyzedGames:[],games:e.games&&e.games.length?e.games:gamesFromSlimRows(t.games),metrics:a,slimGames:t.games,__slim:!0,insights:e.insights||null,profile:a.profile||e.profile||null,stats:a.stats||e.stats||null,analysisTime:e.analysisTime||null}}function apiGameToMetadata(e,t){const a=e.white?.username?.toLowerCase()===t.toLowerCase(),r=a?e.white:e.black,o=a?e.black:e.white,n=r.result==="win"?"win":r.result==="agreed"||r.result==="repetition"||r.result==="stalemate"||r.result==="insufficient"||r.result==="50move"?"draw":"loss",c=r.result==="win"?o.result||"resigned":r.result==="checkmated"?"checkmate":r.result||"unknown",i=parsePGNHeaders(e.pgn||""),l=((e.pgn||"").replace(/\[[^\]]*\]/g,"").replace(/\{[^}]*\}/g,"").match(/\b\d+\./g)||[]).length;return{date:i.Date?i.Date.replace(/\./g,"-"):new Date((e.end_time||0)*1e3).toISOString().slice(0,10),white:i.White||e.white?.username||"?",black:i.Black||e.black?.username||"?",wRating:e.white?.rating||parseInt(i.WhiteElo)||1400,bRating:e.black?.rating||parseInt(i.BlackElo)||1400,result:n,method:c,eco:i.ECO||"?",opening:openingNameFromHeaders(i),moves:l,accuracy:e.accuracies?a?e.accuracies.white:e.accuracies.black:null,timeControl:e.time_control||i.TimeControl||"?",timeClass:e.time_class||"blitz",color:a?"white":"black",finalClock:(()=>{const d=extractClockTimes(e.pgn||"");if(d.length===0)return null;const u=d.filter((g,p)=>a?p%2===0:p%2===1);return u.length>0?u[u.length-1]:null})(),pgn:e.pgn||null}}function lichessGameToMetadata(e,t){if(!e.players?.white||!e.players?.black)return null;const a=(e.players.white.user?.name||e.players.white.user?.id||"").toLowerCase()===t.toLowerCase(),r=a?e.players.white:e.players.black,o=a?e.players.black:e.players.white;let n;e.winner?e.winner==="white"===a?n="win":n="loss":n="draw";const c={mate:"checkmate",resign:"resigned",timeout:"timeout",outoftime:"timeout",stalemate:"stalemate",draw:"agreement"},i=c[e.status]||e.status;let s="";if(e.clock){const h=Math.floor(e.clock.initial/60),w=e.clock.increment||0;s=`${h*60}+${w}`}const l={ultraBullet:"bullet",bullet:"bullet",blitz:"blitz",rapid:"rapid",classical:"classical",correspondence:"daily"},d=e.moves?e.moves.split(" ").length:0,u=Math.ceil(d/2);let g=null;if(e.clocks&&e.clocks.length>0){const h=e.clocks.filter((w,S)=>a?S%2===0:S%2===1);h.length>0&&(g=h[h.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:n,method:i,eco:e.opening?.eco||"?",opening:e.opening?.name||"Unknown",moves:u,accuracy:null,timeControl:s,timeClass:l[e.speed]||"blitz",color:a?"white":"black",finalClock:g,pgn:e.pgn||null,lichessId:e.id,hasServerEvals:!!(e.analysis&&e.analysis.length>0),serverAnalysis:e.analysis||null}}function analyzeGameFromLichessEvals(e,t,a){const r=e.analysis;if(!r||r.length===0)return null;const o=(e.moves||"").split(" ").filter(Boolean);if(o.length===0)return null;const n=t.color==="white"?"w":"b",c=t.pgn?replayGame(t.pgn):null,i=c?c.positions:null,s=[];for(let y=0;y<o.length&&y<r.length;y++){const m=r[y],b=y%2===0?"w":"b";let k;m.eval!==void 0?k=m.eval:m.mate!==void 0?k=m.mate>0?1e4-Math.abs(m.mate)*10:-1e4+Math.abs(m.mate)*10:k=0;const A=k,E=b==="w"?-k:k,M=y>0?r[y-1].eval!==void 0?r[y-1].eval:r[y-1].mate!==void 0?r[y-1].mate>0?9990:-9990:0:0,T=cpToWinPct(b==="w"?M:-M),D=cpToWinPct(b==="w"?k:-k),_=Math.max(0,T-D),C=moveAccuracy(_),B=Math.round(Math.max(0,M-k)*(b==="w"?1:-1)),L=classifyMoveByWinDrop(_);let $=C;L==="book"||L==="brilliant"||L==="best"?$=100:L==="excellent"?$=Math.max($,98):L==="good"&&($=Math.max($,95));const F=i?i[y+1]:null;s.push({moveNumber:Math.floor(y/2)+1,san:o[y],turn:b,cpl:B,classification:L,gamePhase:getFenPhase(F,y),evalBefore:y>0?b==="w"?M:-M:0,evalAfter:E,whiteEval:A,bestMove:m.best||null,clock:t.finalClock,isPlayerMove:b===n,accuracy:$})}const l=s.filter(y=>y.isPlayerMove),d=s.filter(y=>!y.isPlayerMove),u=l.length>0?l.reduce((y,m)=>y+m.accuracy,0)/l.length:0,g=d.length>0?d.reduce((y,m)=>y+m.accuracy,0)/d.length:0,p={};for(const y of l)p[y.classification]=(p[y.classification]||0)+1;const h=l.filter(y=>y.gamePhase==="opening"),w=l.filter(y=>y.gamePhase==="middlegame"),S=l.filter(y=>y.gamePhase==="endgame"),x=y=>y.length>0?y.reduce((m,b)=>m+b.cpl,0)/y.length:0,f=s.map(y=>y.whiteEval),v=f.map(y=>n==="w"?y:-y);return{pgn:e.pgn||"",headers:{White:t.white,Black:t.black,Date:t.date,Result:t.result==="win"?n==="w"?"1-0":"0-1":t.result==="loss"?n==="w"?"0-1":"1-0":"1/2-1/2",TimeControl:t.timeControl},playerColor:n,totalMoves:o.length,moveAnalysis:s,playerAccuracy:Math.round(u*10)/10,opponentAccuracy:Math.round(g*10)/10,playerAvgCpl:Math.round(x(l)*10)/10,classifications:p,openingCpl:Math.round(x(h)*10)/10,middlegameCpl:Math.round(x(w)*10)/10,endgameCpl:Math.round(x(S)*10)/10,wasWinning:v.some(y=>y>=150),wasLosing:v.some(y=>y<=-150),maxAdvantage:Math.round(Math.max(0,...v)),evalGraph:f,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}];function readProfileDepth(){try{const e=document.cookie.match(/(?:^|;\s*)centichess_setting_profileReportDepth=([^;]+)/);if(e){const t=JSON.parse(decodeURIComponent(e[1]));if(typeof t=="number"&&t>=0&&t<=30)return t}}catch{}return 10}const initialState={phase:"ready",username:"",platform:"chesscom",accounts:[],depth:readProfileDepth(),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,_loadedAnalysis:null,_loadedSlim: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(r=>r.platform===t.platform&&r.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((a,r)=>r!==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 a=t.p||{},r=a.aggregates||{},o=a.metrics?withOpeningNames({metrics:a.metrics,games:a.games||[]}):null;return{...initialState,phase:"complete",username:a.username||"",platform:a.platform||"chesscom",format:a.format||"rapid",depth:a.depth||10,gameCount:a.gameCount||40,profile:r.profile||o?.metrics?.profile||null,stats:r.stats||o?.metrics?.stats||null,games:r.games&&r.games.length?r.games:gamesFromSlimRows(o?.games),analyzedGames:r.analyzedGames||[],correlations:r.correlations||null,patterns:r.patterns||null,analysisTime:r.analysisTime||null,_loadedAnalysis:a.aggregates||o?{...r,insights:rehydrateInsights(a.insights)}:null,_loadedSlim:o,_loadedReportId:a.id||null,_historyList:e._historyList||[],signedIn:e.signedIn}}case"SET_HISTORY_LIST":return{...e,_historyList:t.rows||[]};case"RESET":return{...initialState,signedIn:e.signedIn,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||[],signedIn:e.signedIn};default:return e}}function StatBox({label:e,value:t,sub:a,color:r="white",large:o,icon:n}){return n?React.createElement("div",{className:"pr-stat-box",style:{display:"flex",alignItems:"center",gap:12}},React.createElement("span",{style:{display:"inline-flex",lineHeight:0,opacity:.7},dangerouslySetInnerHTML:{__html:n}}),React.createElement("div",null,React.createElement("div",{className:"pr-label",style:{marginTop:6}},e),React.createElement("div",{className:o?"pr-stat-value--lg":"pr-stat-value",style:{color:r}},t),a&&React.createElement("div",{className:"pr-dim pr-mt-1"},a))):React.createElement("div",{className:"pr-stat-box"},React.createElement("div",{className:"pr-label"},e),React.createElement("div",{className:o?"pr-stat-value--lg":"pr-stat-value",style:{color:r}},t),a&&React.createElement("div",{className:"pr-dim pr-mt-1"},a))}function TcMark({tc:e,size:t=13}){const a=TREND_COLORS[e];if(!a)return null;const r={width:t,height:t,viewBox:"0 0 24 24","aria-hidden":"true",style:{flex:"none",display:"block"}},o=TC_LABEL[e]||e;return e==="bullet"?React.createElement("svg",{...r,fill:a},React.createElement("title",null,o),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"})):e==="blitz"?React.createElement("svg",{...r,fill:a,stroke:"none"},React.createElement("title",null,o),React.createElement("polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2"})):e==="daily"||e==="classical"?React.createElement("svg",{...r,fill:"none",stroke:a,strokeWidth:"2.4",strokeLinecap:"round"},React.createElement("title",null,o),React.createElement("circle",{cx:"12",cy:"12",r:"9"}),React.createElement("path",{d:"M12 7v5l3.2 1.8"})):React.createElement("svg",{...r,fill:"none",stroke:a,strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"},React.createElement("title",null,o),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"}))}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 WorstGamesShell({children:e}){return React.createElement(SectionCard,{title:"Your three worst games",badge:"data-driven",delay:.5},React.createElement("p",{style:{color:"var(--pr-text-primary)",fontSize:16,lineHeight:1.55,fontWeight:500,margin:"0 0 18px"}},"This is where the patterns above actually cost you. Reviewing a game move by move is the fastest way to turn a number into something you can fix."),React.createElement("div",{style:{display:"flex",flexDirection:"column",gap:10}},e))}function WorstGamesSlim({games:e}){return React.createElement(WorstGamesShell,null,e.map((t,a)=>{const o=(String(t.color||"").toLowerCase().startsWith("b")?t.white:t.black)||"Opponent",n=String(t.result||"").toLowerCase(),c=n==="draw"?{text:"Draw",color:"var(--pr-text-secondary)"}:n==="win"?{text:"Win",color:"#5DB67D"}:n==="loss"?{text:"Loss",color:"#CF6E6E"}:null;return React.createElement("div",{key:a,style:{display:"flex",alignItems:"center",gap:14,flexWrap:"wrap",padding:"14px 16px",borderRadius:12,background:"rgba(255,255,255,0.03)",border:"1px solid rgba(255,255,255,0.06)"}},React.createElement("div",{style:{minWidth:62}},React.createElement("div",{style:{fontSize:22,fontWeight:700,color:"#CF6E6E",lineHeight:1.1}},Math.round(t.accuracy),"%"),React.createElement("div",{style:{fontSize:12,color:"var(--pr-text-secondary)"}},"accuracy")),React.createElement("div",{style:{flex:"1 1 300px",minWidth:0}},React.createElement("div",{style:{display:"flex",alignItems:"baseline",gap:8,minWidth:0}},React.createElement("span",{style:{fontWeight:600,color:"var(--pr-text-primary)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}},"vs ",o),c&&React.createElement("span",{style:{color:c.color,fontWeight:600,fontSize:13,flexShrink:0}},c.text)),React.createElement("div",{style:{fontSize:13,color:"var(--pr-text-secondary)"}},t.date?String(t.date).replace(/\./g,"-"):"")),React.createElement("button",{type:"button",className:"pr-btn pr-btn--primary",onClick:()=>{window.LumiAnalytics?.track("worst_game_review_opened",{rank:a+1,accuracy:Math.round(t.accuracy),mode:"slim"}),window.open(`/game/report?url=${encodeURIComponent(t.url)}`,"_blank")},style:{background:"var(--lumi-accent)",color:"#1a1a17",whiteSpace:"nowrap"}},"Review this game"))}))}function openPgnReview(e,t){const a=e.headers||{},r={source:"pgn",white:{username:a.White||"White"},black:{username:a.Black||"Black"},result:a.Result||"*",timeControl:{display:a.TimeControl||""},date:a.Date||"",analyzedAs:e.playerColor==="b"?"black":"white"};try{sessionStorage.setItem("lumichess_game_pgn",e.pgn),sessionStorage.setItem("lumichess_game_meta",JSON.stringify(r))}catch{return}window.LumiAnalytics?.track("worst_game_review_opened",{rank:t,accuracy:Math.round(e.playerAccuracy)}),window.open("/game/report","_blank")}function WorstGamesToReview({analysis:e}){const t=e?.__slim?(e.games||[]).filter(n=>n&&n.url&&Number.isFinite(n.accuracy)).sort((n,c)=>n.accuracy-c.accuracy).slice(0,3):null,a=(e?.analyzedGames||[]).filter(n=>n&&!n.isQuickMode&&n.pgn&&Number.isFinite(n.playerAccuracy));if(t)return t.length<3?null:React.createElement(WorstGamesSlim,{games:t});if(a.length<3)return null;const r=[...a].sort((n,c)=>n.playerAccuracy-c.playerAccuracy).slice(0,3),o=n=>{const c=n.headers?.Result;return c==="1/2-1/2"?{text:"Draw",color:"var(--pr-text-secondary)"}:c==="1-0"&&n.playerColor!=="b"||c==="0-1"&&n.playerColor==="b"?{text:"Win",color:"#5DB67D"}:{text:"Loss",color:"#CF6E6E"}};return React.createElement(WorstGamesShell,null,r.map((n,c)=>{const i=n.headers||{},s=n.playerColor==="b"?i.White||"Opponent":i.Black||"Opponent",l=n.classifications?.blunder||0,d=o(n);return React.createElement("div",{key:c,style:{display:"flex",alignItems:"center",gap:14,flexWrap:"wrap",padding:"14px 16px",borderRadius:12,background:"rgba(255,255,255,0.03)",border:"1px solid rgba(255,255,255,0.06)"}},React.createElement("div",{style:{minWidth:62}},React.createElement("div",{style:{fontSize:22,fontWeight:700,color:"#CF6E6E",lineHeight:1.1}},Math.round(n.playerAccuracy),"%"),React.createElement("div",{style:{fontSize:12,color:"var(--pr-text-secondary)"}},"accuracy")),React.createElement("div",{style:{flex:"1 1 300px",minWidth:0}},React.createElement("div",{style:{display:"flex",alignItems:"baseline",gap:8,minWidth:0}},React.createElement("span",{style:{fontWeight:600,color:"var(--pr-text-primary)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}},"vs ",s),React.createElement("span",{style:{color:d.color,fontWeight:600,fontSize:13,flexShrink:0}},d.text)),React.createElement("div",{style:{fontSize:13,color:"var(--pr-text-secondary)"}},[l>0?`${l} blunder${l===1?"":"s"}`:null,i.Date?i.Date.replace(/\./g,"-"):null].filter(Boolean).join(" \xB7 "))),React.createElement("button",{type:"button",className:"pr-btn pr-btn--primary",onClick:()=>openPgnReview(n,c+1),style:{background:"var(--lumi-accent)",color:"#1a1a17",whiteSpace:"nowrap"}},"Review this game"))}))}function SectionCard({title:e,badge:t,children:a,className:r="",delay:o=0}){return React.createElement("div",{className:`pr-card pr-animate-section ${r}`,style:{animationDelay:`${o}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)),a)}function ProgressBar({value:e,max:t=100,color:a="#5DB67D",height:r=6,label:o,showPct:n=!0}){const c=Math.min(100,Math.round(e/t*100));return React.createElement("div",{className:"pr-row--3"},o&&React.createElement("span",{className:"pr-meta pr-text-right pr-shrink-0",style:{width:80}},o),React.createElement("div",{className:"pr-flex-1 pr-progress-bar",style:{height:r,background:"rgba(255,255,255,0.04)"}},React.createElement("div",{className:"pr-progress-bar__fill",style:{width:`${c}%`,background:a}})),n&&React.createElement("span",{className:"pr-text-xs pr-font-bold pr-text-right",style:{color:a,width:40}},c,"%"))}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:a,phase:r}=e,o=t.totalGames>0?Math.round(a.length/t.totalGames*100):0,n=a.filter(i=>i),c=n.length>0?Math.round(n.reduce((i,s)=>i+s.playerAccuracy,0)/n.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"}},r==="fetching"?"Fetching Games...":e.depth===0?"Processing Games...":"Analyzing Moves..."),React.createElement("p",{style:{fontSize:16,color:"#E8E4DF",margin:0,lineHeight:1.4}},r==="fetching"?`Loading ${e.platform==="lichess"?"Lichess":"Chess.com"} games for ${e.username}...`:`Game ${Math.min(a.length+1,t.totalGames)} of ${t.totalGames}`)),r==="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"}},o,"%")),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:`${o}%`,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}},c!==null?`${c}%`:"\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}},n.length)))))}function InlineProgress({state:e}){const{progress:t,analyzedGames:a,phase:r,cachedGamesCount:o}=e,n=t.totalGames>0?Math.round(a.length/t.totalGames*100):0,c=a.filter(i=>i).length>0?Math.round(a.filter(i=>i).reduce((i,s)=>i+s.playerAccuracy,0)/a.filter(i=>i).length*10)/10:null;return React.createElement("div",{className:"pr-max-w-lg pr-transient"},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"},r==="fetching"?"Fetching Games...":e.depth===0?"Processing Games...":"Analyzing Moves..."),React.createElement("p",{className:"pr-body pr-text-muted"},r==="fetching"?`Loading ${e.platform==="lichess"?"Lichess":"Chess.com"} games for ${e.username}...`:`Game ${Math.min(a.length+1,t.totalGames)} of ${t.totalGames}`)),r==="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"},n,"%")),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:`${n}%`,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"}}))),c!==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"}},c,"%")),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"}},a.length))))))}function InlineError({error:e,onRetry:t}){return React.createElement("div",{className:"pr-max-w-lg pr-transient"},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 pr-btn--primary"},"Try Again")))}function SelectionScreen({state:e,dispatch:t,onStart:a,onLoadHistory:r}){const[o,n]=useState(!1),[c,i]=useState(!1),[s,l]=useState(""),d=e._historyList||[],u=!!e.username.trim(),g=()=>{if(!u){l("Enter your username first.");const v=document.getElementById("pr-username");v&&v.focus();return}l("");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{}a()},p=[{id:"rapid",label:"Rapid"},{id:"blitz",label:"Blitz"},{id:"bullet",label:"Bullet"},{id:"classical",label:"Classical"}],h=e.depth<=10?"Fast":e.depth<=18?"Standard":"Deep",w=({platform:v,size:y=22,color:m})=>{if(v==="chesscom"){const k=m||"#81B64C";return React.createElement("svg",{width:y,height:y,viewBox:"0 1.5 50 50","aria-hidden":"true"},React.createElement("ellipse",{cx:"25",cy:"18.126",fill:k,stroke:"rgba(0,0,0,0.35)",strokeLinejoin:"round",rx:"7.161",ry:"6.834"}),React.createElement("path",{fill:k,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:k,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 b=m||"#F0EBE0";return React.createElement("svg",{width:y,height:y,viewBox:"0 0 50 50","aria-hidden":"true"},React.createElement("path",{fill:b,stroke:b,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"}))},S={all:"#D4A44B",rapid:"#81B64C",blitz:"#FFBF00",bullet:"#E8A035",classical:"#6B9FD4"},x=({format:v,size:y=18})=>{const m=S[v]||"var(--pr-text-body)";return v==="all"?React.createElement("svg",{width:y,height:y,viewBox:"0 0 24 24",fill:"none",stroke:m,strokeWidth:"2.4",strokeLinecap:"round","aria-hidden":"true"},React.createElement("path",{d:"M4 7h16M4 12h11M4 17h7"})):v==="classical"?React.createElement("svg",{width:y,height:y,viewBox:"0 0 24 24",fill:"none",stroke:m,strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},React.createElement("path",{d:"M6 3h12M6 21h12M8 3c0 4 8 5 8 9s-8 5-8 9M16 3c0 4-8 5-8 9s8 5 8 9"})):v==="rapid"?React.createElement("svg",{width:y,height:y,viewBox:"0 0 24 24",fill:"none",stroke:m,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:y,height:y,viewBox:"0 0 24 24",fill:m,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:y,height:y,viewBox:"0 0 24 24",fill:m,"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},f={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",{className:"prs-hero__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",{className:"prs-hero__sub",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}},"Stockfish 18 reads the last 1,000 games of any Chess.com or Lichess account and scores six skills: openings, tactics, endgames, converting wins, time use and defence."),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:f},"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 y=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:y?v.activeBg:"rgba(255,255,255,0.045)",border:y?`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:y?1:.85,transform:y?"translateY(-1px)":"translateY(0)",boxShadow:y?"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:y?1:.78}}):React.createElement(React.Fragment,null,React.createElement(w,{platform:v.id,size:22,color:y?"#F0EBE0":"var(--pr-text-body)"}),React.createElement("span",{style:{color:y?"#fff":"var(--pr-text-body)"}},v.label)))}))),React.createElement("div",null,React.createElement("label",{style:f,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=>{s&&l(""),t({type:"SET_USERNAME",value:v.target.value})},onKeyDown:v=>{v.key==="Enter"&&g()},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:f},"Format"),React.createElement("div",{className:"pr-pill-group",style:{width:"100%",gap:10}},p.map(v=>{const y=e.format===v.id,m=S[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:y?`${m}26`:"rgba(255,255,255,0.045)",color:y?m:"var(--pr-text-primary)",border:y?`2px solid ${m}`:"1.5px solid rgba(255,255,255,0.10)",borderRadius:12,fontSize:16,fontWeight:600,padding:"12px 14px",height:48,transform:y?"translateY(-1px)":"translateY(0)",boxShadow:y?"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(x,{format:v.id,size:18}),React.createElement("span",null,v.label))}))),React.createElement("button",{onClick:g,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"}))),s&&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"})),s)),d.length>0&&React.createElement("section",{className:"prs-hist","aria-label":"Past reports"},React.createElement("div",{className:"prs-hist__head"},React.createElement("h2",{className:"prs-hist__title"},"Past reports"),React.createElement("span",{className:"prs-hist__count"},d.length," saved")),React.createElement("div",{className:"prs-hist__list"},d.map(v=>{const y=v.platform==="chesscom"?"Chess.com":"Lichess",m=new Date(v.created_at).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"2-digit"}),b=v.format==="all"?"All types":v.format||null;return React.createElement("button",{key:v.id,type:"button",className:"prs-hist__row",onClick:()=>r&&r(v.id)},React.createElement("span",{className:"prs-hist__mark","aria-hidden":"true"},React.createElement(w,{platform:v.platform,size:18,color:v.platform==="chesscom"?"#81B64C":"#F0EBE0"})),React.createElement("span",{className:"prs-hist__text"},React.createElement("span",{className:"prs-hist__name"},v.username),React.createElement("span",{className:"prs-hist__meta"},y,b?React.createElement(React.Fragment,null," \xB7 ",React.createElement("span",{className:"prs-hist__fmt"},b)):null," ","\xB7 ",v.game_count," games \xB7 ",m)),React.createElement("svg",{className:"prs-hist__go",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true"},React.createElement("path",{d:"M9 18l6-6-6-6"})))}))))}function PlayerCard({profile:e,stats:t,analysis:a,platform:r,analysisTime:o}){const n=e||{username:"?",joined:0,country:"",followers:0,league:"",status:""},c=t||{rapid:{},blitz:{},bullet:{},tactics:{}},i=n.joined?new Date(n.joined*1e3).toLocaleDateString("en-US",{month:"short",year:"numeric"}):"?",s=r==="lichess"||n.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"}},n.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"},n.username),n.title&&React.createElement(Badge,{color:"#D4A44B"},n.title),React.createElement(Badge,{color:s?"#6B9FD4":"#5DB67D"},s?"Lichess":"Chess.com"),React.createElement(Badge,{color:a.isHeuristic?"#D4A44B":"#5DB67D"},a.isHeuristic?"Estimated":"Full Analysis"),o&&React.createElement(Badge,{color:"rgba(255,255,255,0.12)"},o>=60?`${Math.floor(o/60)}m ${o%60}s`:`${o}s`)),React.createElement("div",{className:"pr-body pr-text-muted pr-mb-3"},n.country?`${n.country} \xB7 `:"","Member since ",i,n.followers?` \xB7 ${n.followers} followers`:"")))),React.createElement("div",{className:"pr-grid-4 pr-mt-5"},React.createElement(StatBox,{label:"Rapid",value:c.rapid.current||"\u2014",sub:c.rapid.best?`Best: ${c.rapid.best}`:"",color:"#5DB67D",icon:TC_ICONS.rapid}),React.createElement(StatBox,{label:"Blitz",value:c.blitz.current||"\u2014",sub:c.blitz.best?`Best: ${c.blitz.best}`:"",color:"#6B9FD4",icon:TC_ICONS.blitz}),React.createElement(StatBox,{label:"Bullet",value:c.bullet.current||"\u2014",sub:c.bullet.best?`Best: ${c.bullet.best}`:"",color:"#D4A44B",icon:TC_ICONS.bullet}),React.createElement(StatBox,{label:"Tactics",value:c.tactics.highest||"\u2014",sub:"Puzzle rating",color:"#9B8ABF",icon:TC_ICONS.tactics})))}function LockedSectionCard({title:e,onUnlock:t,delay:a=0}){return React.createElement("div",{className:"pr-card pr-locked pr-animate-section",style:{animationDelay:`${a}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",className:"pr-locked__tap",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:r=>{r.currentTarget.style.color="rgba(232,228,224,0.72)"},onMouseLeave:r=>{r.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({part:e="all"}={}){const t=()=>{try{window.LumiOpenAuthModal?.("signup")}catch{}},a=["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,e!=="rows"&&React.createElement("div",{className:"pr-card pr-locked-pitch 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 pr-locked-signin","data-mode":"signup",onClick:t,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")),e!=="pitch"&&a.map((r,o)=>typeof r=="object"&&r.header?React.createElement("div",{key:`h-${r.header}`,style:{scrollMarginTop:64,padding:"24px 0 8px"}},React.createElement("h2",{style:{margin:0,fontSize:18,fontWeight:700,color:"#fff",opacity:.6}},r.header)):React.createElement(LockedSectionCard,{key:r,title:r,onUnlock:t,delay:.1+o*.025})))}const TREND_COLORS={rapid:"#6B9FD4",blitz:"#E0A33C",bullet:"#C77DBB",daily:"#7FB98A",classical:"#8C8FE0",rating:"#6B9FD4"},TC_LABEL={rapid:"Rapid",blitz:"Blitz",bullet:"Bullet",daily:"Daily",classical:"Classical",rating:"Rating"};function ReportDelta(e){const t=reportDeltaOf(e);if(!t)return null;const{metrics:a,prev:r,daysSince:o}=t,n=e.format;if(a.every(s=>s.dir==="held"))return null;const c=n?n.charAt(0).toUpperCase()+n.slice(1):null,i=t.dateLabel;return React.createElement(SectionCard,{title:"What Changed",delay:.05},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",null,"Since your last ",c?`${c} `:"","report"),i&&React.createElement(React.Fragment,null,React.createElement("span",{style:{opacity:.4}},"\xB7"),React.createElement("span",null,i)),o!=null&&React.createElement(React.Fragment,null,React.createElement("span",{style:{opacity:.4}},"\xB7"),React.createElement("span",null,o===0?"today":o===1?"1 day ago":`${o} days ago`))),React.createElement("div",{style:{display:"grid",gap:12,gridTemplateColumns:"repeat(auto-fit, minmax(170px, 1fr))"}},a.map(s=>{const l=s.dir==="up"?"#5DB67D":s.dir==="down"?"#CF6E6E":"rgba(240,235,224,0.8)",d=s.dir==="up"?"\u25B2":s.dir==="down"?"\u25BC":"\u2014",u=s.dir==="held"?"Held":`${s.dir==="up"?"Up":"Down"} ${Math.abs(s.delta)}${s.suffix}`;return React.createElement("div",{className:"pr-stat-box",key:s.key},React.createElement("div",{className:"pr-label"},s.label),React.createElement("div",{style:{display:"flex",alignItems:"baseline",gap:8,flexWrap:"wrap"}},React.createElement("span",{className:"pr-stat-value",style:{color:"var(--pr-text-primary)"}},s.cur,s.suffix),React.createElement("span",{style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:14,fontWeight:700,color:l,background:s.dir==="held"?"rgba(240,235,224,0.10)":l+"18",padding:"1px 7px",borderRadius:4,whiteSpace:"nowrap"}},React.createElement("span",{"aria-hidden":"true",style:{fontSize:10,lineHeight:1}},d),React.createElement("span",null,u))),React.createElement("div",{className:"pr-dim pr-mt-1"},"was ",s.was,s.suffix))})))}function reportDeltaOf({analysis:e,history:t,platform:a,format:r,depth:o,loadedReportId:n}){const c=(t||[]).filter(p=>p&&p.platform===a&&(p.format||null)===(r||null)).slice().sort((p,h)=>new Date(h.created_at)-new Date(p.created_at));let i=null;if(n){const p=c.findIndex(h=>h.id===n);i=p>=0&&c[p+1]||null}else i=c[0]||null;i&&Number.isFinite(i.depth)&&Number.isFinite(o)&&i.depth>0!=o>0&&(i=null);const s=p=>{const h=(p.wins||0)+(p.losses||0)+(p.draws||0);return Number.isFinite(p.wins)&&h>0?Math.round(p.wins/h*100):null},l=p=>Number.isFinite(p)?p:null,d=(i?[{key:"lumi_score",label:"Lumi Score",suffix:"",cur:l(e.lumiScore)!=null?Math.round(e.lumiScore):null,was:l(i.lumi_score)!=null?Math.round(i.lumi_score):null},{key:"avg_accuracy",label:"Avg Accuracy",suffix:"%",cur:l(e.avgAccuracy),was:l(i.avg_accuracy)},{key:"win_rate",label:"Win Rate",suffix:"%",cur:l(e.winRate)!=null?Math.round(e.winRate):null,was:s(i)}]:[]).filter(p=>p.cur!=null&&p.was!=null).map(p=>{const h=Math.round((p.cur-p.was)*10)/10;return{...p,delta:h,dir:h>0?"up":h<0?"down":"held"}}),u=i?.created_at?Math.max(0,Math.round((Date.now()-new Date(i.created_at).getTime())/864e5)):null;if(!d.length)return null;const g=i.created_at?new Date(i.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric"}):null;return{metrics:d,prev:i,daysSince:u,dateLabel:g}}function RatingMomentum({stats:e,analysis:t,username:a,platform:r,format:o,gameCount:n}){const c=e||{rapid:{current:0},blitz:{current:0}},i=t.rapidBlitzGap,s=Array.isArray(t.ratingTrendAll)&&t.ratingTrendAll.length>0,l=Array.isArray(t.ratingTrend)&&t.ratingTrend.length>0;if(!s&&!l)return null;const d=r==="lichess"?"Lichess":"Chess.com",u=o?o.charAt(0).toUpperCase()+o.slice(1):null;return React.createElement(SectionCard,{title:"Rating & Momentum",badge:t.isHeuristic?"estimated":null,delay:.1},a&&React.createElement("div",{className:"pr-meta-row"},React.createElement("span",{className:"pr-meta-row__name"},a),React.createElement("span",{className:"pr-meta-row__rest"},React.createElement("span",null,d),u&&React.createElement(React.Fragment,null,React.createElement("span",{className:"pr-meta-row__dot"},"\xB7"),React.createElement("span",null,u)),Number.isFinite(n)&&n>0&&React.createElement(React.Fragment,null,React.createElement("span",{className:"pr-meta-row__dot"},"\xB7"),React.createElement("span",null,n," games")))),React.createElement("div",{className:"pr-grid-2--lg pr-rm-grid"},React.createElement("div",null,(()=>{const g=(t.ratingTrendClasses||[]).filter(f=>(t.ratingTrendAll||[]).some(v=>v[f]!=null)),p=g.length>0&&Array.isArray(t.ratingTrendAll),h=p?t.ratingTrendAll:t.ratingTrend,w=f=>{const v=h.map(y=>p?y[f]:y.rating).filter(y=>y!=null);return v.length>=2?v[v.length-1]-v[0]:null},S=f=>t.ratingTrendCounts?.[f]??h.filter(v=>v[f]!=null).length,x=p?g.map(f=>({key:f,label:TC_LABEL[f]||f,color:TREND_COLORS[f]||"#6B9FD4",delta:w(f),n:S(f)})):[{key:"rating",label:TC_LABEL[t.primaryTimeClass]||"Rating",color:"#6B9FD4",delta:w("rating"),n:h.length}];return React.createElement(React.Fragment,null,React.createElement("div",{className:"pr-title--white pr-mb-3",style:{display:"flex",alignItems:"center",gap:10,flexWrap:"wrap"}},React.createElement("span",{className:"pr-trend-title"},"Rating Trend (Last ",h.length," Games)"),React.createElement("span",{className:"pr-trend-title--short"},"Rating Trend"),x.map(f=>{const v=f.delta==null?"rgba(255,255,255,0.5)":f.delta>0?"#5DB67D":f.delta<0?"#CF6E6E":"rgba(255,255,255,0.5)";return React.createElement("span",{key:f.key,style:{display:"inline-flex",alignItems:"center",gap:6,fontSize:14,fontWeight:600,color:"var(--pr-text-body)"}},React.createElement("span",{style:{width:10,height:10,borderRadius:3,background:f.color,display:"inline-block"}}),f.label,f.n>0&&React.createElement("span",{className:f.n===h.length?"pr-trend-n pr-trend-n--full":"pr-trend-n",style:{fontWeight:500,color:"var(--pr-text-muted)"}},"\xB7 ",f.n," ",f.n===1?"game":"games"),f.delta!=null&&React.createElement("span",{style:{fontSize:13,fontWeight:700,color:v,background:`${v}18`,padding:"1px 6px",borderRadius:4}},f.delta>=0?"+":"",f.delta))})),React.createElement("div",{className:"pr-chart-h48"},React.createElement(ResponsiveContainer,{width:"100%",height:"100%"},React.createElement(AreaChart,{data:h,margin:{top:5,right:10,bottom:0,left:0}},React.createElement("defs",null,x.map(f=>React.createElement("linearGradient",{key:f.key,id:`ratingGrad-${f.key}`,x1:"0",y1:"0",x2:"0",y2:"1"},React.createElement("stop",{offset:"0%",stopColor:f.color,stopOpacity:.28}),React.createElement("stop",{offset:"100%",stopColor:f.color,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,{cursor:React.createElement(CursorFloorCapture,null),content:({active:f,payload:v,label:y})=>{if(!f||!v?.length)return null;const m=v.filter(b=>b.value!=null);return m.length?React.createElement("div",{style:{background:"rgba(255,255,255,0.95)",border:"1px solid rgba(0,0,0,0.12)",borderRadius:8,padding:"6px 12px",fontSize:14,fontWeight:700,color:"#1a1a1a",whiteSpace:"nowrap",backdropFilter:"blur(6px)",boxShadow:"0 6px 18px rgba(0,0,0,0.25)"}},m.map((b,k)=>React.createElement("span",{key:b.dataKey,style:{marginLeft:k?10:0,color:b.color||"#3a72b0"}},TC_LABEL[b.dataKey]||"Rating"," game ",y,": ",b.value))):null}}),x.map(f=>React.createElement(Area,{key:f.key,activeDot:React.createElement(DropDot,null),type:"monotone",dataKey:f.key,stroke:f.color,fill:`url(#ratingGrad-${f.key})`,strokeWidth:2,dot:!1,connectNulls:!0}))))))})()),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 MiniBoard({fen:e,playedUci:t,bestUci:a,flip:r}){const o="#ecdab9",n="#c5a076",c=React.useMemo(()=>{try{return new window.Chess(e).board()}catch{return null}},[e]);if(!c)return null;const i=d=>{const g="/assets/pieces/maestro/"+(d.color+d.type.toUpperCase())+".svg";return window.LumiAssets?.staticAssetUrl?window.LumiAssets.staticAssetUrl(g):g},s=d=>{const u=d.charCodeAt(0)-97,g=parseInt(d[1],10)-1,p=r?7-u:u,h=r?g:7-g;return{cx:p+.5,cy:h+.5}},l=(d,u,g)=>{if(!d||d.length<4)return null;const p=s(d.slice(0,2)),h=s(d.slice(2,4)),w=h.cx-p.cx,S=h.cy-p.cy,x=Math.hypot(w,S)||1,f=h.cx-w/x*.32,v=h.cy-S/x*.32;return React.createElement("line",{key:g,x1:p.cx,y1:p.cy,x2:f,y2:v,stroke:u,strokeWidth:.16,strokeLinecap:"round",markerEnd:`url(#mb-head-${g})`,opacity:.92})};return React.createElement("div",{style:{position:"relative",width:"100%",aspectRatio:"1 / 1",borderRadius:6,overflow:"hidden",boxShadow:"0 1px 4px rgba(0,0,0,0.3)"}},React.createElement("div",{style:{position:"absolute",inset:0,display:"grid",gridTemplateColumns:"repeat(8,1fr)",gridTemplateRows:"repeat(8,1fr)"}},Array.from({length:64}).map((d,u)=>{const g=Math.floor(u/8),p=u%8,h=r?7-g:g,w=r?7-p:p,S=c[h][w],x=(g+p)%2===0;return React.createElement("div",{key:u,style:{background:x?o:n,position:"relative"}},S&&React.createElement("img",{src:i(S),alt:"",draggable:!1,style:{position:"absolute",inset:0,width:"100%",height:"100%"}}))})),React.createElement("svg",{viewBox:"0 0 8 8",style:{position:"absolute",inset:0,width:"100%",height:"100%",pointerEvents:"none"}},React.createElement("defs",null,React.createElement("marker",{id:"mb-head-played",viewBox:"0 0 6 6",refX:"3",refY:"3",markerWidth:"4",markerHeight:"4",orient:"auto"},React.createElement("path",{d:"M0,0 L6,3 L0,6 z",fill:"#CF6E6E"})),React.createElement("marker",{id:"mb-head-best",viewBox:"0 0 6 6",refX:"3",refY:"3",markerWidth:"4",markerHeight:"4",orient:"auto"},React.createElement("path",{d:"M0,0 L6,3 L0,6 z",fill:"#5DB67D"}))),l(t,"#CF6E6E","played"),l(a,"#5DB67D","best")))}function TacticsConversionInline({analysis:e}){const t=React.useMemo(()=>{if(e.__slim)return e.metrics.tactics||null;try{return window.LumiProfile?.TacticsFoundMissed?.computeFoundMissed(e.analyzedGames||[])}catch(g){return console.warn("[tactics] found-vs-missed compute failed",g),null}},[e]);if(!t||!t.gamesUsed)return null;const{motifs:a}=t,r=["fork","pin","mateIn1"];if(!r.some(g=>a[g]&&a[g].total>0))return null;const n=e.analyzedGames||[],c=r.reduce((g,p)=>g+(a[p]?.found||0),0),i=r.reduce((g,p)=>g+(a[p]?.total||0),0);if(!i)return null;const s=Math.round(c/i*100),l=s>=65?"#5DB67D":s>=50?"#D4A44B":"#CF6E6E",d=[{name:"Found",value:c,fill:"#5DB67D"},{name:"Missed",value:i-c,fill:"#CF6E6E"}],u=g=>{const p=n[g.gameIdx];if(!p||!p.pgn)return;const h=p.headers||{},w={source:"pgn",white:{username:h.White||"White"},black:{username:h.Black||"Black"},result:h.Result||"*",timeControl:{display:h.TimeControl||""},date:h.Date||"",analyzedAs:p.playerColor==="b"?"black":"white",reviewMiss:{moveIndex:g.ply+1,playedUci:g.playedUci,bestUci:g.bestUci}};sessionStorage.setItem("lumichess_game_pgn",p.pgn),sessionStorage.setItem("lumichess_game_meta",JSON.stringify(w)),window.open("/game/report","_blank")};return React.createElement("div",{style:{gridColumn:"1 / -1"}},React.createElement("div",{className:"pr-label pr-mb-3"},"Tactical Conversion"),React.createElement("div",{className:"pr-grid-2--lg"},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:l,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)"}},c,"/",i," chances")),React.createElement("div",{style:{flex:1}},React.createElement(ResponsiveContainer,{width:"100%",height:120},React.createElement(BarChart,{data:d,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,{cursor:!1,content:ChartTip}),React.createElement(Bar,{activeBar:{fillOpacity:1,style:{filter:"brightness(1.5) saturate(1.35)"}},dataKey:"value",radius:[0,3,3,0]},d.map((g,p)=>React.createElement(Cell,{key:p,fill:g.fill}))))))),React.createElement("div",null,React.createElement(DimCoach,{title:"What this measures",body:"How often you played the winning move when a clear one-move tactic was on the board, such as a fork, a pin, or a mate in one."}),React.createElement(DimCoach,{title:"Your performance",body:`You played the winning tactic in ${c} of ${i} chances across ${t.gamesUsed} games (forks, pins, mate-in-1). ${s>=65?"Strong tactical vision. You spot and take what the position offers.":s>=50?"Room to improve. Slow down when material is loose or the enemy king is exposed. That is where these tactics live.":"This is a critical weakness. You are reaching positions with winning tactics on the board and playing past them. Daily puzzle work on forks and pins will convert directly into rating."}`}))),(()=>{const g=(t.misses||[]).filter(w=>w.motif==="mateIn1");if(!g.length)return null;const p=!0,h=g.slice(0,12);return React.createElement("div",{style:{marginTop:8}},React.createElement("div",{className:"pr-label pr-mb-3"},"Mate in 1 You Missed",g.length>h.length&&React.createElement("span",{style:{textTransform:"none",letterSpacing:0,fontWeight:500,color:"var(--pr-text-secondary)"}}," \xB7 showing ",h.length," of ",g.length)),React.createElement("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(172px, 1fr))",gap:16}},h.map((w,S)=>{const x=n[w.gameIdx]||{},f=x.playerColor==="b",v=x.headers?x.playerColor==="w"?x.headers.Black:x.headers.White:null,y=Math.floor(w.ply/2)+1,m=React.createElement(React.Fragment,null,React.createElement(MiniBoard,{fen:w.fen,playedUci:w.playedUci,bestUci:w.bestUci,flip:f}),React.createElement("div",{style:{fontSize:12,color:"var(--pr-text-secondary)",marginTop:5,textAlign:"center",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}},"Move ",y,v?` vs ${v}`:""));return p?React.createElement("button",{key:S,onClick:()=>u(w),style:{display:"block",width:"100%",padding:0,background:"none",border:"none",cursor:"pointer",font:"inherit"}},m):React.createElement("div",{key:S},m)})),React.createElement("div",{style:{fontSize:12.5,color:"var(--pr-text-secondary)",marginTop:10,display:"flex",gap:16,flexWrap:"wrap"}},React.createElement("span",{style:{display:"inline-flex",alignItems:"center",gap:6}},React.createElement("span",{style:{width:14,borderTop:"3px solid #5DB67D"}})," The mate you missed"),React.createElement("span",{style:{display:"inline-flex",alignItems:"center",gap:6}},React.createElement("span",{style:{width:14,borderTop:"3px solid #CF6E6E"}})," What you played")))})())}function PerformanceRadar({analysis:e,state:t}){const a=e.skillProfile&&e.skillProfile.dimensions,r=["opening","tactical","endgame","capitalization","time_mgmt","resourcefulness"],o={opening:"Opening",tactical:"Tactics",endgame:"Endgame",resourcefulness:"Resourcefulness",capitalization:"Conversion",time_mgmt:"Time Management"},n=a?r.filter(f=>e.skillProfile.dimensions[f]).map(f=>{const v=e.skillProfile.dimensions[f];return{dim:o[f]||f,value:v.score||50,fullMark:100,confidence:v.confidence}}):e.radar;if(!Array.isArray(n)||n.length===0)return null;const c=a?e.skillProfile.confidence:null,i=a?"Skill Profile":"Performance Radar",s=a?"#D4A44B":"#5DB67D",l=n,d=f=>f>=65?{label:"Strong",color:"#5DB67D"}:f>=45?{label:"Develop",color:"#D4A44B"}:{label:"Weak spot",color:"#CF6E6E"},u={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"},g=e.profile?.username||t?.username||"",p=t?.format&&t.format!=="all"?t.format:null,h=(e.__slim?e.analyzedCount:e.analyzedGames?.length)||0,w=n.map(f=>({...f,value:0})),[S,x]=useState(w);return useEffect(()=>{const f=setTimeout(()=>x(n),80);return()=>clearTimeout(f)},[]),React.createElement(SectionCard,{title:i,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:S,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:f,x:v,y,textAnchor:m,cy:b,...k})=>{const A=n.find($=>$.dim===f.value),E=A?A.value:"",M=typeof window<"u"&&window.innerWidth<640,T=typeof b=="number"&&y>b+4,D=T?y+14:y-12,_=T?y+30:y+6,C={Resourcefulness:"Resource","Time Management":"Time Mgmt","Tactical Vision":"Tactics","Blunder Resist.":"Blunders",Capitalization:"Convert","Opening Prep":"Opening"},B=M&&C[f.value]?C[f.value]:f.value,L=M?11:14;return React.createElement("g",null,React.createElement("text",{x:v,y:D,textAnchor:m,fill:"#F0EDE8",fontSize:L,fontWeight:600},B),React.createElement("text",{x:v,y:_,textAnchor:m,fill:s,fontSize:L,fontWeight:700},E))}}),React.createElement(Radar,{name:"You",dataKey:"value",stroke:s,fill:s,fillOpacity:.15,strokeWidth:2,dot:{r:3,fill:s},isAnimationActive:!0,animationDuration:1500,animationEasing:"ease-out"})))),React.createElement("div",null,React.createElement("div",{className:"pr-interp-list"},l.map(f=>{const v=d(f.value),y=u[f.dim];return React.createElement("div",{key:f.dim,className:"pr-interp-row"},React.createElement("span",{className:"pr-interp-dot",style:{background:v.color}}),React.createElement("span",{className:"pr-interp-name"},f.dim),React.createElement("span",{className:"pr-interp-score",style:{color:v.color}},f.value),React.createElement("span",{className:"pr-interp-badge",style:{background:`${v.color}18`,color:v.color}},v.label),y&&React.createElement("span",{role:"button",tabIndex:0,"aria-label":`Review ${f.dim}`,title:`Review ${f.dim}`,onClick:()=>document.getElementById(y)?.scrollIntoView({behavior:"smooth",block:"start"}),onKeyDown:m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),document.getElementById(y)?.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)return null;let a,r,o;if(e.__slim){const i=e.metrics.moveQuality;if(!i)return null;a=i.classificationCounts,r=i.totalMoves,o=i.accData}else{if(!e.analyzedGames||e.analyzedGames.length===0)return null;const i=e.analyzedGames.flatMap(l=>l.moveAnalysis.filter(d=>d.isPlayerMove&&d.classification!==null));if(i.length===0)return null;r=i.length,a={},i.forEach(l=>{a[l.classification]=(a[l.classification]||0)+1});const s=(t||"").toLowerCase();o=e.analyzedGames.map((l,d)=>({game:d+1,accuracy:l.playerAccuracy,opponent:(l.headers?.White||"").toLowerCase()===s?l.headers?.Black||`Game ${d+1}`:l.headers?.White||`Game ${d+1}`}))}const c=["brilliant","best","excellent","good","book","inaccuracy","mistake","blunder"].map(i=>({name:CLASSIFICATION_LABELS[i],count:a[i]||0,color:CLASSIFICATION_COLORS[i]})).filter(i=>i.count>0);return React.createElement(SectionCard,{title:"Move Quality: 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 (",r," moves)"),React.createElement("div",{className:"pr-chart-h56"},React.createElement(ResponsiveContainer,{width:"100%",height:"100%"},React.createElement(BarChart,{data:c,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,{cursor:!1,content:ChartTip}),React.createElement(Bar,{activeBar:{fillOpacity:1,style:{filter:"brightness(1.5) saturate(1.35)"}},dataKey:"count",radius:[0,4,4,0]},c.map((i,s)=>React.createElement(Cell,{key:s,fill:i.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:o},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,{cursor:!1,content:i=>React.createElement(ChartTip,{...i,formatter:(s,l,d)=>[`${s}%`,d.payload.opponent]})}),React.createElement(Bar,{activeBar:{fillOpacity:1,style:{filter:"brightness(1.5) saturate(1.35)"}},dataKey:"accuracy",radius:[3,3,0,0]},o.map((i,s)=>React.createElement(Cell,{key:s,fill:i.accuracy>=85?"#5DB67D":i.accuracy>=70?"#6B9FD4":i.accuracy>=55?"#D4A44B":"#CF6E6E"})))))))),React.createElement("div",{className:"pr-grid-3 pr-mt-5"},(()=>{let i,s,l;if(e.__slim)({avgOpening:i,avgMiddle:s,avgEnd:l}=e.metrics.moveQuality);else{const d=e.analyzedGames;i=Math.round(d.reduce((u,g)=>u+g.openingCpl,0)/d.length*10)/10,s=Math.round(d.reduce((u,g)=>u+g.middlegameCpl,0)/d.length*10)/10,l=Math.round(d.reduce((u,g)=>u+g.endgameCpl,0)/d.length*10)/10}return[{label:"Opening CPL",value:i,color:i<20?"#5DB67D":i<40?"#D4A44B":"#CF6E6E"},{label:"Middlegame CPL",value:s,color:s<30?"#5DB67D":s<50?"#D4A44B":"#CF6E6E"},{label:"Endgame CPL",value:l,color:l<25?"#5DB67D":l<45?"#D4A44B":"#CF6E6E"}].map(d=>React.createElement(StatBox,{key:d.label,label:d.label,value:d.value,sub:"avg centipawn loss",color:d.color}))})()))}function TimeManagement({analysis:e,games:t}){const a=Math.round(e.timeoutLosses/Math.max(1,e.losses)*100),r=Math.round(e.timeTrouble/e.total*100),o=[{range:"0-5s",count:t.filter(n=>n.finalClock!==null&&n.finalClock<5).length,color:"#CF6E6E"},{range:"5-15s",count:t.filter(n=>n.finalClock!==null&&n.finalClock>=5&&n.finalClock<15).length,color:"#D4A44B"},{range:"15-30s",count:t.filter(n=>n.finalClock!==null&&n.finalClock>=15&&n.finalClock<30).length,color:"#D4A44B"},{range:"30-60s",count:t.filter(n=>n.finalClock!==null&&n.finalClock>=30&&n.finalClock<60).length,color:"#6B9FD4"},{range:"1-2min",count:t.filter(n=>n.finalClock!==null&&n.finalClock>=60&&n.finalClock<120).length,color:"#5DB67D"},{range:"2min+",count:t.filter(n=>n.finalClock!==null&&n.finalClock>=120).length,color:"#5DB67D"}];return React.createElement(SectionCard,{title:"Time Management",delay:.2},a>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"}},a,"% of your losses are from running out of time. You end ",r,"% 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:o},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,{cursor:!1,content:ChartTip}),React.createElement(Bar,{activeBar:{fillOpacity:1,style:{filter:"brightness(1.5) saturate(1.35)"}},dataKey:"count",radius:[4,4,0,0]},o.map((n,c)=>React.createElement(Cell,{key:c,fill:n.color}))))))),React.createElement("div",{className:"pr-grid-2"},React.createElement(StatBox,{label:"Timeout Losses",value:e.timeoutLosses,sub:`${a}% of losses`,color:"#CF6E6E"}),React.createElement(StatBox,{label:"Time Trouble",value:`${r}%`,sub:"games ending <15s",color:"#D4A44B"}),React.createElement(StatBox,{label:"Severe (<5s)",value:e.severeTimeTrouble,sub:"games",color:"#CF6E6E"}),React.createElement(StatBox,{label:"Timeout Wins",value:e.timeoutWins,sub:"opponent flagged",color:"#5DB67D"}))))}function OpeningRepertoire({analysis:e}){const t=e.openings.map(n=>({name:n.name,wins:n.wins,losses:n.losses,draws:n.draws})),a=t.map(n=>n.wins+n.losses+n.draws),r=a.length>0?Math.max(...a,1):1,o=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:o}},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(r,2)]}),React.createElement(YAxis,{type:"category",dataKey:"name",width:220,tick:{fontSize:13,fill:"var(--pr-text-body)"}}),React.createElement(Tooltip,{cursor:!1,content:ChartTip}),React.createElement(Bar,{activeBar:{fillOpacity:1,style:{filter:"brightness(1.5) saturate(1.35)"}},dataKey:"wins",stackId:"a",fill:"#5DB67D",barSize:18}),React.createElement(Bar,{activeBar:{fillOpacity:1,style:{filter:"brightness(1.5) saturate(1.35)"}},dataKey:"draws",stackId:"a",fill:"#8A857F",barSize:18}),React.createElement(Bar,{activeBar:{fillOpacity:1,style:{filter:"brightness(1.5) saturate(1.35)"}},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"},a=Object.entries(e.winMethods).map(([w,S])=>({name:t[w]||w,value:S,key:w})),r=Object.entries(e.lossMethods).map(([w,S])=>({name:t[w]||w,value:S,key:w})),o=["#5DB67D","#7DC89A","#9ED6B2","#BFE5CA"],n=["#CF6E6E","#D98B8B","#E3A8A8","#EDC5C5"],c=(w,S)=>{const x=w.reduce((v,y)=>v+y.value,0);if(x===0)return 0;const f=w.find(v=>v.key===S);return f?Math.round(f.value/x*100):0},i=c(a,"checkmate"),s=c(a,"resignation"),l=c(a,"timeout"),d=c(r,"checkmate"),u=c(r,"resignation"),g=c(r,"timeout"),p=[];d>=35?p.push(`${d}% of your losses end in checkmate, which is high for your level. Most players resign once down material; playing on to mate often means you're not recognising lost positions in time.`):d>=20?p.push(`${d}% of losses end in checkmate, within normal range.`):p.push(`Only ${d}% of losses end in checkmate. You resign promptly once lost.`),g>=25?p.push(`${g}% of losses are on time. That is a clock problem, not a chess problem. See Time Management above.`):g>0&&p.push(`${g}% of losses are on time, not the main loss source.`);const h=[];return s>=55?h.push(`${s}% of wins come from your opponent resigning. You build winning positions and hold them.`):i>=35&&h.push(`${i}% of wins are by checkmate. Your style is sharp and tactical, finishing games on the board.`),l>=20&&h.push(`${l}% of wins are timeouts. 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:a,cx:"50%",cy:"50%",innerRadius:45,outerRadius:70,dataKey:"value",label:w=>{const S=typeof window<"u"&&window.innerWidth<640;return React.createElement("text",{x:w.x,y:w.y,fill:"var(--pr-text-primary)",textAnchor:w.textAnchor,dominantBaseline:"central",fontSize:S?11:15,fontWeight:500},`${w.name} ${(w.percent*100).toFixed(0)}%`)},labelLine:!1},a.map((w,S)=>React.createElement(Cell,{key:S,fill:o[S%o.length]}))),React.createElement(Tooltip,{cursor:!1,content:ChartTip}))))),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:r,cx:"50%",cy:"50%",innerRadius:45,outerRadius:70,dataKey:"value",label:w=>{const S=typeof window<"u"&&window.innerWidth<640;return React.createElement("text",{x:w.x,y:w.y,fill:"var(--pr-text-primary)",textAnchor:w.textAnchor,dominantBaseline:"central",fontSize:S?11:15,fontWeight:500},`${w.name} ${(w.percent*100).toFixed(0)}%`)},labelLine:!1},r.map((w,S)=>React.createElement(Cell,{key:S,fill:n[S%n.length]}))),React.createElement(Tooltip,{cursor:!1,content:ChartTip})))))),React.createElement("div",{style:{marginTop:16}},React.createElement(DimCoach,{title:"What this measures",body:"How your wins and losses end, 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)."}),(h.length>0||p.length>0)&&React.createElement(DimCoach,{title:"Your performance",body:[...h,...p].join(" ")})))}function fullMoves(e,t){return Number.isFinite(e)?t==="lichess"?e:Math.ceil(e/2):e}function PsychProfile({analysis:e,platform:t}){const a=(e.games||[]).slice().sort((f,v)=>{const y=f?.date||f?.headers?.Date||"",m=v?.date||v?.headers?.Date||"";return String(y).localeCompare(String(m))});let r=0,o=0,n=0,c=0,i=0,s=0,l=0,d=0;for(let f=0;f<a.length;f++){const v=a[f];if(v?.result==="loss"?(n++,c=0,n>r&&(r=n)):v?.result==="win"?(c++,n=0,c>o&&(o=c)):(n=0,c=0),f+1<a.length){const y=a[f+1]?.accuracy;typeof y=="number"&&(v?.result==="loss"?(i+=y,s++):v?.result==="win"&&(l+=y,d++))}}const u=s>=3?Math.round(i/s*10)/10:null,g=d>=3?Math.round(l/d*10)/10:null,p=u!=null&&g!=null?Math.round((g-u)*10)/10:null,h=new Set(a.map(f=>f?.date||f?.headers?.Date).filter(Boolean)).size,w=(()=>{const f=e.longestSession||0;let v=f>=13?"High":f>=10?"Moderate":"Low";(r>=6||e.afterLossWinRate<35)&&(v=v==="Low"?"Moderate":"High");const y={High:{cls:"pr-alert--danger",color:"#CF6E6E"},Moderate:{cls:"pr-alert--warning",color:"#D4A44B"},Low:{cls:"pr-alert--success",color:"#5DB67D"}}[v];return{level:v,...y}})(),S=[];e.afterLossWinRate>=55?S.push(`Strong tilt resilience. You win ${e.afterLossWinRate}% of games right after a loss (>50% is rare; most players drop 5-10pp).`):e.afterLossWinRate>=40?S.push(`Average tilt response. You win ${e.afterLossWinRate}% of post-loss games, similar to your overall rate.`):S.push(`Only ${e.afterLossWinRate}% of post-loss games are wins, so tilt is real. Step away for a few minutes after losing.`),r>=5?S.push(`Worst stretch: ${r} losses in a row. That is a serious tilt spiral. The fix is usually a break, not "one more game".`):r>=3?S.push(`Worst stretch: ${r} losses in a row, survivable but a signal to pause.`):r>0&&S.push(`Worst stretch: only ${r} loss${r===1?"":"es"} back-to-back. You self-regulate well.`),o>=5?S.push(`Best stretch: ${o} wins in a row. When you are on, you ride it.`):o>=3&&S.push(`Best stretch: ${o} wins in a row.`),p!=null&&Math.abs(p)>=3?S.push(`Accuracy after a loss (${u}%) vs after a win (${g}%) differs by ${Math.abs(p)} points. ${p>0?"Losses clearly drag your next game down. Reset before the rematch.":"Losses sharpen your focus and wins make you sloppy. Stay disciplined when ahead."}`):p!=null&&S.push(`Accuracy is steady regardless of the previous result (${u}% after losses, ${g}% after wins)${w.level==="Low"?", which is emotionally even-keeled":""}.`),e.longestSession>=10?S.push(`Longest session was ${e.longestSession} games in one day, which is fatigue territory. Performance usually degrades after 6 to 8 rated games.`):e.longestSession>=7&&S.push(`Longest session ${e.longestSession} games, at the edge of where fatigue bites.`);const x=fullMoves(e.avgMoves,t);return x>=30?S.push(`Average game runs ${x} moves. You grind long endgames rather than ending in the middlegame.`):x<15&&S.push(`Average game runs ${x} moves, a sharp and 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"}),React.createElement(StatBox,{label:"Worst Streak",value:r,sub:r===1?"loss in a row":"losses in a row",color:r>=4?"#CF6E6E":"#D4A44B"}),React.createElement(StatBox,{label:"Best Streak",value:o,sub:o===1?"win in a row":"wins in a row",color:"#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"})),p!=null&&Math.abs(p)>=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)",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,g,"%")," after a win and ",React.createElement("strong",null,u,"%")," after a loss. That is a ",Math.abs(p),"-point swing the previous result alone explains.")),e.marathonDays>0&&React.createElement("div",{className:`pr-alert ${w.cls} pr-mb-3`},React.createElement("div",{className:"pr-text-sm pr-font-semibold pr-mb-1",style:{color:w.color}},"Tilt Risk: ",w.level),React.createElement("div",{className:"pr-text-xs",style:{color:w.color}},"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: tilt recovery, win/loss streaks, accuracy after each kind of result, session length, game tempo. Across the analyzed games you played on ${h} different day${h===1?"":"s"}.`}),React.createElement(DimCoach,{title:"Your performance",body:S.join(" ")})))}function ImprovementPlan({analysis:e,stats:t}){const a=t||{rapid:{current:0},blitz:{current:0}},r=e.recommendations||[],o=e.radar||[],n=e.insights||null,c={};if(n?.dimensionInsights)for(const d of n.dimensionInsights)c[d.key]=d;if(r.length>0){const d=r.filter(h=>h.score>=60).slice(0,3),u=r.filter(h=>h.score<50).slice(0,3),g=r.find(h=>h.isPrimary),p=a.blitz?.current||a.rapid?.current||1200;return React.createElement(SectionCard,{title:"Personalized Improvement Plan",badge:"data-driven",delay:.45},n&&(n.headline||n.mainInsight)&&React.createElement("div",{className:"pr-alert--gradient pr-mb-6"},n.headline&&React.createElement("div",{className:"pr-text-lg pr-font-bold pr-text-white pr-mb-2"},n.headline),n.mainInsight&&React.createElement("div",{className:"pr-text-base",style:{color:"var(--pr-text-primary)",fontWeight:500,lineHeight:1.55}},n.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"),d.length===0&&React.createElement("div",{className:"pr-text-sm",style:{color:"var(--pr-text-secondary)"}},"Analyze more games to identify strengths."),d.map(h=>React.createElement("div",{key:h.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"}},h.label," \xB7 Score: ",h.score))))),React.createElement("div",null,React.createElement("div",{className:"pr-text-base pr-font-bold pr-mb-3",style:{color:"#CF6E6E"}},"Priority Improvements"),u.length===0&&React.createElement("div",{className:"pr-text-sm",style:{color:"var(--pr-text-secondary)"}},"No significant weaknesses detected."),u.map(h=>{const w=c[h.dimension];return React.createElement("div",{key:h.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"}},h.isPrimary?"! ":"",h.label," \xB7 Score: ",h.score)),React.createElement("div",{className:"pr-text-sm pr-mb-2",style:{color:"#F0D9D9",lineHeight:1.55,fontWeight:500}},w?.text||h.description))}))),g&&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: ",g.label),React.createElement("div",{className:"pr-text-base",style:{color:"var(--pr-text-primary)",fontWeight:500,lineHeight:1.55}},g.description)),n?.patterns&&n.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"),n.patterns.map((h,w)=>React.createElement("div",{key:w,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}},h)))))}const i=[...o].sort((d,u)=>u.value-d.value).slice(0,3),s=[...o].sort((d,u)=>d.value-u.value).slice(0,3),l={"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"),i.map(d=>React.createElement("div",{key:d.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"}},d.dim," \xB7 Score: ",d.value))))),React.createElement("div",null,React.createElement("div",{className:"pr-text-sm pr-font-semibold pr-mb-3",style:{color:"#CF6E6E"}},"Priority Improvements"),s.map(d=>React.createElement("div",{key:d.dim,className:"pr-weakness-item"},React.createElement("div",{className:"pr-text-sm pr-font-semibold pr-mb-1",style:{color:"#E3A8A8"}},"! ",d.dim," \xB7 Score: ",d.value),React.createElement("div",{className:"pr-text-xs pr-ml-2",style:{color:"#E3A8A8"}},l[d.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,a)=>React.createElement("div",{key:a,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"},a={critical:"rgba(207,110,110,0.08)",warning:"rgba(212,164,75,0.08)",info:"rgba(107,159,212,0.08)"},r={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((o,n)=>React.createElement("div",{key:n,className:"pr-pattern-card",style:{background:a[o.severity]||a.info,borderColor:r[o.severity]||r.info}},React.createElement("div",{className:"pr-row pr-mb-1"},React.createElement("span",{className:"pr-badge--severity",style:{background:(t[o.severity]||"#6B9FD4")+"25",color:t[o.severity]||"#6B9FD4"}},o.severity),React.createElement("span",{className:"pr-text-sm pr-font-semibold pr-text-secondary"},o.title)),React.createElement("div",{className:"pr-text-xs pr-text-muted"},o.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 a=e[e.length-1],r=e[e.length-2],o=a.dimensions?Object.keys(a.dimensions):[],n=e.slice(-5).map((i,s)=>({snapshot:s+1,accuracy:i.accuracy||0,score:i.lumiScore||0,date:i.date?new Date(i.date).toLocaleDateString("en-US",{month:"short",day:"numeric"}):`#${s+1}`})),c={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"},o.map(i=>{const s=a.dimensions?.[i]||0,l=r.dimensions?.[i]||0,d=s-l;return d===0?null:React.createElement("div",{key:i,className:"pr-delta-row"},React.createElement("span",{className:"pr-delta-row__label"},c[i]||i),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,s))}%`,background:d>0?"#5DB67D":"#CF6E6E"}}))),React.createElement("span",{className:"pr-delta-row__value",style:{color:d>0?"#5DB67D":"#CF6E6E"}},d>=0?"+":"",Math.round(d)))}).filter(Boolean),o.every(i=>(a.dimensions?.[i]||0)-(r.dimensions?.[i]||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:n},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,{cursor:React.createElement(CursorFloorCapture,null),content:ChartTip}),React.createElement(Line,{activeDot:React.createElement(DropDot,null),type:"monotone",dataKey:"accuracy",stroke:"#5DB67D",strokeWidth:2,dot:{r:4,fill:"#5DB67D"}})))))))}function AccuracyOverview({analysis:e,games:t}){if(e.isHeuristic||!e.__slim&&!e.analyzedGames?.length)return null;const a=e.__slim?e.metrics.accByResult:computeAccuracyByResult(e.analyzedGames),r=e.__slim?e.metrics.accByMove:computeAccuracyByMoveNumber(e.analyzedGames),o=e.__slim?!1:e.analyzedGames.every(i=>!i||i.isQuickMode),n={win:"#5DB67D",draw:"#8A857F",loss:"#CF6E6E"},c={win:"When You Win",draw:"When You Draw",loss:"When You Lose"};return React.createElement(SectionCard,{title:"Accuracy Insights",badge:o?"instant":"engine",delay:.15},React.createElement("div",{className:"pr-grid-3 pr-mb-6"},["win","draw","loss"].map(i=>React.createElement("div",{key:i,className:"pr-acc-result-card"},React.createElement("div",{className:"pr-text-xs pr-text-muted pr-mb-1"},c[i]),React.createElement("div",{className:"pr-text-2xl pr-font-bold",style:{color:n[i]}},a[i]?.avg||"\u2014"),React.createElement("div",{className:"pr-text-xs pr-text-dim pr-mt-1"},a[i]?.count||0," games")))),r.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:r},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,{cursor:React.createElement(CursorFloorCapture,null),content:i=>React.createElement(ChartTip,{...i,formatter:(s,l,d)=>[`${s}%`,`Move ${d.payload.move} (${d.payload.games} games)`]})}),React.createElement(ReferenceLine,{y:e.avgAccuracy,stroke:"rgba(255,191,0,0.3)",strokeDasharray:"4 4"}),React.createElement(Area,{activeDot:React.createElement(DropDot,null),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.__slim&&!e.analyzedGames?.length)return null;const a=e.__slim?e.metrics.gamePhase:computeGamePhaseStats(e.analyzedGames),r={opening:"Opening",middlegame:"Middlegame",endgame:"Endgame"},o={opening:"\u2654",middlegame:"\u2658",endgame:"\u2656"},n={opening:"#D4A44B",middlegame:"#6B9FD4",endgame:"#5DB67D"},c=Object.values(a).reduce((u,g)=>u+(g.accSamples||0),0),i=c>0?Math.round(Object.values(a).reduce((u,g)=>u+g.accuracy*(g.accSamples||0),0)/c*10)/10:e.avgAccuracy,s={opening:"Short games",middlegame:"Medium length games",endgame:"Long games"},l={opening:"games that ended within 10 moves",middlegame:"games that ended between moves 11 and 20",endgame:"games that ended after move 20"},d=Object.entries(a).filter(([,u])=>u.games>0);return React.createElement(SectionCard,{title:"Game Phases",delay:.2},React.createElement("div",{style:{color:"var(--pr-text-primary)",fontSize:16,lineHeight:1.55,fontWeight:500,marginBottom:20}},"How accurately you play as a game goes on. Each game contributes to all three phases, scored from the moves you actually played in that stretch. Bars that clear the amber line are phases where you play better than your own average across phases, ",i,"%."),React.createElement("div",{style:{display:"flex",flexDirection:"column",gap:2}},React.createElement("div",{style:{display:"flex",alignItems:"flex-end",gap:14,paddingBottom:3}},React.createElement("div",{style:{width:128,flexShrink:0}}),React.createElement("div",{style:{position:"relative",flex:1,height:14}},React.createElement("div",{style:{position:"absolute",left:`${i}%`,transform:"translateX(-50%)",bottom:0,whiteSpace:"nowrap",fontSize:10,fontWeight:700,letterSpacing:.3,textTransform:"uppercase",color:"#D4A44B"}},"Average across phases")),React.createElement("div",{style:{width:54,flexShrink:0}}),React.createElement("div",{style:{width:56,flexShrink:0}})),Object.entries(a).map(([u,g])=>{const p=Math.round((g.accuracy-i)*10)/10,h=p>=0,w=h?"#5DB67D":"#CF6E6E";return React.createElement("div",{key:u,style:{display:"flex",alignItems:"center",gap:14,padding:"9px 0"}},React.createElement("div",{style:{width:128,flexShrink:0,display:"flex",alignItems:"center",gap:9,color:n[u]}},React.createElement("span",{style:{fontSize:20,lineHeight:1}},o[u]),React.createElement("span",{style:{fontSize:15,fontWeight:700}},r[u])),React.createElement("div",{style:{position:"relative",flex:1,height:30,background:"rgba(255,255,255,0.05)",borderRadius:6}},React.createElement("div",{style:{position:"absolute",top:0,bottom:0,left:0,width:`${g.accuracy}%`,background:w,opacity:.85,borderRadius:6}}),React.createElement("div",{style:{position:"absolute",left:`${i/2}%`,top:"50%",transform:"translate(-50%, -50%)",fontSize:10,fontWeight:700,letterSpacing:.4,textTransform:"uppercase",color:"rgba(255,255,255,0.85)",whiteSpace:"nowrap",pointerEvents:"none"}},"Average accuracy"),React.createElement("div",{style:{position:"absolute",top:-3,bottom:-3,left:`${i}%`,width:2,background:"#D4A44B"}})),React.createElement("div",{style:{width:54,flexShrink:0,textAlign:"right",fontSize:19,fontWeight:800,color:"#fff",fontVariantNumeric:"tabular-nums"}},g.accuracy,"%"),React.createElement("div",{style:{width:56,flexShrink:0,textAlign:"right",fontSize:15,fontWeight:700,color:w,fontVariantNumeric:"tabular-nums"}},h?"+":"",p))})),React.createElement("div",{className:"pr-text-xs pr-text-dim pr-mt-2"},"Each bar is your accuracy in that phase. The amber line is your average across phases (",i,"%), the weighted mean of the three phases.",i!==e.avgAccuracy?` Phase accuracy is scored differently from your overall accuracy (${e.avgAccuracy}%), so the two numbers differ.`:""," Green bars clear it and red bars fall short. The last column is the gap against that average."),d.length>0&&React.createElement("div",{style:{marginTop:40}},React.createElement("div",{className:"pr-label pr-mb-2"},"Results by Game Length"),React.createElement(DimCoach,{title:"What this measures",body:React.createElement(React.Fragment,null,"Game length often reveals where victories and defeats are truly decided. Short games usually hinge on opening preparation, tactical shots, or early blunders. Medium-length games are won or lost in the intensity of the middlegame battle, while long games test endgame technique, calculation, patience, and the ability to stay accurate under prolonged pressure.",React.createElement("div",{style:{marginTop:12}},"By comparing your win rate across these groups, you can uncover the type of game that plays to your strengths, and identify the kind of battles that quietly cost you the most rating."))}),React.createElement("div",{className:"pr-rate-tile-grid",style:{display:"grid",gridTemplateColumns:`repeat(${d.length}, 1fr)`,gap:12}},d.map(([u,g])=>React.createElement("div",{key:u,style:{background:"rgba(255,255,255,0.04)",borderRadius:10,padding:"14px 16px",display:"flex",flexDirection:"column"}},React.createElement("div",{style:{fontSize:15,fontWeight:700,color:"#fff"}},s[u]),React.createElement("div",{style:{fontSize:13,color:"var(--pr-text-secondary)",marginBottom:10}},l[u]),React.createElement("div",{style:{marginTop:"auto",display:"flex",justifyContent:"space-between",alignItems:"baseline",fontVariantNumeric:"tabular-nums"}},React.createElement("span",{style:{fontSize:14,color:"var(--pr-text-primary)",fontWeight:500}},g.games," ",g.games===1?"game":"games"),g.games<2?React.createElement("span",{style:{fontSize:17,fontWeight:700,color:"var(--pr-text-secondary)"}},g.wins," ",g.wins===1?"win":"wins"):React.createElement("span",{style:{fontSize:17,fontWeight:700,color:g.winRate>=50?"#5DB67D":"#CF6E6E"}},g.winRate,"% won")))))))}function ChartTip({active:e,payload:t,label:a,formatter:r}){if(!e||!t||!t.length)return null;const o=t.map((n,c)=>{if(r){const l=r(n.value,n.name,n,c,t),d=Array.isArray(l)?l[0]:l,u=Array.isArray(l)?l[1]:n.name;return u!=null&&u!==""?`${u}: ${d}`:`${d}`}return`${t.length===1&&a!=null&&a!==""?a:n.name!=null?n.name:a}: ${n.value}`});return React.createElement("div",{style:{background:"rgba(255,255,255,0.95)",color:"#1a1a1a",fontWeight:700,fontSize:14,lineHeight:1.35,padding:"6px 12px",borderRadius:8,whiteSpace:"nowrap",border:"1px solid rgba(0,0,0,0.12)",backdropFilter:"blur(6px)",boxShadow:"0 6px 18px rgba(0,0,0,0.25)"}},o.map((n,c)=>React.createElement("div",{key:c},n)))}let _plotFloorY=null;function CursorFloorCapture(e){return e&&e.top!=null&&e.height!=null?_plotFloorY=e.top+e.height:e&&e.points&&e.points[1]&&e.points[1].y!=null&&(_plotFloorY=e.points[1].y),null}function DropDot(e){const{cx:t,cy:a,stroke:r,fill:o}=e;if(t==null||a==null)return null;const n=r||o||"#fff";return React.createElement("g",null,_plotFloorY!=null&&_plotFloorY>a&&React.createElement("line",{x1:t,y1:a,x2:t,y2:_plotFloorY,stroke:"rgba(255,255,255,0.4)",strokeWidth:1.5}),React.createElement("circle",{cx:t,cy:a,r:4,fill:n,stroke:"#fff",strokeWidth:1.5}))}function pieceIconUrl(e){return"/assets/pieces/maestro/w"+e+".svg"}function PieceAccuracyChart({analysis:e}){if(e.isHeuristic||!e.__slim&&!e.analyzedGames?.length)return null;const t=e.__slim?e.metrics.pieceAcc:computePieceAccuracy(e.analyzedGames);if(t.length===0)return null;const a=t.reduce((i,s)=>i.accuracy>s.accuracy?i:s),r=t.reduce((i,s)=>i.accuracy<s.accuracy?i:s),o={Pawn:"pawn breaks and structure decisions",Knight:"outpost choice and forking geometry",Bishop:"long-diagonal tactics and good-vs-bad bishop trades",Rook:"open-file timing and endgame technique",Queen:"tactical calculation and avoiding early trades",King:"endgame activity and safety calls"},n=a.accuracy-r.accuracy,c=n<4?`Your accuracy is balanced across pieces (${r.accuracy}-${a.accuracy}%). No single piece is dragging you down, and your decisions carry equal weight whichever piece is moving.`:`Your ${a.name.toLowerCase()} play is ${n.toFixed(1)} points sharper than your ${r.name.toLowerCase()} play (${a.accuracy}% vs ${r.accuracy}%). Your ${r.name.toLowerCase()} moves are where the points are leaking${o[r.name]?`, so work on ${o[r.name]}`:""}.`;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,{cursor:!1,content:i=>React.createElement(ChartTip,{...i,formatter:(s,l,d)=>[`${s}% (${d.payload.moves} moves)`,d.payload.name]})}),React.createElement(Bar,{activeBar:{fillOpacity:1,style:{filter:"brightness(1.5) saturate(1.35)"}},dataKey:"accuracy",radius:[0,4,4,0]},t.map((i,s)=>React.createElement(Cell,{key:s,fill:i.color}))))))),React.createElement("div",{className:"pr-stack--xs"},React.createElement("div",{className:"pr-title--white pr-mb-3"},"Moves per Piece"),t.map(i=>{const s=Math.max(...t.map(d=>d.moves)),l=Math.round(i.moves/s*100);return React.createElement("div",{key:i.piece,className:"pr-piece-bar"},React.createElement("div",{className:"pr-piece-bar__label"},i.name),React.createElement("div",{className:"pr-piece-bar__track"},React.createElement("div",{className:"pr-piece-bar__fill",style:{width:`${l}%`,background:i.color}}),React.createElement("span",{className:"pr-piece-bar__count"},i.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"}},a.name," (",a.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"}},r.name," (",r.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. Rook accuracy reflects endgame technique, knight reflects positional vision, and queen reflects tactical calculation."}),React.createElement(DimCoach,{title:"Your performance",body:c})))}function CastlingAnalysis({analysis:e,games:t}){if(e.isHeuristic||!e.__slim&&!e.analyzedGames?.length)return null;const a=e.__slim?e.metrics.castling:computeCastlingStats(e.analyzedGames);if(a.total===0)return null;const r=l=>{const d=l.win+l.loss+l.draw;return d>0?Math.round(l.win/d*100):0},o=[a.kingSide>0&&{name:"Kingside (O-O)",value:a.kingSide,fill:"#6B9FD4"},a.queenSide>0&&{name:"Queenside (O-O-O)",value:a.queenSide,fill:"#D4A44B"},a.noCastle>0&&{name:"No Castle",value:a.noCastle,fill:"#8A857F"}].filter(Boolean),n=r({win:a.castleResults.kingside.win+a.castleResults.queenside.win,loss:a.castleResults.kingside.loss+a.castleResults.queenside.loss,draw:a.castleResults.kingside.draw+a.castleResults.queenside.draw}),c=r(a.castleResults.none),i=n-c,s=[];return a.castledPct>=90?s.push(`You castle in ${a.castledPct}% of games, a strong king-safety habit.`):a.castledPct>=70?s.push(`You castle in ${a.castledPct}% of games, which is acceptable, but the ${100-a.castledPct}% where you skip it are where the king is exposed.`):s.push(`You castle in only ${a.castledPct}% of games. The king stays in the centre too often. Aim for >85%.`),a.avgCastleMove&&(a.avgCastleMove<=9?s.push(`Average castle move ${a.avgCastleMove}, early and by-the-book opening play.`):a.avgCastleMove<=13?s.push(`Average castle move ${a.avgCastleMove}, on schedule.`):s.push(`Average castle move ${a.avgCastleMove}. Late castling exposes you to king-side attacks. Aim for move 7-10.`)),i>=10?s.push(`You win ${n}% when you castle vs ${c}% when you don't. You are clearly better off with the king safe.`):i<=-10?s.push(`You actually win more often when you DON'T castle (${c}% vs ${n}% castled). That is unusual, probably small sample noise on the no-castle games, but worth watching.`):s.push(`You win at a similar rate whether you castle or not (${n}% castled vs ${c}% not). In this sample, castling is not 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:o,cx:"50%",cy:"50%",innerRadius:40,outerRadius:70,dataKey:"value",label:l=>{const d=typeof window<"u"&&window.innerWidth<640,u=d?l.name.replace(/\s*\([^)]*\)/g,""):l.name;return React.createElement("text",{x:l.x,y:l.y,fill:"var(--pr-text-primary)",textAnchor:l.textAnchor,dominantBaseline:"central",fontSize:d?11:15,fontWeight:500},`${u} ${(l.percent*100).toFixed(0)}%`)},labelLine:!1},o.map((l,d)=>React.createElement(Cell,{key:d,fill:l.fill}))),React.createElement(Tooltip,{cursor:!1,content:ChartTip}))))),React.createElement("div",{className:"pr-grid-2"},React.createElement(StatBox,{label:"Castled",value:`${a.castledPct}%`,sub:`${a.kingSide+a.queenSide} of ${a.total} games`,color:"#6B9FD4"}),React.createElement(StatBox,{label:"Avg Castle Move",value:a.avgCastleMove||"\u2014",sub:"move number",color:"#D4A44B"}),React.createElement(StatBox,{label:"Win% with Castle",value:`${n}%`,sub:"when castled",color:i>=10?"#5DB67D":i<=-10?"#CF6E6E":"#fff"}),React.createElement(StatBox,{label:"Win% without",value:`${c}%`,sub:"when not castled",color:i<=-10?"#5DB67D":i>=10?"#CF6E6E":"#fff"}))),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:s.join(" ")})))}function OpeningDeepDive({analysis:e,games:t}){if(e.isHeuristic||!e.__slim&&!e.analyzedGames?.length)return null;const a=e.__slim?e.metrics.openingDeep:computeOpeningDeepDive(e.analyzedGames);return a.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,a.map((r,o)=>React.createElement("tr",{key:o},React.createElement("td",null,React.createElement("div",{className:"pr-table__name"},r.name)),React.createElement("td",{className:"text-center"},React.createElement("span",{className:"pr-text-xs pr-text-muted"},r.total)),React.createElement("td",{className:"text-center"},r.total<2?React.createElement("span",{className:"pr-text-xs pr-text-muted"},"\u2014"):React.createElement("span",{className:"pr-text-xs pr-font-semibold",style:{color:r.winRate>=55?"#5DB67D":r.winRate>=45?"#D4A44B":"#CF6E6E"}},r.winRate,"%")),React.createElement("td",{className:"text-center"},React.createElement("span",{className:"pr-text-xs pr-font-semibold",style:{color:r.avgAccuracy>=80?"#5DB67D":r.avgAccuracy>=70?"#6B9FD4":"#D4A44B"}},r.avgAccuracy)),React.createElement("td",{className:"text-center"},React.createElement("span",{className:"pr-text-xs pr-text-muted"},r.avgBookDepth!==null?`${r.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"}},r.wins,"W"),React.createElement("span",{className:"pr-text-xs pr-text-dim"},r.draws,"D"),React.createElement("span",{className:"pr-text-xs",style:{color:"#CF6E6E"}},r.losses,"L")))))))))}function MoveQualityDistribution({analysis:e}){if(e.isHeuristic||!e.__slim&&!e.analyzedGames?.length)return null;const t=e.totalClassifications||{},a=Object.values(t).reduce((o,n)=>o+n,0);if(a===0)return null;const r=[{key:"brilliant",label:"Brilliancy",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(o=>({...o,count:t[o.key]||0,pct:Math.round((t[o.key]||0)/a*1e3)/10})).filter(o=>o.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"},r.map(o=>React.createElement("div",{key:o.key,className:"pr-quality-row"},React.createElement("div",{className:"pr-quality-row__label",style:{color:o.color}},o.label),React.createElement("div",{className:"pr-quality-row__bar"},React.createElement("div",{style:{height:"100%",borderRadius:"var(--lumi-radius-xs)",width:`${Math.max(2,o.pct)}%`,background:o.color,opacity:.7}}),React.createElement("span",{className:"pr-piece-bar__pct"},o.pct,"%"),React.createElement("span",{className:"pr-piece-bar__count",style:{color:"var(--lumi-text-muted)"}},o.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:r.slice(0,6),cx:"50%",cy:"50%",innerRadius:50,outerRadius:80,dataKey:"count",label:o=>React.createElement("text",{x:o.x,y:o.y,fill:"var(--pr-text-primary)",textAnchor:o.textAnchor,dominantBaseline:"central",fontSize:15,fontWeight:500},`${o.payload.pct}%`),labelLine:!1},r.slice(0,6).map((o,n)=>React.createElement(Cell,{key:n,fill:o.color}))),React.createElement(Tooltip,{cursor:!1,content:o=>React.createElement(ChartTip,{...o,formatter:(n,c,i)=>[`${n.toLocaleString()} (${i.payload.pct}%)`,i.payload.label]})})))))))}function GameDrillDown({gameAnalysis:e,gameMetadata:t,onBack:a}){if(!e)return null;if(e.isQuickMode)return React.createElement("div",{className:"pr-container",style:{paddingTop:24}},React.createElement("button",{onClick:a,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:r,playerAccuracy:o,opponentAccuracy:n,headers:c}=e,i=r.map((l,d)=>({move:d+1,moveLabel:l.moveNumber,label:`${l.moveNumber}${l.turn==="w"?".":"..."} ${l.san}`,eval:Math.max(-500,Math.min(500,l.whiteEval))/100,cpl:l.isPlayerMove?l.cpl:null,classification:l.classification,san:l.san,turn:l.turn,isPlayer:l.isPlayerMove})),s=r.filter(l=>l.isPlayerMove);return React.createElement("div",{className:"pr-stack pr-animate-section"},React.createElement("button",{onClick:a,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"},c?.White||"?"," vs ",c?.Black||"?"),React.createElement("div",{className:"pr-text-xs pr-text-muted pr-mt-1"},c?.Date," \xB7 ",c?.TimeControl," \xB7 ",c?.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"}},o,"%")),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"},n,"%")))),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:i},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:l=>Math.ceil(l/2),interval:Math.max(1,Math.floor(i.length/20))}),React.createElement(YAxis,{domain:[-5,5],tick:{fontSize:14,fill:"var(--pr-text-primary)",fontWeight:500},tickFormatter:l=>l>0?`+${l}`:`${l}`}),React.createElement(ReferenceLine,{y:0,stroke:"rgba(255,255,255,0.15)",strokeWidth:1.5}),React.createElement(Tooltip,{cursor:React.createElement(CursorFloorCapture,null),content:l=>React.createElement(ChartTip,{...l,formatter:(d,u,g)=>{const p=g.payload;return[`${d>0?"+":""}${d.toFixed(1)}`,p.label]}})}),React.createElement(Area,{activeDot:React.createElement(DropDot,null),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"},s.filter(l=>l.cpl>20).sort((l,d)=>d.cpl-l.cpl).slice(0,10).map((l,d)=>React.createElement("div",{key:d,className:"pr-moment-row",style:{background:CLASSIFICATION_COLORS[l.classification]+"10"}},React.createElement("span",{className:"pr-text-xs pr-text-dim",style:{fontFamily:"monospace",width:32}},l.moveNumber,"."),React.createElement("span",{className:"pr-text-sm pr-font-semibold pr-text-white",style:{width:64}},l.san),React.createElement("span",{className:"pr-badge--pill",style:{background:CLASSIFICATION_COLORS[l.classification]+"25",color:CLASSIFICATION_COLORS[l.classification]}},CLASSIFICATION_LABELS[l.classification]),React.createElement("span",{className:"pr-text-xs pr-text-dim pr-ml-auto"},"-",Math.round(l.cpl)," cp"))),s.filter(l=>l.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. Great game!"))))}function GamesList({analysis:e,games:t,platform:a,onSelectGame:r,limit:o=0}){const[n,c]=useState(!1),i=o&&!n?t.slice(0,o):t,s=!!e.__slim,l=!e.isHeuristic&&e.analyzedGames&&e.analyzedGames.length>0,d=l&&e.analyzedGames.every(u=>!u||u.isQuickMode);return React.createElement(SectionCard,{title:"Game-by-Game Results",badge:l?d?"instant":"analyzed":s?"analyzed":null,delay:.5},React.createElement("div",{className:"pr-game-list pr-stack--1"},i.map((u,g)=>{const p=l?e.analyzedGames[g]:null,h=s&&e.slimGames?.[g]||null,w=h&&(h.url||u.url)||null,S=p?p.playerAccuracy:h?h.a??u.accuracy:u.accuracy,x=u.result==="win"?"W":u.result==="loss"?"L":"D",f=u.result==="win"?"#5DB67D":u.result==="loss"?"#CF6E6E":"#8A857F",v=u.color==="white"?u.black:u.white;return React.createElement("div",{key:g,className:`pr-game-list__item ${l||w?"pr-game-list__item--clickable":""}`,onClick:()=>{l&&p?r(g):w&&window.open(w,"_blank","noopener")}},React.createElement("span",{className:"pr-game-list__result",style:{background:f}},x),React.createElement("div",{className:"pr-game-list__info"},React.createElement("div",{className:"pr-game-list__name"},v),React.createElement("div",{className:"pr-game-list__detail",style:{display:"flex",alignItems:"center",gap:6,minWidth:0}},React.createElement(TcMark,{tc:u.timeClass||h?.tc}),React.createElement("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}},u.opening," \xB7 ",fullMoves(u.moves,a)," moves"))),S!==null&&React.createElement("div",{className:"pr-game-list__acc"},React.createElement("div",{className:"pr-text-sm pr-font-bold",style:{color:S>=85?"#5DB67D":S>=70?"#6B9FD4":"#D4A44B"}},S,"%"),React.createElement("div",{className:"pr-meta--10"},"Accuracy")),l&&p&&React.createElement("span",{className:"pr-text-xs pr-text-dim"},"\u2192"),!l&&w&&React.createElement("span",{className:"pr-text-xs pr-text-dim"},"\u2197"))})),i.length<t.length&&React.createElement("button",{type:"button",className:"pr-games-more",onClick:()=>c(!0)},"Show all ",t.length," games"))}function whenOnWindow(e,t){if(window[e]){t(window[e]);return}const a=Date.now(),r=setInterval(()=>{window[e]?(clearInterval(r),t(window[e])):Date.now()-a>15e3&&clearInterval(r)},40)}const _openedReports=new Map;function ChessProfileReport(){const[e,t]=useReducer(reducer,void 0,()=>{try{const k=location.pathname||"";if(/^\/profile-report\/[^/?#]+/.test(k)||new URLSearchParams(location.search).get("id"))return{...initialState,phase:"fetching"}}catch{}let m=null;try{const k=sessionStorage.getItem("lumichess_pr_resume");k&&(m=JSON.parse(k))}catch{}if(m&&m.username)return{...initialState,phase:"fetching",username:m.username,platform:m.platform||initialState.platform,format:m.format||initialState.format,gameCount:m.gameCount||initialState.gameCount};let b=null;try{b=window.LumiAccounts&&window.LumiAccounts.main()||null}catch{}try{const k=localStorage.getItem("lumichess_pr_last_form"),A=k?JSON.parse(k):{};return{...initialState,platform:b&&b.platform||A.platform||initialState.platform,username:b&&b.username||A.username||initialState.username,format:A.format||initialState.format,gameCount:A.gameCount||initialState.gameCount,depth:initialState.depth}}catch{}return{...initialState,platform:b&&b.platform||initialState.platform,username:b&&b.username||initialState.username}});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 a=useRef(null),r=useRef(!1);useEffect(()=>{e.phase==="complete"&&r.current&&(r.current=!1,import("/src/engagement/streak-daily.js").then(m=>m.reportStreakProgress("profile")).catch(()=>{}))},[e.phase]);const o=useRef(!1);useEffect(()=>{if(o.current||e.signedIn===null)return;let m=null;try{const k=(location.pathname||"").match(/^\/profile-report\/([^/?#]+)/);k&&(m=decodeURIComponent(k[1])),m||(m=new URLSearchParams(location.search).get("id"))}catch{}m&&(o.current=!0,n(m))},[e.signedIn]),useEffect(()=>{(async()=>{try{const m=await window.LumiProfile?.Auth?.getProfile?.();t({type:"SET_SIGNED_IN",value:!!m})}catch{t({type:"SET_SIGNED_IN",value:!1})}})()},[]),useEffect(()=>{(async()=>{try{try{if(sessionStorage.getItem("lumichess_pr_resume"))return;const A=location.pathname||"";if(/^\/profile-report\/[^/?#]+/.test(A)||new URLSearchParams(location.search).get("id"))return}catch{}await ProfileCache.init();const m=await ProfileCache.getLastUsed();if(m){const{platform:A,username:E}=m,M=await ProfileCache.getFullReport(A,E);if(M){t({type:"RESTORE_STATE",p:{...M,platform:A,username:E}});return}}const b=[];try{const A=await window.LumiProfile?.Auth?.getProfile?.();A?.chess_com_username&&b.push({platform:"chesscom",username:A.chess_com_username}),A?.lichess_username&&b.push({platform:"lichess",username:A.lichess_username})}catch{}if(b.length===0)try{const A=localStorage.getItem("lumichess_accounts_local");if(A){const E=JSON.parse(A);Array.isArray(E)&&b.push(...E)}}catch{}const k=window.LumiAccounts&&window.LumiAccounts.main()||b.find(A=>A.platform==="chesscom")||b[0];k&&k.username&&(t({type:"SET_PLATFORM",value:k.platform}),t({type:"SET_USERNAME",value:k.username}))}catch(m){console.warn("Restore failed:",m.message)}})()},[]),useEffect(()=>{(async()=>{try{const m=window.LumiProfile?.ProfileReportHistory;if(!m)return;const b=await m.list(20);b&&b.length>0&&t({type:"SET_HISTORY_LIST",rows:b})}catch(m){console.warn("History list failed:",m.message)}})()},[]);const n=useCallback(async m=>{try{const b=window.LumiProfile?.ProfileReportHistory;if(!b||!m){t({type:"RESET"});return}let k=null;if(m.length<36)try{const E=(await b.list(50)||[]).find(M=>String(M.id).startsWith(m));E&&(k=_openedReports.get(E.id)||await b.get(E.id))}catch{}else k=_openedReports.get(m)||await b.get(m);if(k&&!k.aggregates&&!k.metrics&&(k=null),!k){try{let A=[];try{A=JSON.parse(sessionStorage.getItem("lumi_pr_open_failed")||"[]")}catch{A=[]}Array.isArray(A)||(A=[]),A.push(String(m).slice(0,8)),sessionStorage.setItem("lumi_pr_open_failed",JSON.stringify(A.slice(-20)))}catch{}try{window.history.replaceState(null,"","/profile-report")}catch{}t({type:"RESET"});return}try{sessionStorage.removeItem("lumi_pr_want")}catch{}k.id&&_openedReports.set(k.id,k),showReportAddress(k.id),t({type:"LOAD_HISTORICAL_REPORT",p:{id:k.id,platform:k.platform,username:k.username,format:k.format,depth:k.depth,gameCount:k.game_count,aggregates:k.aggregates,insights:k.insights,metrics:k.metrics,games:k.games}})}catch(b){console.warn("History load failed:",b.message)}},[]),c=useCallback(m=>{const k=(e._historyList||[]).filter(A=>A.format===m&&A.platform===e.platform&&String(A.username).toLowerCase()===String(e.username).toLowerCase()).sort((A,E)=>(E.game_count||0)-(A.game_count||0)||String(E.created_at||"").localeCompare(String(A.created_at||"")))[0];k&&n(k.id)},[e._historyList,e.platform,e.username,n]),i=useCallback(m=>{const b=M=>M.platform===m.platform&&String(M.username).toLowerCase()===String(m.username).toLowerCase(),k=(e._historyList||[]).filter(b),A=M=>M.slice().sort((T,D)=>(D.game_count||0)-(T.game_count||0)||String(D.created_at||"").localeCompare(String(T.created_at||"")))[0],E=A(k.filter(M=>M.format===e.format))||A(k);if(!E){window.location.href=`/profile-report?account=${encodeURIComponent(`${m.platform}:${m.username}`)}`;return}document.querySelectorAll("#root .prv2").forEach(M=>M.classList.add("is-updating"));try{sessionStorage.setItem("lumi_pr_want",`${m.platform}:${m.username}`)}catch{}n(E.id)},[e._historyList,e.format,n]);useEffect(()=>{const m=()=>{e.selectedGameIdx!==null&&t({type:"BACK_TO_REPORT"})};return window.addEventListener("popstate",m),()=>window.removeEventListener("popstate",m)},[e.selectedGameIdx]);const s=useRef(!1),l=useRef(null);useEffect(()=>{if(s.current||e.signedIn===null)return;try{if(/^\/profile-report\/[^/?#]+/.test(location.pathname)||new URLSearchParams(location.search).get("id"))return}catch{}let m=null;try{m=sessionStorage.getItem("lumichess_pr_resume")}catch{}if(!m)return;let b;try{b=JSON.parse(m)}catch{return}s.current=!0,setTimeout(()=>{const k=l.current;k&&k(b)},50)},[e.signedIn]);const d=useCallback(async(m=null)=>{r.current=!0,t({type:"START_FETCH"});const b=(m?.username||e.username).trim().toLowerCase(),k=m?.depth||e.depth,A=m?.platform||e.platform,E=m?.gameCount||e.gameCount,M=m?.format||e.format;try{window.LumiAccounts?.add(A,(m?.username||e.username).trim())}catch{}let T=e.signedIn;if(T===null){try{T=!!await window.LumiProfile?.Auth?.getProfile?.()}catch{T=!1}t({type:"SET_SIGNED_IN",value:T})}if(!T){try{sessionStorage.setItem("lumichess_pr_resume",JSON.stringify({username:b,platform:A,format:M,gameCount:E,fromGuest:!0})),sessionStorage.setItem("lumi_pr_signed_out","1")}catch{}location.replace("/profile-report");return}if(T&&m?.fromGuest&&window.LumiReportQuota)try{const B=await window.LumiReportQuota.reportAllowance();if(B?.blocked){try{sessionStorage.setItem("lumi_pr_quota_sheet",JSON.stringify(B))}catch{}t({type:"BACK_TO_SELECTION"});return}}catch{}try{await ProfileCache.init()}catch(B){console.warn("Cache init failed:",B.message)}let D=null,_=null,C=0;if(A==="lichess"){try{const F=await fetchLichessProfile(b);D=F.profile,_=F.stats}catch(F){t({type:"FETCH_FALLBACK",profile:null,stats:null,error:F.message||"Could not load Lichess profile."});return}let B=[];try{B=await fetchLichessGames(b,E,M,F=>{t({type:"ANALYSIS_PROGRESS",progress:{currentGame:`Streaming games... (${F})`}})},{classicalSeparate:!0})}catch(F){t({type:"FETCH_FALLBACK",profile:D,stats:_,error:F.message||"Could not load Lichess games."});return}if(B.length===0){const F=M==="rapid"&&_?.classical?.wins>0?" Your classical games are under Classical.":"";t({type:"FETCH_FALLBACK",profile:D,stats:_,error:`No ${M==="all"?"":M+" "}games found for "${b}" on Lichess.${F}`});return}const L=B.map(F=>lichessGameToMetadata(F,b)).filter(Boolean);t({type:"FETCH_SUCCESS",profile:D,stats:_,games:L,apiGames:B});try{const F=window.LumiProfile?.OpeningBook;F&&!F.loaded&&await F.load()}catch(F){console.warn("Opening book load failed:",F.message)}let $=null;try{$=new StockfishEngine,await $.init(),a.current=$}catch{t({type:"ENGINE_FALLBACK",error:"Analysis engine failed to load. Showing estimated analysis."});return}for(let F=0;F<B.length;F++){const N=L[F];if(!N){t({type:"GAME_ANALYZED",result:null});continue}const R=N.lichessId||null;t({type:"ANALYSIS_PROGRESS",progress:{gameIndex:F,moveIndex:0,totalGames:B.length,totalMoves:0,currentGame:`${N.white} vs ${N.black}`}});const I=R?await ProfileCache.getGameAnalysis("lichess",R,k):null;if(I){t({type:"GAME_ANALYZED",result:I}),C++;continue}let z=null;if(N.pgn)try{z=await analyzeGameWithEngine(N.pgn,$,k,(W,P)=>{t({type:"ANALYSIS_PROGRESS",progress:{moveIndex:W,totalMoves:P,gameIndex:F,totalGames:B.length,currentGame:`${N.white} vs ${N.black}`}})},b)}catch(W){console.warn(`Failed to analyze Lichess game ${F}:`,W.message)}z&&R&&await ProfileCache.saveGameAnalysis("lichess",R,k,z),t({type:"GAME_ANALYZED",result:z})}$.destroy(),a.current=null}else{try{const R=await fetch(`https://api.chess.com/pub/player/${b}`,{headers:{Accept:"application/json"}});if(!R.ok){t({type:"FETCH_FALLBACK",profile:null,stats:null,error:R.status===404?`User "${b}" not found on Chess.com. Check the spelling.`:`Chess.com API returned ${R.status}. Try again later.`});return}const I=await R.json();D={username:I.username||b,avatar:I.avatar||"",country:I.country?.split("/").pop()||"??",status:I.status||"basic",joined:I.joined||0,lastOnline:I.last_online||0,followers:I.followers||0,league:I.league||"",title:I.title||""};const z=await fetch(`https://api.chess.com/pub/player/${b}/stats`,{headers:{Accept:"application/json"}});if(z.ok){const W=await z.json();_={rapid:{current:W.chess_rapid?.last?.rating||0,best:W.chess_rapid?.best?.rating||0,wins:W.chess_rapid?.record?.win||0,losses:W.chess_rapid?.record?.loss||0,draws:W.chess_rapid?.record?.draw||0},blitz:{current:W.chess_blitz?.last?.rating||0,best:W.chess_blitz?.best?.rating||0,wins:W.chess_blitz?.record?.win||0,losses:W.chess_blitz?.record?.loss||0,draws:W.chess_blitz?.record?.draw||0},bullet:{current:W.chess_bullet?.last?.rating||0,best:W.chess_bullet?.best?.rating||0,wins:W.chess_bullet?.record?.win||0,losses:W.chess_bullet?.record?.loss||0,draws:W.chess_bullet?.record?.draw||0},daily:{current:W.chess_daily?.last?.rating||0,best:W.chess_daily?.best?.rating||0,wins:W.chess_daily?.record?.win||0,losses:W.chess_daily?.record?.loss||0,draws:W.chess_daily?.record?.draw||0},tactics:{highest:W.tactics?.highest?.rating||0},puzzleRush:{best:W.puzzle_rush?.best?.score||0}}}}catch(R){t({type:"FETCH_FALLBACK",profile:null,stats:null,error:`Network error: ${R.message}. Check your internet connection.`});return}const B=M;let L=[];try{L=await fetchChessComGames(b,E,B)}catch(R){console.warn("Game fetch failed:",R.message)}if(L.length===0){const R=B==="all"?"":` ${B}`;t({type:"FETCH_FALLBACK",profile:D,stats:_,error:`No${R} games found for "${D?.username||b}".`});return}const $=L.map(R=>apiGameToMetadata(R,b)).map(R=>B==="classical"&&R?{...R,timeClass:"classical"}:R);t({type:"FETCH_SUCCESS",profile:D,stats:_,games:$,apiGames:L});try{const R=window.LumiProfile?.OpeningBook;R&&!R.loaded&&await R.load()}catch(R){console.warn("Opening book load failed:",R.message)}const F=L;let N=null;try{N=new StockfishEngine,await N.init(),a.current=N}catch{t({type:"ENGINE_FALLBACK",error:"Analysis engine failed to load. Showing estimated analysis."});return}for(let R=0;R<F.length;R++){const I=F[R],z=parsePGNHeaders(I.pgn),W=I.url||z.Link||null,P=W?`v2_${W}`.replace(/[^a-zA-Z0-9_]/g,""):null;t({type:"ANALYSIS_PROGRESS",progress:{gameIndex:R,moveIndex:0,totalGames:F.length,totalMoves:0,currentGame:`${z.White||"?"} vs ${z.Black||"?"}`}});try{const G=P?await ProfileCache.getGameAnalysis("chesscom",P,k):null;if(G){t({type:"GAME_ANALYZED",result:G}),C++;continue}const O=await analyzeGameWithEngine(I.pgn,N,k,(K,j)=>{t({type:"ANALYSIS_PROGRESS",progress:{moveIndex:K,totalMoves:j,gameIndex:R,totalGames:F.length,currentGame:`${z.White||"?"} vs ${z.Black||"?"}`}})},b);O&&P&&await ProfileCache.saveGameAnalysis("chesscom",P,k,O),t({type:"GAME_ANALYZED",result:O})}catch(G){console.warn(`Failed to analyze game ${R}:`,G.message),t({type:"GAME_ANALYZED",result:null})}}N.destroy(),a.current=null}try{window.LumiAnalytics?.track("profile_report_analysis_done",{platform:A,format:e.format,depth:k,game_count:e.gameCount,reason:`cache_hits_${C}`})}catch{}t({type:"ANALYSIS_COMPLETE",correlations:null,patterns:null,progressHistory:[]})},[e.username,e.depth,e.format,e.platform,e.gameCount,e.signedIn]);useEffect(()=>{l.current=d},[d]);const u=useMemo(()=>{if(e.phase!=="complete")return null;if(e._loadedAnalysis){try{const k=e._loadedAnalysis;if(e._loadedSlim&&!k.analyzedGames?.length)return buildSlimAnalysis(k,e._loadedSlim);if(new URLSearchParams(window.location.search).get("slim")==="1"&&k.analyzedGames?.length){const E=e._loadedSlim||window.LumiProfile?.slimReport&&window.LumiProfile.slimReport(k,k.games||[]);if(E)return buildSlimAnalysis(k,E)}}catch(k){console.warn("[slim render] fell back to full render:",k?.message||k)}return e._loadedAnalysis}if(e.isHeuristic)return analyzeGamesHeuristic(e.games,e.stats);const m=buildAnalysisFromEngine(e.analyzedGames,e.games,e.stats);m.correlations=computeCorrelations(e.analyzedGames,e.games),m.patterns=detectPatterns(e.analyzedGames,e.games);const b=e.analyzedGames.filter(k=>k!==null);if(b.length>0){const k=b.map((A,E)=>convertToCoachingRecord(A,e.games[E])).filter(Boolean);if(k.length>0){const A=e.stats?.blitz?.current||e.stats?.rapid?.current||1200;try{const E=computeInlineSkillProfile(k,A);m.skillProfile=E,m.recommendations=computeInlineRecommendations(E,A);const M=window.LumiProfile?.CoachingInsights;if(M)try{m.insights=M.generate(k,E,A)}catch(T){console.warn("CoachingInsights.generate failed:",T.message)}}catch(E){console.warn("SkillProfile computation failed:",E.message)}}}return m},[e.phase,e.isHeuristic,e.analyzedGames,e.games,e.stats,e._loadedAnalysis,e._loadedSlim,e._loadedReportId]),[g,p]=useState([]),[h,w]=useState(!1);useEffect(()=>{if(e.phase!=="complete"||!u||e.isHeuristic||e._loadedReportId)return;const m=e.platform,b=e.username.trim().toLowerCase();(async()=>{try{await ProfileCache.init();const k={};u.skillProfile?.dimensions?Object.entries(u.skillProfile.dimensions).forEach(([T,D])=>{k[T]=D.score||0}):u.radar&&u.radar.forEach(T=>{k[T.dim]=T.value});const A={accuracy:u.avgAccuracy,lumiScore:u.lumiScore,dimensions:k};await ProfileCache.appendHistory(m,b,A),await ProfileCache.saveSnapshot(m,b,A),await ProfileCache.saveFullReport(m,b,{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(m,b);const E=await ProfileCache.getHistory(m,b);p(E);const M=window.LumiProfile?.ProfileReportHistory;if(M){const T=(e.games||[]).map(L=>({headers:L?.headers||null,url:L?.url||null,platform:L?.platform||null,timeControl:L?.timeControl||null,opening:L?.opening||null,date:L?.date||null,finalClock:L?.finalClock??null,result:L?.result??null,method:L?.method??null,moves:L?.moves??null,accuracy:L?.accuracy??null,color:L?.color??null,eco:L?.eco??null,timeClass:L?.timeClass??null,wRating:L?.wRating??null,bRating:L?.bRating??null,white:L?.white??null,black:L?.black??null})),{insights:D,..._}=u,C={..._,profile:e.profile||null,stats:e.stats||null,games:T},B=await M.save({platform:m,username:b,format:e.format,gameCount:e.gameCount,depth:e.depth,aggregates:C,insights:D||null});if(B?.id&&!isMemberInline())try{const L=await M.list(50);for(const $ of Array.isArray(L)?L:[])$.id!==B.id&&await M.remove($.id)}catch(L){console.warn("[profile report] old report not removed:",L?.message||L)}B?.id&&showReportAddress(B.id)}}catch(k){console.warn("Snapshot save failed:",k.message)}})()},[e.phase,u,e.isHeuristic,e.platform,e.username]),useEffect(()=>()=>{a.current&&a.current.destroy()},[]);const S=e.phase==="fetching"||e.phase==="analyzing";if(useEffect(()=>{const m=document.getElementById("pr-vanilla-selection"),b=document.getElementById("root"),k=document.getElementById("prs-card-formfields"),A=document.getElementById("prs-card-loading"),E=document.getElementById("prs-card-loading-static");if(!m||!b)return;if((()=>{try{const D=location.pathname||"";if(/^\/profile-report\/[^/?#]+/.test(D)||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"),m.hidden=!0,b.hidden=!1,k&&(k.style.visibility=""),A&&(A.hidden=!0),E&&(E.style.display="");return}const T=document.getElementById("prs-live");if(S&&T){m.hidden=!0,b.hidden=!0;return}if((e.phase==="complete"||e.phase==="error")&&T&&(document.getElementById("prs-sample")?.remove(),document.getElementById("prs-live-host")?.remove()),S)document.documentElement?.classList.remove("pr-report-active"),document.body?.classList.remove("pr-report-active"),m.hidden=!1,b.hidden=!0,k&&(k.style.visibility="hidden"),A&&(A.hidden=!1),E&&(E.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"),m.hidden=!0,b.hidden=!1,k&&(k.style.visibility=""),A&&(A.hidden=!0),E&&(E.style.display="");else if(e.phase==="ready"&&m.hidden){document.documentElement?.classList.remove("pr-report-active"),document.body?.classList.remove("pr-report-active"),b.hidden=!0,k&&(k.style.visibility=""),A&&(A.hidden=!0),E&&(E.style.display=""),m.hidden=!1;const D=[m,...m.querySelectorAll(".prs-hero, .prs-sub, .prs-card, .prs-past")];D.forEach(_=>{_.style.animation="none"}),m.offsetWidth,D.forEach(_=>{_.style.animation=""})}},[S,e.phase]),useEffect(()=>{if(e.phase==="complete"||e.phase==="error")try{sessionStorage.removeItem("lumichess_pr_resume")}catch{}},[e.phase]),useEffect(()=>{if(!S&&e.phase!=="complete"&&e.phase!=="error")return;const m=e.analyzedGames.filter(Boolean),b=m.length?m.reduce((k,A)=>k+(A.playerAccuracy||0),0)/m.length:null;window.dispatchEvent(new CustomEvent("lumi-pr-progress",{detail:{phase:e.phase,total:e.progress.totalGames||0,done:e.analyzedGames.length,move:e.progress.moveIndex||0,moves:e.progress.totalMoves||0,current:e.progress.currentGame||"",acc:b,username:e.username,platform:e.platform,format:e.format,error:e.phase==="error"?String(e.error||""):"",heuristic:!!e.isHeuristic}}))},[e.phase,e.progress,e.analyzedGames.length,S]),e.selectedGameIdx!==null&&u){const m=u.analyzedGames?.[e.selectedGameIdx]||null;return React.createElement("div",{className:"pr-page"},React.createElement("div",{className:"pr-container"},React.createElement(GameDrillDown,{gameAnalysis:m,gameMetadata:e.games[e.selectedGameIdx],onBack:()=>{try{window.history.back()}catch{t({type:"BACK_TO_REPORT"})}}})))}const x=e.phase==="complete"&&u,f=!e.freeTier&&!isMemberInline(),v=f?weakestSkill(u):null,y=x&&!h&&!e.freeTier&&!u.isHeuristic&&profileReportV2Enabled();return useEffect(()=>{const m=window.__LUMI_FRAME__;!m||!m.setScreen||m.setScreen({title:x?"Profile Report":null,onBack:null})},[x]),useEffect(()=>{if(window.__LUMI_FRAME__)return;const m=e.selectedGameIdx!==null;if(!(x||e.phase==="error"))return;const k=A=>{if(!(!A.target.closest||!A.target.closest(".lumi-tophead__back"))){if(A.preventDefault(),A.stopImmediatePropagation(),m){try{window.history.back()}catch{t({type:"BACK_TO_REPORT"})}return}window.history.back()}};return document.addEventListener("click",k,!0),()=>document.removeEventListener("click",k,!0)},[x,e.phase,e.selectedGameIdx]),useEffect(()=>{if(e.phase!=="ready")return;let m=null;try{m=sessionStorage.getItem("lumi_pr_want"),sessionStorage.removeItem("lumi_pr_want")}catch{}window.location.replace(m?`/profile-report?account=${encodeURIComponent(m)}`:"/profile-report")},[e.phase]),React.createElement("div",{className:"pr-page"},S&&(()=>{const m=document.getElementById("prs-card-loading-react");return m?ReactDOM.createPortal(React.createElement(InlineProgressInner,{state:e}),m):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"})})),x&&y&&React.createElement("div",{className:"pr-container pr-stack pr-v2-host",style:{position:"relative"}},React.createElement(ProfileReportV2Mount,{state:e,analysis:u,onFail:()=>w(!0),onFormat:c,onAccount:i})),x&&!y&&React.createElement("div",{className:"pr-container pr-stack",style:{position:"relative"}},!e.freeTier&&!u.isHeuristic&&React.createElement(ReportSyncSlot,{state:e}),!f&&React.createElement(ReportDelta,{analysis:u,history:e._historyList,platform:e.platform,format:e.format,depth:e.depth,loadedReportId:e._loadedReportId}),e.freeTier&&React.createElement(LockedPreview,{part:"pitch"}),React.createElement(RatingMomentum,{stats:e.stats,analysis:u,username:e.username,platform:e.platform,format:e.format,gameCount:e.games?.length??e.gameCount}),e.freeTier?React.createElement(LockedPreview,{part:"rows"}):React.createElement(React.Fragment,null,React.createElement(PerformanceRadar,{analysis:u,state:e}),f?React.createElement(React.Fragment,null,FREE_OPEN_SKILLS.map(m=>React.createElement(WeakestSkillSection,{key:m,skill:m,analysis:u,games:e.games,username:e.username})),!FREE_OPEN_SKILLS.includes(v)&&React.createElement(WeakestSkillSection,{skill:v,analysis:u,games:e.games,username:e.username}),React.createElement(LockedReport,{analysis:u,weakest:v,games:e.games,username:e.username,stats:e.stats,platform:e.platform}),React.createElement(WorstGamesToReview,{analysis:u})):React.createElement(React.Fragment,null,React.createElement(OpeningDimension,{analysis:u,games:e.games}),React.createElement(SkillDimensionSections,{analysis:u,games:e.games,username:e.username,skipOpening:!0}),React.createElement(ImprovementPlan,{analysis:u,stats:e.stats}),React.createElement(WorstGamesToReview,{analysis:u}),React.createElement(AdditionalInsights,{analysis:u,games:e.games,platform:e.platform})),React.createElement(GamesList,{analysis:u,games:e.games,platform:e.platform,limit:f?5:0,onSelectGame:m=>{if(f){const b=gameLink(e.games?.[m])||u.analyzedGames?.[m]?.url;if(b){location.href=`/game/report?url=${encodeURIComponent(b)}`;return}askToUnlock("game","game breakdown");return}try{window.history.pushState({pr:"drilldown",idx:m},"")}catch{}t({type:"SELECT_GAME",idx:m})}}))))}const DIM_TRAIN={"dim-opening":{href:"/ai-coach-training/openings",label:"Train openings",what:"The Opening Trainer",does:"tactical puzzles from the lines you play",premium:!0},"dim-tactical":{href:"/ai-coach-training/patterns",label:"Train tactics",what:"The Pattern Drill",does:"puzzles on the motifs you miss most",premium:!0},"dim-endgame":{href:"/ai-coach-training/endgames",label:"Train endgames",what:"The Endgame Trainer",does:"puzzles in the endings you score worst",premium:!0},"dim-capitalization":{href:"/ai-coach-training/conversion",label:"Train conversion",what:"Advantage Conversion",does:"winning positions to finish off",premium:!0},"dim-resourcefulness":{href:"/ai-coach-training/mistakes",label:"Train defending",what:"The Mistake Set",does:"positions from your own games, worst first",premium:!0},"dim-consistency":{href:"/ai-coach-training",label:"Today's session",what:"The day's session",does:"a bounded set the coach picks for you",premium:!0},"dim-time-mgmt":{href:"/puzzle/storm",label:"Play Puzzle Storm",what:"Puzzle Storm",does:"three minutes against the clock",premium:!1}};function ReportSyncSlot({state:e}){const t=useRef(null);return useEffect(()=>{if(!t.current)return;let a=null,r=!1;return whenOnWindow("LumiReportSync",o=>{!r&&t.current&&(a=o.attach(t.current,{platform:e.platform,username:e.username,format:e.format,depth:e.depth,gameCount:(e.games||[]).length||e.gameCount,stats:e.stats}))}),()=>{r=!0,a&&a()}},[e.platform,e.username,e.format]),React.createElement("div",{ref:t,className:"pr-sync prv2"})}function profileReportV2Enabled(){try{if(new URLSearchParams(window.location.search).has("v1")||localStorage.getItem("lumi_profile_report_v1")==="1")return!1}catch{}return!!window.LumiProfileReportV2}const V2_TRAIN={opening:"dim-opening",tactical:"dim-tactical",endgame:"dim-endgame",capitalization:"dim-capitalization",resourcefulness:"dim-resourcefulness",consistency:"dim-consistency",time_mgmt:"dim-time-mgmt"};function ProfileReportV2Mount({state:e,analysis:t,onFail:a,onFormat:r,onAccount:o}){const n=useRef(null),c=useRef(null);return useEffect(()=>()=>{try{c.current&&c.current.destroy()}catch{}c.current=null},[]),useEffect(()=>{try{e.format&&localStorage.setItem("lumi_pr_open_format",e.format)}catch{}const i=setTimeout(()=>{const s=e.games||t.games||[],l=e._historyList||[],d=e._loadedReportId?l.find(p=>p.id===e._loadedReportId):null,u=[...new Set(l.filter(p=>p.platform===e.platform&&String(p.username).toLowerCase()===String(e.username).toLowerCase()).map(p=>p.format))],g={analysis:t,games:s,stats:e.stats||t.stats||null,platform:e.platform,format:e.format,username:e.username,slim:e._loadedSlim||null,delta:reportDeltaOf({analysis:t,history:l,platform:e.platform,format:e.format,depth:e.depth,loadedReportId:e._loadedReportId}),reportDate:d?.created_at||null,formats:u,onFormat:r,loadFull:e._loadedReportId&&window.LumiProfile?.ProfileReportHistory?()=>window.LumiProfile.ProfileReportHistory.getWithAggregates(e._loadedReportId):null,onAccounts:document.documentElement.hasAttribute("data-coach-hub")?()=>whenOnWindow("LumiReportAccounts",p=>p.open({platform:e.platform,username:e.username,mainOnly:!0,pick:()=>{const h=window.LumiAccounts;Promise.race([h&&h.flush?h.flush():null,new Promise(w=>setTimeout(w,3e3))]).finally(()=>location.replace("/ai-coach/hub"))}})):()=>whenOnWindow("LumiReportAccounts",p=>p.open({platform:e.platform,username:e.username,pick:o,mainOnly:window.matchMedia("(max-width: 760px)").matches})),sync:{attach:p=>{let h=null,w=!1;return whenOnWindow("LumiReportSync",S=>{w||(h=S.attach(p,{platform:e.platform,username:e.username,format:e.format,depth:e.depth,gameCount:(e.games||[]).length||e.gameCount,stats:e.stats}))}),()=>{w=!0,h&&h()}}},train:Object.fromEntries(Object.entries(V2_TRAIN).map(([p,h])=>[p,{href:DIM_TRAIN[h].href,label:DIM_TRAIN[h].label}])),coach:document.documentElement.hasAttribute("data-coach-hub")?e.signedIn&&isMainAccount(e.platform,e.username)?{mount:p=>{let h=null,w=!1;return whenOnWindow("LumiCoachLayer",S=>{w||(h=S.mount({...p,platform:e.platform,username:e.username,reportId:e._loadedReportId}))}),()=>{w=!0,typeof h=="function"&&h()}}}:e.signedIn&&isOwnAccount(e.platform,e.username)?{mount:p=>mainOnlyNote(p,o)}:null:null,locked:isMemberInline()?null:{unlock:askToUnlock,href:`/membership?c=profile-report-unlock&returnUrl=${encodeURIComponent(location.pathname+location.search)}`},reviewGame:p=>{const h=t.analyzedGames?.[p];if(h&&h.pgn&&!h.isQuickMode){openPgnReview(h,null);return}const w=gameLink(s[p])||t.slimGames?.[p]?.url;w&&window.open(`/game/report?url=${encodeURIComponent(w)}`,"_blank")},onFail:a};try{c.current?c.current.update(g):c.current=window.LumiProfileReportV2.mount(n.current,g)}catch(p){console.error("[profile report v2] falling back to the classic report",p),a()}},0);return()=>clearTimeout(i)},[t,e._historyList,e.signedIn]),React.createElement("div",{ref:n})}function readTierInline(){try{for(const e of Object.keys(localStorage)){if(!/^sb-.*-auth-token$/.test(e))continue;const t=JSON.parse(localStorage.getItem(e)||"null"),a=(t?.currentSession||t)?.access_token;if(!a)continue;const r=a.split(".")[1].replace(/-/g,"+").replace(/_/g,"/"),o=JSON.parse(atob(r+"=".repeat((4-r.length%4)%4)));return String(o.subscription_tier||"free").toLowerCase()}}catch{}return"free"}const PAID_TIERS_INLINE=["plus","pro","premium"];function isMemberInline(){if(PAID_TIERS_INLINE.includes(readTierInline()))return!0;try{const e=String(localStorage.getItem("lumi_tier")||"").toLowerCase();return!!e&&e!=="free"&&e!=="none"}catch{return!1}}const SKILL_KEYS=["opening","tactical","endgame","capitalization","time_mgmt","resourcefulness"];function showReportAddress(e){try{localStorage.setItem("lumi_pr_open_id",String(e))}catch{}const t=document.documentElement.hasAttribute("data-coach-hub")?"/ai-coach/hub":"/profile-report";try{location.pathname!==t&&window.history.replaceState(window.history.state,"",t+location.search+location.hash)}catch{}}function isMainAccount(e,t){try{const a=window.LumiAccounts?.main();return!!a&&a.platform===e&&String(a.username||"").toLowerCase()===String(t||"").toLowerCase()}catch{return!1}}function mainOnlyNote(e,t){const a=window.LumiAccounts?.main(),r=e.top;if(!a||!r)return()=>{};const o=i=>String(i).replace(/[&<>"]/g,s=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;"})[s]);r.innerHTML=`<div class="co-card co-mainnote"><p>Your AI Coach trains your main account, <b>${o(a.username)}</b>.</p><button type="button" class="co-mainnote__go">Open ${o(a.username)}</button></div>`,r.hidden=!1;const n=r.querySelector(".co-mainnote__go"),c=()=>t(a);return n.addEventListener("click",c),()=>{n.removeEventListener("click",c),r.innerHTML="",r.hidden=!0}}function isOwnAccount(e,t){try{const a=String(t||"").toLowerCase();return(window.LumiAccounts?.all()||[]).some(r=>r&&r.platform===e&&String(r.username||"").toLowerCase()===a)}catch{return!1}}function weakestSkill(e){const t=e?.skillProfile?.dimensions;if(!t)return null;let a=null;for(const r of SKILL_KEYS){const o=t[r]?.score;Number.isFinite(o)&&(a===null||o<t[a].score)&&(a=r)}return a}function gameLink(e){if(!e)return null;if(e.url)return e.url;const t=e.pgn||"",a=t.match(/\[Link "(https?:\/\/[^"]+)"\]/)||t.match(/\[Site "(https?:\/\/(?:www\.)?lichess\.org\/[^"]+)"\]/);return a?a[1]:null}function askToUnlock(e,t){const a=`/membership?c=profile-report-lock&returnUrl=${encodeURIComponent(location.pathname+location.search)}`,r=window.LumiUpgradeModal;if(!r){location.href=a;return}r({title:`Your ${t} is ready`,sub:"Members see every section of every report.",href:a,source:`profile-report-lock-${e}`,stage:"locked"})}const SKILL_SECTION={opening:e=>React.createElement(OpeningDimension,{analysis:e.analysis,games:e.games}),tactical:e=>React.createElement(TacticsDimension,{analysis:e.analysis,username:e.username}),endgame:e=>React.createElement(EndgameDimension,{analysis:e.analysis}),capitalization:e=>React.createElement(ConversionDimension,{analysis:e.analysis}),time_mgmt:e=>React.createElement(TimeManagementDimension,{analysis:e.analysis,games:e.games}),resourcefulness:e=>React.createElement(ResourcefulnessDimension,{analysis:e.analysis})};function WeakestSkillSection({skill:e,analysis:t,games:a,username:r}){const o=SKILL_SECTION[e];return!o||!t||t.isHeuristic?null:o({analysis:t,games:a,username:r})}const LockContext=React.createContext(null);function Locked({id:e,name:t,peek:a=210,score:r=null,children:o}){return React.createElement("div",{className:"pr-lock",onClick:()=>askToUnlock(e,t)},React.createElement(LockContext.Provider,{value:{score:r}},React.createElement("div",{className:"pr-lock__body",style:{"--pr-lock-peek":`${a}px`},"aria-hidden":"true",inert:""},o)),React.createElement("div",{className:"pr-lock__bar"},React.createElement("svg",{viewBox:"0 0 24 24",width:"16",height:"16","aria-hidden":"true"},React.createElement("rect",{x:"5",y:"10.5",width:"14",height:"10",rx:"2.4",fill:"#ecb43e"}),React.createElement("path",{d:"M8.2 10.5V8a3.8 3.8 0 0 1 7.6 0v2.5",fill:"none",stroke:"#cf8d1b",strokeWidth:"2.2",strokeLinecap:"round"})),React.createElement("span",{className:"pr-lock__say"},"Members see your full ",t),React.createElement("button",{type:"button",className:"pr-lock__go"},"Unlock")))}const FREE_OPEN_SKILLS=["opening","tactical"],SKILL_ORDER=[["opening","opening breakdown"],["tactical","tactics breakdown"],["endgame","endgame breakdown"],["capitalization","conversion breakdown"],["time_mgmt","time breakdown"],["resourcefulness","defence breakdown"]],AUTO_LOCK_KEY="lumi_pr_lock_offer_day";function lockOfferToday(){const e=new Date().toLocaleDateString("en-CA");try{if(localStorage.getItem(AUTO_LOCK_KEY)===e)return!1}catch{}if(/LumichessNative/.test(navigator.userAgent)||document.documentElement.classList.contains("lumi-inshell")||[...document.querySelectorAll('[role="dialog"][aria-modal="true"], #mem-upgrade, .lumi-streak-overlay')].some(a=>{const r=a.getBoundingClientRect();return r.width>0&&r.height>0})||!window.LumiUpgradeModal)return!1;try{localStorage.setItem(AUTO_LOCK_KEY,e)}catch{}return window.LumiUpgradeModal({title:"There is more in your report",sub:"Members see every section of every report.",href:`/membership?c=profile-report-autolock&returnUrl=${encodeURIComponent(location.pathname+location.search)}`,source:"profile-report-autolock",stage:"offer"}),!0}function useAutoLockOffer(e){useEffect(()=>{const t=e.current;if(!t)return;const a=new Date().toLocaleDateString("en-CA");try{if(localStorage.getItem(AUTO_LOCK_KEY)===a)return}catch{}if(/LumichessNative/.test(navigator.userAgent)||document.documentElement.classList.contains("lumi-inshell"))return;const r=1200;let o=0;const n=setInterval(()=>{const c=t.getBoundingClientRect(),i=innerHeight/2;if(!(c.top<i&&c.bottom>i)){o=0;return}if(!o){o=Date.now();return}if(!(Date.now()-o<r)){if(lockOfferToday()){clearInterval(n);return}try{if(localStorage.getItem(AUTO_LOCK_KEY)===a){clearInterval(n);return}}catch{}o=0}},300);return()=>clearInterval(n)},[e])}function LockedReport({analysis:e,weakest:t,games:a,username:r,stats:o,platform:n}){const c=useRef(null);if(useAutoLockOffer(c),!e||e.isHeuristic)return null;const i=SKILL_ORDER.filter(([s])=>s!==t&&!FREE_OPEN_SKILLS.includes(s));return React.createElement(React.Fragment,null,React.createElement("div",{ref:c,className:"pr-stack"},i.map(([s,l])=>React.createElement(Locked,{key:s,id:s,name:l,score:e.skillProfile?.dimensions?.[s]?.score},SKILL_SECTION[s]({analysis:e,games:a,username:r}))),React.createElement(Locked,{id:"consistency",name:"consistency breakdown"},React.createElement(ConsistencyDimension,{analysis:e,games:a})),React.createElement(Locked,{id:"plan",name:"improvement plan",peek:210},React.createElement(ImprovementPlan,{analysis:e,stats:o})),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(Locked,{id:"mental",name:"mental game read",peek:170},React.createElement(PsychProfile,{analysis:e,platform:n})),React.createElement(Locked,{id:"color",name:"colour breakdown",peek:170},React.createElement(ColorAsymmetry,{analysis:e})),React.createElement(Locked,{id:"piece",name:"piece breakdown",peek:170},React.createElement(AccuracyByPieceInsight,{analysis:e})),React.createElement(Locked,{id:"phases",name:"game phases",peek:170},React.createElement(GamePhaseDeepDive,{analysis:e,games:a})),React.createElement(Locked,{id:"castling",name:"castling read",peek:170},React.createElement(CastlingAnalysis,{analysis:e,games:a})),React.createElement(Locked,{id:"results",name:"win and loss read",peek:170},React.createElement(WinLossMethods,{analysis:e}))))}const DIM_SCORE_KEY={"dim-opening":"opening","dim-tactical":"tactical","dim-endgame":"endgame","dim-capitalization":"capitalization","dim-resourcefulness":"resourcefulness","dim-time-mgmt":"time_mgmt"};function dimStanding(e,t){const a=DIM_SCORE_KEY[e],r=t?.skillProfile?.dimensions;if(!a||!r)return null;const o=Math.round(r[a]?.score);if(!Number.isFinite(o))return null;const n=Object.values(r).map(c=>Math.round(c?.score)).filter(Number.isFinite);return{score:o,weakest:n.length>1&&o===Math.min(...n)}}const RADAR_ORDER=["opening","tactical","endgame","capitalization","time_mgmt","resourcefulness"],RADAR_SHORT={opening:"Opening",tactical:"Tactics",endgame:"Endgame",capitalization:"Conversion",time_mgmt:"Time",resourcefulness:"Defence"};function radarHeroHtml(e,t){const a=t?.skillProfile?.dimensions,r=DIM_SCORE_KEY[e];if(!a)return null;const o=RADAR_ORDER.filter(S=>Number.isFinite(Math.round(a[S]?.score)));if(o.length<3)return null;const n=120,c=104,i=72,s=(S,x)=>{const f=(-90+S*(360/o.length))*Math.PI/180;return[n+Math.cos(f)*i*x,c+Math.sin(f)*i*x]},l=([S,x])=>`${S.toFixed(1)},${x.toFixed(1)}`,d=S=>o.map((x,f)=>l(s(f,S))).join(" "),u=o.map((S,x)=>l(s(x,Math.max(8,Math.round(a[S].score))/100))).join(" "),g=o.indexOf(r),p=g>=0?s(g,Math.max(8,Math.round(a[r].score))/100):null,h=g>=0?s(g,1.13):null,w=h?h[0]<n-8?"end":h[0]>n+8?"start":"middle":"middle";return`
      <svg class="mem-radar" viewBox="0 0 240 200" role="img" aria-label="Your skill profile, with this module's axis marked">
        <polygon points="${d(1)}" class="mem-radar__ring" />
        <polygon points="${d(.66)}" class="mem-radar__ring" />
        <polygon points="${d(.33)}" class="mem-radar__ring" />
        ${o.map((S,x)=>`<line x1="${n}" y1="${c}" x2="${s(x,1)[0].toFixed(1)}" y2="${s(x,1)[1].toFixed(1)}" class="mem-radar__axis${x===g?" is-target":""}" />`).join("")}
        <polygon points="${u}" class="mem-radar__shape" />
        ${o.map((S,x)=>`<circle cx="${s(x,Math.max(8,Math.round(a[o[x]].score))/100)[0].toFixed(1)}" cy="${s(x,Math.max(8,Math.round(a[o[x]].score))/100)[1].toFixed(1)}" r="${x===g?3.6:2.2}" class="mem-radar__dot${x===g?" is-target":""}" />`).join("")}
        ${p?`<circle cx="${p[0].toFixed(1)}" cy="${p[1].toFixed(1)}" r="5" class="mem-radar__pulse" />
                <circle cx="${p[0].toFixed(1)}" cy="${p[1].toFixed(1)}" r="5" class="mem-radar__pulse mem-radar__pulse--late" />`:""}
        ${h&&RADAR_SHORT[r]?`<text x="${h[0].toFixed(1)}" y="${h[1].toFixed(1)}" class="mem-radar__label" text-anchor="${w}" dominant-baseline="middle">${RADAR_SHORT[r]}</text>`:""}
      </svg>`}function TrainButton({id:e,analysis:t}){const a=DIM_TRAIN[e];if(!a)return null;const r=o=>{const n=PAID_TIERS_INLINE.includes(readTierInline());try{window.LumiAnalytics?.track("profile_report_train_clicked",{module:e,href:a.href,paid:n})}catch{}if(!a.premium||n)return;const c=window.LumiUpgradeModal;if(!c)return;o.preventDefault();const i=dimStanding(e,t),s=RADAR_SHORT[DIM_SCORE_KEY[e]]||"",l=i?`Your ${s} score is ${i.score} of 100${i.weakest?", your lowest":""}.`:"Your report has just measured it.";c({heroHtml:radarHeroHtml(e,t),eyebrow:"AI Coach",title:i&&i.weakest?"Your weakest area":"Train this weakness",sub:`${l} ${a.what} works on it with ${a.does}.`,cta:"Get Premium",href:`/membership?c=profile-report-train&returnUrl=${encodeURIComponent(a.href)}`,source:`profile-report-${e}`})};return React.createElement("a",{className:"pr-train",href:a.href,onClick:r},a.label,React.createElement("svg",{viewBox:"0 0 24 24","aria-hidden":"true"},React.createElement("path",{d:"M9 5l7 7-7 7",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round"})))}function DimSectionCard({id:e,title:t,children:a,analysis:r}){const o=React.useContext(LockContext);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:"var(--lumi-accent)",letterSpacing:"-0.01em"}},t),o&&Number.isFinite(o.score)&&React.createElement("span",{className:"pr-lock__score",style:{color:o.score>=65?"#5DB67D":o.score>=45?"#D4A44B":"#CF6E6E"}},Math.round(o.score)),!o&&React.createElement(TrainButton,{id:e,analysis:r})),React.createElement("div",{className:"pr-grid-2--lg"},a))}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))}const EV15_CLAMP_PAWNS=5;function evalAt15(e,t=1){const a=e.evalGraph[28]*t/100;return Math.max(-EV15_CLAMP_PAWNS,Math.min(EV15_CLAMP_PAWNS,a))}function OpeningDimension({analysis:e,games:t}){const[a,r]=useState(!1);let o,n,c,i,s,l,d,u,g,p,h;if(e.__slim){const x=e.metrics.openingDim;if(!x)return null;({avgEval15:o,avgEval15W:n,avgEval15B:c,avgBookDepth:i,avgLeaveBook:s,firstMoves:l,firstMovesBlack:d,allOpeningsList:u,nReal:g,nWhite:p,nBlack:h}=x)}else{const x=(e.analyzedGames||[]).filter(_=>!_.isQuickMode);if(x.length===0)return null;const f=x.filter(_=>_.evalGraph&&_.evalGraph.length>=29).map(_=>{const C=_.playerColor==="w"?1:-1;return evalAt15(_,C)}),v=x.filter(_=>_.playerColor==="w"&&_.evalGraph&&_.evalGraph.length>=29).map(_=>evalAt15(_,1)),y=x.filter(_=>_.playerColor==="b"&&_.evalGraph&&_.evalGraph.length>=29).map(_=>evalAt15(_,-1));o=f.length>0?+(f.reduce((_,C)=>_+C,0)/f.length).toFixed(1):null,n=v.length>0?+(v.reduce((_,C)=>_+C,0)/v.length).toFixed(1):null,c=y.length>0?+(y.reduce((_,C)=>_+C,0)/y.length).toFixed(1):null;const m=[],b=[];x.forEach(_=>{const C=_.moveAnalysis.filter($=>$.isPlayerMove);let B=0;for(const $ of C)if($.classification==="book"||$.classification==="best"||$.classification==="excellent")B++;else break;m.push(B);const L=C.findIndex($=>$.classification!=="book");b.push(L===-1?C.length:L+1)}),i=m.length>0?+(m.reduce((_,C)=>_+C,0)/m.length).toFixed(1):null,s=b.length>0?+(b.reduce((_,C)=>_+C,0)/b.length).toFixed(1):null;const k=x.filter(_=>_.playerColor==="w"),A={};k.forEach(_=>{const C=_.moveAnalysis.find(B=>B.isPlayerMove);if(C){const B=C.san||"?";A[B]=(A[B]||0)+1}}),l=Object.entries(A).sort((_,C)=>C[1]-_[1]).slice(0,4);const E=x.filter(_=>_.playerColor==="b"),M={};E.forEach(_=>{const C=_.moveAnalysis.find(B=>B.isPlayerMove);if(C){const B=C.san||"?";M[B]=(M[B]||0)+1}}),d=Object.entries(M).sort((_,C)=>C[1]-_[1]).slice(0,4);const T={};x.forEach(_=>{const C=openingNameFromHeaders(_.headers||{}),B=_.playerColor;T[C]||(T[C]={wins:0,losses:0,draws:0,total:0,accs:[],evalAt15:[],exitCps:[]}),T[C].total++;const L=_.headers?.Result;if(B==="w"&&L==="1-0"||B==="b"&&L==="0-1"?T[C].wins++:L==="1/2-1/2"?T[C].draws++:T[C].losses++,T[C].accs.push(_.playerAccuracy),_.evalGraph&&_.evalGraph.length>=29){const N=B==="w"?1:-1;T[C].evalAt15.push(evalAt15(_,N))}const F=window.LumiProfile?.openingExitCp?.(_);F!=null&&T[C].exitCps.push(F)});const D=([_,C])=>{const B=C.exitCps.length>0?+(C.exitCps.reduce((L,$)=>L+$,0)/C.exitCps.length/100).toFixed(1):null;return{name:_,...C,winRate:Math.round(C.wins/C.total*100),avgAcc:Math.round(C.accs.reduce((L,$)=>L+$,0)/C.accs.length),avgEv15:C.evalAt15.length>0?+(C.evalAt15.reduce((L,$)=>L+$,0)/C.evalAt15.length).toFixed(1):null,avgExit:B,exitVerdict:window.LumiProfile?.openingPhaseVerdict?.(B)??null}};u=Object.entries(T).map(D).sort((_,C)=>C.total-_.total),g=x.length,p=k.length,h=E.length}const w=x=>x>=.3?"#5DB67D":x<=-.3?"#CF6E6E":"#D4A44B",S=x=>x>=60?"#5DB67D":x>=40?"#D4A44B":"#CF6E6E";return React.createElement(DimSectionCard,{id:"dim-opening",title:"Opening",analysis:e},React.createElement("div",null,o!==null&&React.createElement(React.Fragment,null,React.createElement("div",{className:"pr-label pr-mb-3"},"How you stand 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:w(o)}},o>=0?"+":"",o)),n!==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:w(n)}},n>=0?"+":"",n)),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:w(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," opening families across ",g," games.",s!==null&&React.createElement(React.Fragment,null," You stay in book theory for ",React.createElement("strong",{style:{color:"#fff"}},"~",Math.round(s)," 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)."),o!==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:")," ",o>=.3?"By move 15 you are consistently ahead. Your preparation is paying off.":o<=-.3?"By move 15 you are usually behind. Focus on studying your opening repertoire.":"By move 15 you are roughly equal. That is solid, but finding ways to get an edge will boost results.",n!==null&&c!==null&&Math.abs(n-c)>.5&&` Your ${n>c?"White":"Black"} openings are stronger (${n>c?`+${n}`:`${c>=0?"+":""}${c}`} vs ${n>c?(c>=0?"+":"")+c:"+"+n}).`)),React.createElement("div",null,p>0&&l.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}},l.map(([x,f])=>{const v=Math.round(f/p*100);return React.createElement("div",{key:x,style:{display:"flex",alignItems:"center",gap:8}},React.createElement("span",{style:{fontSize:14,fontWeight:600,color:"#fff",width:36}},x),React.createElement("div",{style:{flex:1,height:14,background:"rgba(255,255,255,0.06)",borderRadius:4,overflow:"hidden"}},React.createElement("div",{style:{width:`${v}%`,height:"100%",background:"#D4A44B",borderRadius:4}})),React.createElement("span",{style:{fontSize:13,color:"var(--pr-text-body)",width:50,textAlign:"right"}},v,"%"))})))),React.createElement("div",null,h>0&&d.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}},d.map(([x,f])=>{const v=Math.round(f/h*100);return React.createElement("div",{key:x,style:{display:"flex",alignItems:"center",gap:8}},React.createElement("span",{style:{fontSize:14,fontWeight:600,color:"#fff",width:36}},x),React.createElement("div",{style:{flex:1,height:14,background:"rgba(255,255,255,0.06)",borderRadius:4,overflow:"hidden"}},React.createElement("div",{style:{width:`${v}%`,height:"100%",background:"#6B9FD4",borderRadius:4}})),React.createElement("span",{style:{fontSize:13,color:"var(--pr-text-body)",width:50,textAlign:"right"}},v,"%"))})))),React.createElement("div",{style:{gridColumn:"1 / -1"}},React.createElement("div",{className:"pr-label pr-mb-3"},"Most-Played Openings"),(()=>{const x=u,f=C=>C.name;let v;if(a)v=[...x].sort((C,B)=>B.total-C.total).map(C=>({...C,tag:null}));else{const C=[...x].sort((R,I)=>I.total-R.total).slice(0,5),B=new Set(C.map(f)),$=[...x.filter(R=>!B.has(f(R))&&R.total>=2)].sort((R,I)=>I.winRate-R.winRate||I.total-R.total).slice(0,2);$.forEach(R=>B.add(f(R)));const N=[...x.filter(R=>!B.has(f(R))&&R.total>=2)].sort((R,I)=>R.winRate-I.winRate||I.total-R.total).slice(0,2);v=[...C.map(R=>({...R,tag:null})),...$.map(R=>({...R,tag:"Bright spot"})),...N.map(R=>({...R,tag:"Needs work"}))]}const y=C=>C>=55?"#5DB67D":C>=40?"#D4A44B":"#CF6E6E",m=C=>C==="Bright spot"?"rgba(93,182,125,0.18)":C==="Needs work"?"rgba(207,110,110,0.18)":null,b=C=>C==="Bright spot"?"#9ED6B2":C==="Needs work"?"#E3A8A8":null,k=C=>C==="better"?"rgba(93,182,125,0.18)":C==="worse"?"rgba(207,110,110,0.18)":"rgba(212,164,75,0.18)",A=C=>C==="better"?"#9ED6B2":C==="worse"?"#E3A8A8":"#E0C489",E=C=>C==="better"?"Better":C==="worse"?"Worse":"Equal",M=C=>{if(C.total<2){const L=(()=>{const $=C.avgEv15;return $==null?null:Math.max(-EV15_CLAMP_PAWNS,Math.min(EV15_CLAMP_PAWNS,$))})();return L!==null?`One analyzed game with this opening: at move 15 you stood ${L>=0?"+":""}${L}. Too few games to read a trend into.`:"One analyzed game with this opening. Too few to judge."}const B=(()=>{const L=C.avgEv15;return L==null?null:Math.max(-EV15_CLAMP_PAWNS,Math.min(EV15_CLAMP_PAWNS,L))})();return B!==null&&B>=.3&&C.winRate>=55?`At move 15 you stand ${B>=0?"+":""}${B} and win ${C.winRate}% of the time. This opening is working. Keep it in your repertoire.`:B!==null&&B>=.3&&C.winRate<45?`At move 15 you stand ${B>=0?"+":""}${B} but only win ${C.winRate}%. The opening is fine; you're losing these games in the middlegame.`:B!==null&&B<=-.3&&C.winRate>=55?`At move 15 you stand ${B} pawns but win ${C.winRate}%. Your defense is strong, though better preparation would make these games easier.`:B!==null&&B<=-.3?`At move 15 you stand ${B} pawns. Study the theory or switch to an opening you know better.`:C.winRate>=55?`${C.winRate}% wins, ${C.avgAcc}% accuracy. This opening is working for you.`:C.winRate<40?`${C.winRate}% wins, ${C.avgAcc}% accuracy. This opening isn't producing results. Study the main ideas or switch to one you're more comfortable with.`:`${C.winRate}% wins, ${C.avgAcc}% accuracy. Results are average. Deeper preparation would help.`},T=C=>{const B=[];return C.wins&&B.push(`${C.wins} won`),C.draws&&B.push(`${C.draws} drawn`),C.losses&&B.push(`${C.losses} lost`),B.join(", ")},D=x.length,_=D>v.length||a;return React.createElement(React.Fragment,null,v.map(C=>{const B=y(C.winRate);return React.createElement("div",{key:f(C)+(C.tag||""),style:{marginBottom:18,paddingLeft:14,borderLeft:`2px solid ${B}`}},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"}},C.name),React.createElement("span",{style:{color:"var(--pr-text-secondary)",fontSize:14}},"(",C.total," game",C.total!==1?"s":""," \xB7 ",T(C),")"),C.tag&&React.createElement("span",{style:{fontSize:13,fontWeight:600,padding:"2px 8px",borderRadius:10,background:m(C.tag),color:b(C.tag)}},C.tag),C.exitVerdict&&React.createElement("span",{title:"Average engine eval on your last opening move. The line below is the eval at move 15.",style:{fontSize:13,fontWeight:600,padding:"2px 8px",borderRadius:10,background:k(C.exitVerdict),color:A(C.exitVerdict)}},E(C.exitVerdict)," when the opening ends (",C.avgExit>0?"+":"",C.avgExit,")")),React.createElement("div",{style:{fontSize:16,color:"var(--pr-text-primary)",lineHeight:1.55,marginTop:6,fontWeight:500}},M(C)))}),_&&React.createElement("button",{type:"button",onClick:()=>r(C=>!C),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:C=>{C.currentTarget.style.background="rgba(255,255,255,0.04)",C.currentTarget.style.borderColor="rgba(255,255,255,0.25)"},onMouseLeave:C=>{C.currentTarget.style.background="transparent",C.currentTarget.style.borderColor="rgba(255,255,255,0.15)"}},a?"Show fewer \u2191":`Show all ${D} variations \u2193`))})()),(()=>{const x=(u||[]).filter(b=>b.avgExit!=null&&b.total>=2);if(x.length===0)return null;const f=[...x].sort((b,k)=>b.avgExit-k.avgExit),v=f[0],y=b=>b==="better"?"#5DB67D":b==="worse"?"#CF6E6E":"#D4A44B",m=Math.max(1,...f.map(b=>Math.abs(b.avgExit)));return React.createElement("div",{style:{gridColumn:"1 / -1"}},React.createElement("div",{className:"pr-label pr-mb-3"},"Coming Out of the Opening"),React.createElement("div",{style:{display:"flex",flexDirection:"column",gap:10}},f.map(b=>{const k=Math.abs(b.avgExit)/m*50,A=b.avgExit<0;return React.createElement("div",{key:b.name,style:{display:"flex",alignItems:"center",gap:12}},React.createElement("div",{style:{flex:"0 0 34%",minWidth:0,fontSize:15,color:"var(--pr-text-primary)",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}},b.name,React.createElement("span",{style:{color:"var(--pr-text-secondary)",fontSize:13,fontWeight:400}}," \xB7 ",b.total," game",b.total!==1?"s":"")),React.createElement("div",{style:{flex:1,position:"relative",height:18,background:"rgba(255,255,255,0.04)",borderRadius:4}},React.createElement("div",{style:{position:"absolute",left:"50%",top:0,bottom:0,width:1,background:"rgba(255,255,255,0.18)"}}),React.createElement("div",{style:{position:"absolute",top:3,bottom:3,[A?"right":"left"]:"50%",width:`${k}%`,background:y(b.exitVerdict),borderRadius:3}})),React.createElement("div",{style:{flex:"0 0 62px",textAlign:"right",fontSize:15,fontWeight:700,color:y(b.exitVerdict)}},b.avgExit>0?"+":"",b.avgExit))})),React.createElement("div",{style:{marginTop:16}}),React.createElement(DimCoach,{title:"What this measures",body:"The engine evaluation at the moment each game actually leaves the opening, the position you hand yourself going into the middlegame. Unlike Score on Move 15 above, this tracks the real opening\u2192middlegame boundary, so it isn't thrown off by games that leave theory early or stay in it long. Positive means you come out better; the equal band is \u22120.7 to +0.7."}),React.createElement(DimCoach,{title:"Your performance",body:v.exitVerdict==="worse"?`You come out of ${v.name} worst, at ${v.avgExit} across ${v.total} games. That is a preparation leak, not a middlegame one. The position is already worse before the middlegame starts, so studying this line pays back directly.`:`No line drops you below the equal band. Your worst exit is ${v.name} at ${v.avgExit>0?"+":""}${v.avgExit} over ${v.total} games, which is within equal. Your openings are handing you playable middlegames.`}))})())}function TacticsDimension({analysis:e,username:t}){const a=e.analyzedGames||[];if(!e.__slim&&a.length===0)return null;const r=e.totalClassifications||{},o=Object.values(r).reduce((h,w)=>h+w,0)||1,n=e.__slim?e.analyzedCount||e.total||1:a.length,c=((r.blunder||0)/n).toFixed(1),i=Math.round(((r.best||0)+(r.excellent||0)+(r.good||0))/o*100),s=[{key:"brilliant",label:"Brilliancy",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(h=>({...h,count:r[h.key]||0,pct:Math.round((r[h.key]||0)/o*1e3)/10})).filter(h=>h.count>0);let l,d,u,g;if(e.__slim){const h=e.metrics.errorFp;if(!h)return null;({tacticsVsOpp:l,youTotalErrors:d,oppTotalErrors:u,phaseData:g}=h)}else{const h=a.flatMap(k=>k.moveAnalysis.filter(A=>A.isPlayerMove)),w=["inaccuracy","mistake","blunder"],S=a.flatMap(k=>k.moveAnalysis.filter(A=>!A.isPlayerMove)),x={inaccuracy:0,mistake:0,blunder:0},f={inaccuracy:0,mistake:0,blunder:0};h.forEach(k=>{w.includes(k.classification)&&x[k.classification]++}),S.forEach(k=>{w.includes(k.classification)&&f[k.classification]++});const v=a.length;l=[{type:"Blunders",you:+(x.blunder/v).toFixed(1),opponents:+(f.blunder/v).toFixed(1),fill:"#CF6E6E"},{type:"Mistakes",you:+(x.mistake/v).toFixed(1),opponents:+(f.mistake/v).toFixed(1),fill:"#ffa459"},{type:"Inaccuracies",you:+(x.inaccuracy/v).toFixed(1),opponents:+(f.inaccuracy/v).toFixed(1),fill:"#f7c631"}],d=l.reduce((k,A)=>k+A.you,0),u=l.reduce((k,A)=>k+A.opponents,0);const y={opening:0,middlegame:0,endgame:0},m={opening:{inaccuracy:0,mistake:0,blunder:0},middlegame:{inaccuracy:0,mistake:0,blunder:0},endgame:{inaccuracy:0,mistake:0,blunder:0}};h.forEach(k=>{const A=k.gamePhase;A&&y[A]!==void 0&&w.includes(k.classification)&&(y[A]++,m[A][k.classification]++)});const b=y.opening+y.middlegame+y.endgame;g=[{phase:"Opening",errors:y.opening,pct:b>0?Math.round(y.opening/b*100):0,fill:"#D4A44B",...m.opening},{phase:"Middlegame",errors:y.middlegame,pct:b>0?Math.round(y.middlegame/b*100):0,fill:"#CF6E6E",...m.middlegame},{phase:"Endgame",errors:y.endgame,pct:b>0?Math.round(y.endgame/b*100):0,fill:"#6B9FD4",...m.endgame}]}const p={background:"rgba(255,255,255,0.92)",border:"1px solid rgba(0,0,0,0.12)",borderRadius:8,padding:"6px 12px",fontSize:15,color:"#1f1f1f",whiteSpace:"nowrap",backdropFilter:"blur(6px)",boxShadow:"0 6px 18px rgba(0,0,0,0.22)"};return React.createElement(DimSectionCard,{id:"dim-tactical",title:"Tactics",analysis:e},React.createElement("div",null,React.createElement("div",{className:"pr-label pr-mb-3"},"Move Quality"),React.createElement("div",{className:"pr-stack--2"},s.map(h=>React.createElement("div",{key:h.key,className:"pr-quality-row"},React.createElement("div",{className:"pr-quality-row__label",style:{color:h.color}},h.label),React.createElement("div",{className:"pr-quality-row__bar"},React.createElement("div",{style:{height:"100%",borderRadius:"var(--lumi-radius-xs)",width:`${Math.max(2,h.pct)}%`,background:h.color,opacity:.7}}),React.createElement("span",{className:"pr-piece-bar__pct"},h.pct,"%"),React.createElement("span",{className:"pr-piece-bar__count",style:{color:"var(--lumi-text-muted)"}},h.count.toLocaleString())))))),React.createElement("div",null,React.createElement(DimCoach,{title:"Move quality",body:`${i}% of your moves were good, excellent, or best across ${n} games.`}),React.createElement(DimCoach,{title:"Blunder rate",body:`You average ${c} blunders per game. ${parseFloat(c)>2?"Reducing blunders is the single biggest lever for rating improvement.":parseFloat(c)>1?"You're within normal range. Eliminating the remaining blunders will unlock your next rating tier.":"Excellent blunder control and strong tactical awareness."}`})),React.createElement("div",{style:{gridColumn:"1 / -1"}},React.createElement("div",{className:"pr-label pr-mb-3"},"Error Fingerprint"),(()=>{const h=[{key:"inaccuracy",label:"Inaccuracies",color:"#f7c631"},{key:"mistake",label:"Mistakes",color:"#ffa459"},{key:"blunder",label:"Blunders",color:"#CF6E6E"}];let w=0,S=null;g.forEach(E=>h.forEach(M=>{const T=E[M.key]||0;T>w&&(w=T,S={phase:E.phase,sev:M})}));const x=g.reduce((E,M)=>E+M.errors,0),f=E=>{const M=parseInt(E.slice(1),16);return`${M>>16&255},${M>>8&255},${M&255}`},v=d-u,y=(v>=0?"+":"")+v.toFixed(1),m=v>.05,b=v<-.05,k=m?"#CF6E6E":b?"#5DB67D":"#D4A44B",A=Math.max(d,u,.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: ",React.createElement("b",{style:{color:"#fff",fontWeight:700}},"You ",d.toFixed(1))," vs ",React.createElement("b",{style:{color:"var(--pr-text-primary)",fontWeight:700}},"Opp ",u.toFixed(1))," ",React.createElement("span",{style:{color:k,fontWeight:700,fontVariantNumeric:"tabular-nums"}},"(",y,")")),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:`${d/A*100}%`,background:m?"#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:`${u/A*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),h.map(E=>React.createElement("div",{key:E.key,style:{textAlign:"center",fontSize:12,fontWeight:700,color:E.color,textTransform:"uppercase",letterSpacing:"0.04em",paddingBottom:2,borderBottom:`2px solid ${E.color}`}},E.label)),g.map(E=>React.createElement(React.Fragment,{key:E.phase},React.createElement("div",{style:{display:"flex",alignItems:"center",fontSize:15,fontWeight:600,color:"#fff"}},E.phase),h.map(M=>{const T=E[M.key]||0,D=w>0?T/w:0;return React.createElement("div",{key:M.key,style:{position:"relative",display:"flex",alignItems:"center",justifyContent:"center",minHeight:44,borderRadius:8,background:`rgba(${f(M.color)}, ${(.08+D*.55).toFixed(3)})`,border:"1px solid rgba(255,255,255,0.05)"}},React.createElement("span",{style:{fontSize:18,fontWeight:800,lineHeight:1,color:T===0?"var(--pr-text-secondary)":"#fff",fontVariantNumeric:"tabular-nums"}},T))}))))),x>0&&S&&(()=>{const E={inaccuracy:"inaccuracies",mistake:"mistakes",blunder:"blunders"},M=`${S.phase} ${E[S.sev.key]}`,T=m?` You also make more errors per game than your opponents (${y}).`:b?` Overall you're the cleaner player (${y} 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)",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"}},M)," are your biggest leak. Focus your training there.",T))})())})()),React.createElement(TacticsConversionInline,{analysis:e}))}const ENDGAME_CLASS_NAMES={pawn:"Pawn endings",rook:"Rook endings",bishop:"Bishop endings",knight:"Knight endings",queen:"Queen endings",queenrook:"Queen-and-rook endings",rookbishop:"Rook & bishop endings",rookknight:"Rook & knight endings",queenminor:"Queen & minor endings",bishopknight:"Two-minor-piece endings",mixed:"Mixed endings"};function EndgameDimension({analysis:e}){const t=useMemo(()=>{if(e.__slim)return e.metrics?.endgameTypes||null;const s=(e.analyzedGames||[]).filter(l=>!l.isQuickMode);if(s.length===0)return null;try{return window.LumiProfile?.computeEndgames?.(s)||null}catch(l){return console.warn("[profile-report] endgame type profile failed:",l?.message||l),null}},[e]),a=window.LumiProfile?.pickWorstEndgame?.((t?.profile||[]).filter(s=>s.positions>0))||null;let r,o,n,c,i;if(e.__slim){const s=e.metrics.endgame;if(!s)return null;({egGames:r,avgEg:o,diff:n,catData:c,nReal:i}=s)}else{const s=(e.analyzedGames||[]).filter(g=>!g.isQuickMode);if(s.length<3||(r=s.map((g,p)=>{const h=g.moveAnalysis||[],S=h.filter(E=>E.isPlayerMove&&E.accuracy!=null).filter(E=>E.gamePhase==="endgame");if(S.length===0)return null;const x=Math.round(S.reduce((E,M)=>E+M.accuracy,0)/S.length*10)/10,f=h.find(E=>E.gamePhase==="endgame"),v=f?g.playerColor==="w"?f.evalBefore:-f.evalBefore:0,y=g.headers?.Result,m=g.playerColor==="w"&&y==="1-0"||g.playerColor==="b"&&y==="0-1",b=y==="1/2-1/2",k=g.playerColor==="w"&&y==="0-1"||g.playerColor==="b"&&y==="1-0";let A="equal";return v>=150?A="advantage":v<=-150&&(A="disadvantage"),{game:p+1,acc:x,category:A,won:m,drew:b,lost:k,entryEval:v,egMoveCount:S.length}}).filter(Boolean),r.length===0))return null;o=Math.round(r.reduce((g,p)=>g+p.acc,0)/r.length*10)/10,n=o-e.avgAccuracy;const l=["advantage","equal","disadvantage"],d={advantage:"With Advantage",equal:"Equal Endgames",disadvantage:"With Disadvantage"},u={advantage:"#5DB67D",equal:"#6B9FD4",disadvantage:"#CF6E6E"};c=l.map(g=>{const p=r.filter(f=>f.category===g);if(p.length===0)return null;const h=p.filter(f=>f.won).length,w=p.filter(f=>f.drew).length,S=p.filter(f=>f.lost).length,x=Math.round(p.reduce((f,v)=>f+v.acc,0)/p.length*10)/10;return{key:g,label:d[g],color:u[g],total:p.length,wins:h,draws:w,losses:S,acc:x}}).filter(Boolean),i=s.length}return React.createElement(DimSectionCard,{id:"dim-endgame",title:"Endgame",analysis:e},React.createElement("div",null,React.createElement("div",{className:"pr-chart-h48"},React.createElement(ResponsiveContainer,{width:"100%",height:"100%"},React.createElement(BarChart,{data:r,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,{cursor:!1,content:s=>React.createElement(ChartTip,{...s,formatter:l=>[`${l}%`,"Endgame Acc."]})}),React.createElement(ReferenceLine,{y:e.avgAccuracy,stroke:"#D4A44B",strokeDasharray:"4 4"}),React.createElement(Bar,{activeBar:{fillOpacity:1,style:{filter:"brightness(1.5) saturate(1.35)"}},dataKey:"acc",radius:[3,3,0,0]},r.map((s,l)=>React.createElement(Cell,{key:l,fill:s.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:"What this measures",body:`How accurately you play once the position simplifies. One bar per analyzed game in which the engine scored at least one of your endgame moves: ${r.length} of ${i}. That counts scored moves, not games that reached an endgame. The Endgames You Reach card below has that number.`}),React.createElement(DimCoach,{title:"Endgame accuracy",body:`Your average endgame accuracy is ${o}%, vs your overall ${e.avgAccuracy}%.`}),React.createElement(DimCoach,{title:"What this means",body:n>=5?"Your endgame is a strength. You play more accurately as positions simplify.":n<=-5?a?`Your endgame lags behind your overall play. Your weakest ending is ${(ENDGAME_CLASS_NAMES[a.cls]||a.cls).toLowerCase()} (${a.accuracy}%), so that is where endgame study will have the most direct impact on your results.`:"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."})),c.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(${c.length}, 1fr)`,gap:12}},c.map(s=>{const l=s.total>0?s.wins/s.total*100:0,d=s.total>0?s.draws/s.total*100:0,u=s.total>0?s.losses/s.total*100:0;return React.createElement("div",{key:s.key,style:{background:"rgba(255,255,255,0.04)",borderRadius:10,padding:"16px 18px"}},React.createElement("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:14}},React.createElement("div",{style:{fontSize:16,fontWeight:700,color:s.color}},s.label),React.createElement("div",{style:{fontSize:14,color:"var(--pr-text-secondary)",textTransform:"uppercase",letterSpacing:"0.06em",fontWeight:600}},s.total," ",s.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"}},s.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}},l>0&&React.createElement("div",{style:{width:`${l}%`,background:"#5DB67D"}}),d>0&&React.createElement("div",{style:{width:`${d}%`,background:"rgba(240,235,224,0.45)"}}),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:s.wins>0?"#5DB67D":"rgba(255,255,255,0.6)"}},React.createElement("span",{style:{fontWeight:700}},s.wins)," won"),React.createElement("span",{style:{color:s.draws>0?"var(--pr-text-primary)":"rgba(255,255,255,0.6)"}},React.createElement("span",{style:{fontWeight:700}},s.draws)," drawn"),React.createElement("span",{style:{color:s.losses>0?"#CF6E6E":"rgba(255,255,255,0.6)"}},React.createElement("span",{style:{fontWeight:700}},s.losses)," lost")))}))),(()=>{const s=(t?.profile||[]).filter(p=>p.positions>0);if(s.length===0)return null;const l=t?.reach,d=Math.max(...s.map(p=>p.positions)),u=window.LumiProfile?.pickWorstEndgame?.(s)||null,g=p=>p==null?"var(--pr-text-secondary)":p>=80?"#5DB67D":p>=65?"#D4A44B":"#CF6E6E";return React.createElement("div",{style:{gridColumn:"1 / -1"}},React.createElement("div",{className:"pr-label pr-mb-3"},"Endgames You Reach"),React.createElement("div",{style:{display:"flex",flexDirection:"column",gap:10}},s.map(p=>React.createElement("div",{key:p.cls,style:{display:"flex",alignItems:"center",gap:12}},React.createElement("div",{style:{flex:"0 0 34%",minWidth:0,fontSize:15,color:"var(--pr-text-primary)",fontWeight:500,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"}},ENDGAME_CLASS_NAMES[p.cls]||p.cls,React.createElement("span",{style:{color:"var(--pr-text-secondary)",fontSize:13,fontWeight:400}}," \xB7 ",p.games," game",p.games!==1?"s":"")),React.createElement("div",{style:{flex:1,height:18,background:"rgba(255,255,255,0.04)",borderRadius:4,overflow:"hidden"}},React.createElement("div",{style:{width:`${p.positions/d*100}%`,height:"100%",background:g(p.accuracy),borderRadius:4,opacity:.85}})),React.createElement("div",{style:{flex:"0 0 96px",textAlign:"right",fontSize:14,color:"var(--pr-text-secondary)",fontVariantNumeric:"tabular-nums"}},p.positions," move",p.positions!==1?"s":""),React.createElement("div",{style:{flex:"0 0 52px",textAlign:"right",fontSize:15,fontWeight:700,color:g(p.accuracy),fontVariantNumeric:"tabular-nums"}},p.accuracy!=null?`${p.accuracy}%`:"\u2014")))),React.createElement("div",{style:{marginTop:16}}),React.createElement(DimCoach,{title:"What this measures",body:`Which kinds of endings you actually get into, by the material left on the board, and how accurately you play each. Bar length is how often you reach it; the number on the right is your accuracy there.${l?` ${l.gamesReached} of ${l.gamesAnalyzed} analyzed games reached an endgame.`:""} A game that simplifies passes through several classes, so it is counted in every row it visits: the per-row game counts overlap and do not add up to the total above.`}),u&&React.createElement(DimCoach,{title:"Your performance",body:`Your weakest ending is ${ENDGAME_CLASS_NAMES[u.cls]||u.cls} at ${u.accuracy}% across ${u.positions} moves in ${u.games} game${u.games!==1?"s":""}. That is the specific technique to study. It is the ending you reach often enough for the accuracy to be real.`}))})())}function ConversionDimension({analysis:e}){let t,a,r,o;if(e.__slim){const i=e.metrics.conversion;if(!i)return null;t=i.rate,a=i.winning,r=i.converted,o=i.granularCap}else{const i=(e.analyzedGames||[]).filter(u=>!u.isQuickMode);if(i.length===0)return null;const s=i.filter(u=>u.maxAdvantage>=150);if(s.length===0)return null;const l=s.filter(u=>{const g=u.headers?.Result;return u.playerColor==="w"&&g==="1-0"||u.playerColor==="b"&&g==="0-1"});a=s.length,r=l.length,t=Math.round(l.length/s.length*100),o=[150,200,300,400].map(u=>{const g=`+${(u/100).toFixed(1)}`,p=i.filter(w=>{if(!w.evalGraph||w.evalGraph.length===0)return!1;const S=w.playerColor==="w"?1:-1;return w.evalGraph.some(x=>x*S>u)}),h=p.filter(w=>{const S=w.headers?.Result;return w.playerColor==="w"&&S==="1-0"||w.playerColor==="b"&&S==="0-1"});return{label:g,total:p.length,converted:h.length,rate:p.length>0?Math.round(h.length/p.length*100):0}}).filter(u=>u.total>0)}const n=t>=65?"#5DB67D":t>=50?"#D4A44B":"#CF6E6E",c=[{name:"Converted",value:r,fill:"#5DB67D"},{name:"Let slip",value:a-r,fill:"#CF6E6E"}];return React.createElement(DimSectionCard,{id:"dim-capitalization",title:"Advantage Capitalization",analysis:e},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:n,lineHeight:1}},t,"%"),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)"}},r,"/",a," games")),React.createElement("div",{style:{flex:1}},React.createElement(ResponsiveContainer,{width:"100%",height:120},React.createElement(BarChart,{data:c,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,{cursor:!1,content:ChartTip}),React.createElement(Bar,{activeBar:{fillOpacity:1,style:{filter:"brightness(1.5) saturate(1.35)"}},dataKey:"value",radius:[0,3,3,0]},c.map((i,s)=>React.createElement(Cell,{key:s,fill:i.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 ${a} games where you had a significant advantage, you won ${r} (${t}%). ${t>=65?"Strong conversion. You close out winning positions effectively.":t>=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."}`})),o.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(${o.length}, 1fr)`,gap:12}},o.map(i=>{const s=i.rate>=65?"#5DB67D":i.rate>=50?"#D4A44B":"#CF6E6E",l=i.total-i.converted,d=i.total>0?i.converted/i.total*100:0,u=i.total>0?l/i.total*100:0;return React.createElement("div",{key:i.label,style:{background:"rgba(255,255,255,0.04)",borderRadius:10,padding:"16px 18px"}},React.createElement("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:14}},React.createElement("div",{style:{fontSize:16,fontWeight:700,color:s}},"Advantage ",i.label),React.createElement("div",{style:{fontSize:14,color:"var(--pr-text-secondary)",textTransform:"uppercase",letterSpacing:"0.06em",fontWeight:600}},i.total," ",i.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"}},i.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}},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:i.converted>0?"#5DB67D":"rgba(255,255,255,0.6)"}},React.createElement("span",{style:{fontWeight:700}},i.converted)," converted"),React.createElement("span",{style:{color:l>0?"#CF6E6E":"rgba(255,255,255,0.6)"}},React.createElement("span",{style:{fontWeight:700}},l)," let slip")))})),o.length>=2&&o[0].rate-o[o.length-1].rate>=10&&React.createElement("div",{style:{fontSize:16,color:"var(--pr-text-primary)",marginTop:12,lineHeight:1.55,fontWeight:500}},"You convert ",o[o.length-1].rate,"% with large advantages (",o[o.length-1].label,") but only ",o[0].rate,"% with small ones (",o[0].label,"). Focus on pressing small edges.")))}function ResourcefulnessDimension({analysis:e}){const t=e.resourcefulness;if(!t||t.total===0)return null;let a;if(e.__slim){const s=e.metrics.resourceGran;if(!s)return null;a=s.granularRes}else{const s=(e.analyzedGames||[]).filter(d=>!d.isQuickMode);if(s.length===0)return null;a=[150,200,300,400].map(d=>{const u=`-${(d/100).toFixed(1)}`,g=s.filter(h=>{if(!h.evalGraph||h.evalGraph.length===0)return!1;const w=h.playerColor==="w"?1:-1;return h.evalGraph.some(S=>S*w<-d)}),p=g.filter(h=>{const w=h.headers?.Result;return w==="1/2-1/2"||h.playerColor==="w"&&w==="1-0"||h.playerColor==="b"&&w==="0-1"});return{label:u,total:g.length,saved:p.length,rate:g.length>0?Math.round(p.length/g.length*100):0}}).filter(d=>d.total>0)}const{total:r,saved:o,rate:n}=t,c=n>=40?"#5DB67D":n>=25?"#D4A44B":"#CF6E6E",i=[{name:"Saved",value:o,fill:"#5DB67D"},{name:"Lost",value:r-o,fill:"#CF6E6E"}];return React.createElement(DimSectionCard,{id:"dim-resourcefulness",title:"Resourcefulness",analysis:e},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:c,lineHeight:1}},n,"%"),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)"}},o,"/",r," games")),React.createElement("div",{style:{flex:1}},React.createElement(ResponsiveContainer,{width:"100%",height:120},React.createElement(BarChart,{data:i,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,{cursor:!1,content:ChartTip}),React.createElement(Bar,{activeBar:{fillOpacity:1,style:{filter:"brightness(1.5) saturate(1.35)"}},dataKey:"value",radius:[0,3,3,0]},i.map((s,l)=>React.createElement(Cell,{key:l,fill:s.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. It measures fighting spirit and defensive skill."}),React.createElement(DimCoach,{title:"Your performance",body:`You were in a difficult position in ${r} games and saved ${o} of them (${n}%). ${n>=40?"Excellent fighting spirit. You rarely surrender lost positions.":n>=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."}`})),a.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(${a.length}, 1fr)`,gap:12}},a.map(s=>{const l=s.rate>=40?"#5DB67D":s.rate>=25?"#D4A44B":"#CF6E6E",d=s.total-s.saved,u=s.total>0?s.saved/s.total*100:0,g=s.total>0?d/s.total*100:0;return React.createElement("div",{key:s.label,style:{background:"rgba(255,255,255,0.04)",borderRadius:10,padding:"16px 18px"}},React.createElement("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:14}},React.createElement("div",{style:{fontSize:16,fontWeight:700,color:l}},"Fell behind ",s.label),React.createElement("div",{style:{fontSize:14,color:"var(--pr-text-secondary)",textTransform:"uppercase",letterSpacing:"0.06em",fontWeight:600}},s.total," ",s.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"}},s.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}},u>0&&React.createElement("div",{style:{width:`${u}%`,background:"#5DB67D"}}),g>0&&React.createElement("div",{style:{width:`${g}%`,background:"#CF6E6E"}})),React.createElement("div",{style:{display:"flex",justifyContent:"space-between",fontSize:14,fontVariantNumeric:"tabular-nums"}},React.createElement("span",{style:{color:s.saved>0?"#5DB67D":"rgba(255,255,255,0.6)"}},React.createElement("span",{style:{fontWeight:700}},s.saved)," saved"),React.createElement("span",{style:{color:d>0?"#CF6E6E":"rgba(255,255,255,0.6)"}},React.createElement("span",{style:{fontWeight:700}},d)," lost")))}))))}function ConsistencyDimension({analysis:e,games:t}){let a,r,o;const n=e.avgAccuracy;if(e.__slim){const i=e.metrics.consistency;if(!i)return null;({accData:a,stdDev:r,nReal:o}=i)}else{const i=(e.analyzedGames||[]).filter(s=>!s.isQuickMode);if(i.length<3)return null;o=i.length,a=i.map((s,l)=>({game:l+1,acc:s.playerAccuracy})),r=Math.round(Math.sqrt(a.reduce((s,l)=>s+(l.acc-n)**2,0)/a.length)*10)/10}const c=e.__slim?null:(e.analyzedGames||[]).filter(i=>!i.isQuickMode);return React.createElement(DimSectionCard,{id:"dim-consistency",title:"Consistency",analysis:e},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,n-30),Math.min(100,n+30)],tick:{fontSize:14,fill:"var(--pr-text-primary)",fontWeight:500},tickFormatter:i=>Math.round(i),width:32}),React.createElement(CartesianGrid,{strokeDasharray:"3 3",vertical:!1}),React.createElement(Tooltip,{cursor:React.createElement(CursorFloorCapture,null),content:i=>React.createElement(ChartTip,{...i,formatter:s=>[`${s}%`,"Accuracy"]})}),React.createElement(ReferenceLine,{y:n,stroke:"#D4A44B",strokeDasharray:"4 4"}),React.createElement(Line,{activeDot:React.createElement(DropDot,null),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: ${r}%. ${r<=5?"Very consistent. You play at a similar level every game.":r<=10?"Moderate variance. Some games are significantly better than others. Watch for tilt and fatigue.":"High variance. Your performance fluctuates a lot. Focus on pre-game routine and staying focused through losses."}`}),React.createElement(DimCoach,{title:"Average accuracy",body:`${n}% across ${o} games.`})),(()=>{const i=e.__slim?e.metrics.consistency.byResult:computeAccuracyByResult(c),s=e.__slim?e.metrics.consistency.byMove:computeAccuracyByMoveNumber(c),l={win:"#5DB67D",draw:"#8A857F",loss:"#CF6E6E"},d={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(u=>{const g=l[u],p=i[u]?.avg,h=i[u]?.count||0;return React.createElement("div",{key:u,style:{background:"rgba(255,255,255,0.04)",borderRadius:10,padding:"16px 18px",opacity:h===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:g}},d[u]),React.createElement("div",{style:{fontSize:14,color:"var(--pr-text-secondary)",textTransform:"uppercase",letterSpacing:"0.06em",fontWeight:600}},h," ",h===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"}},p??"\u2014",p?"%":""),React.createElement("div",{style:{fontSize:15,color:"var(--pr-text-primary)",fontWeight:500}},"accuracy")))}))),s.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:s},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,{cursor:React.createElement(CursorFloorCapture,null),content:u=>React.createElement(ChartTip,{...u,formatter:(g,p,h)=>[`${g}%`,`Move ${h.payload.move} (${h.payload.games} games)`]})}),React.createElement(ReferenceLine,{y:e.avgAccuracy,stroke:"rgba(255,191,0,0.3)",strokeDasharray:"4 4"}),React.createElement(Area,{activeDot:React.createElement(DropDot,null),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 a=Math.round(e.timeoutLosses/Math.max(1,e.losses)*100),r=Math.round(e.timeTrouble/e.total*100);let o,n,c,i,s,l,d,u,g,p,h;if(e.__slim){const f=e.metrics.timeMgmt;if(!f)return null;({hasLongThinkData:o,longThinkOutcome:n,longThinkErrorPct:c,ttAcc:i,comfortAcc:s,accDrop:l,clockBuckets:d,nLongThinks:u,longThinkThreshold:g,nTimeTrouble:p,nComfort:h}=f)}else{const f=(e.analyzedGames||[]).filter(D=>!D.isQuickMode),v=[];f.forEach(D=>{const _=(D.moveAnalysis||[]).filter($=>$.isPlayerMove),B=(D.headers?.TimeControl||"").match(/\+(\d+)/),L=B?parseInt(B[1]):0;for(let $=0;$<_.length;$++){const F=_[$];if(F.clock==null)continue;const N=$>0?_[$-1]:null;if(N&&N.clock!=null){const R=Math.max(0,N.clock-F.clock+L);v.push({...F,timeSpent:R})}}});const y=v.map(D=>D.timeSpent).sort((D,_)=>D-_),m=y.length>0?y[Math.floor(y.length/2)]:10;g=Math.max(m*2,15);const b=v.filter(D=>D.timeSpent>=g);o=b.length>=5,u=b.length;const k=["blunder","mistake","inaccuracy","good","excellent","best"],A={blunder:"#CF6E6E",mistake:"#D4A44B",inaccuracy:"#E8C44B",good:"#8B8B8B",excellent:"#6B9FD4",best:"#5DB67D"},E={blunder:"Blunder",mistake:"Mistake",inaccuracy:"Inaccuracy",good:"Good",excellent:"Excellent",best:"Best"};n=k.map(D=>{const _=b.filter(C=>C.classification===D).length;return{name:E[D],count:_,pct:b.length>0?Math.round(_/b.length*100):0,fill:A[D]}}).filter(D=>D.count>0),c=b.length>0?Math.round(b.filter(D=>["blunder","mistake"].includes(D.classification)).length/b.length*100):0;const M=v.filter(D=>D.clock!=null&&D.clock<30),T=v.filter(D=>D.clock!=null&&D.clock>=60);p=M.length,h=T.length,i=M.length>=3?Math.round(M.reduce((D,_)=>D+_.accuracy,0)/M.length*10)/10:null,s=T.length>=3?Math.round(T.reduce((D,_)=>D+_.accuracy,0)/T.length*10)/10:null,l=i!=null&&s!=null?Math.round((s-i)*10)/10:null,d=[{range:"0-5s",count:t.filter(D=>D.finalClock!==null&&D.finalClock<5).length,color:"#CF6E6E"},{range:"5-15s",count:t.filter(D=>D.finalClock!==null&&D.finalClock>=5&&D.finalClock<15).length,color:"#D4A44B"},{range:"15-30s",count:t.filter(D=>D.finalClock!==null&&D.finalClock>=15&&D.finalClock<30).length,color:"#D4A44B"},{range:"30-60s",count:t.filter(D=>D.finalClock!==null&&D.finalClock>=30&&D.finalClock<60).length,color:"#6B9FD4"},{range:"1-2min",count:t.filter(D=>D.finalClock!==null&&D.finalClock>=60&&D.finalClock<120).length,color:"#5DB67D"},{range:"2min+",count:t.filter(D=>D.finalClock!==null&&D.finalClock>=120).length,color:"#5DB67D"}]}const w=a>=25?"#CF6E6E":a>=12?"#D4A44B":"#5DB67D",S=a>=25?"Clock is the main thing costing you games":a>=12?"Clock costs you some games, but it is fixable":"Strong clock discipline",x=[];return a>=25?x.push(`${a}% of your losses are timeouts (${e.timeoutLosses} of ${e.losses}). The chess part of your game is mostly fine, the clock is not.`):a>=12?x.push(`${a}% of your losses are timeouts (${e.timeoutLosses} of ${e.losses}). Not a crisis, but the leak adds up over a session.`):x.push(`Only ${a}% of your losses are timeouts. You almost always lose on the board, not the clock.`),e.severeTimeTrouble>=5&&x.push(`You finish ${e.severeTimeTrouble} games with under 5 seconds. Bullet-time finishes leave you no margin for error.`),l!=null&&l>8?x.push(`Your accuracy drops ${l} points when low on time, a meaningful pressure leak.`):l!=null&&l>3?x.push(`Accuracy drops ${l} points under pressure, small and manageable.`):l!=null&&x.push(`Accuracy barely changes under pressure (${l} pt drop). You play almost as sharply low on time as when fresh.`),e.timeoutWins>0&&x.push(`On the other side: ${e.timeoutWins} wins came from flagging your opponent.`),React.createElement(DimSectionCard,{id:"dim-time-mgmt",title:"Time Management",analysis:e},React.createElement("div",{style:{gridColumn:"1 / -1",display:"flex",alignItems:"center",gap:16,padding:"16px 18px",background:`${w}14`,border:`1px solid ${w}40`,borderRadius:12}},React.createElement("div",{style:{fontSize:38,fontWeight:800,color:w,lineHeight:1,letterSpacing:"-0.02em",flexShrink:0}},a,"%"),React.createElement("div",null,React.createElement("div",{style:{fontSize:17,fontWeight:700,color:w,marginBottom:2}},S),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:x.join(" ")})),React.createElement("div",{className:"pr-grid-2",style:{gridColumn:"1 / -1"}},React.createElement(StatBox,{label:"Games Lost to Clock",value:e.timeoutLosses,sub:`${a}% of all losses`,color:"#CF6E6E"}),React.createElement(StatBox,{label:"Games in Time Trouble",value:`${r}%`,sub:"finished with <15s left",color:"#D4A44B"}),React.createElement(StatBox,{label:"Bullet-Time Finishes",value:e.severeTimeTrouble,sub:"games ending under 5s",color:"#CF6E6E"}),React.createElement(StatBox,{label:"Wins by Flag",value:e.timeoutWins,sub:"opponent ran out of time",color:"#5DB67D"})),l!=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:s,count:h,sub:"comfort zone"},{stripe:l>5?"#CF6E6E":"#D4A44B",label:"Time trouble (<30s)",acc:i,count:p,sub:"pressure zone"}].map((f,v)=>React.createElement("div",{key:v,style:{background:"rgba(255,255,255,0.04)",borderRadius:10,padding:"16px 18px"}},React.createElement("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:14}},React.createElement("div",{style:{fontSize:16,fontWeight:700,color:f.stripe}},f.label),React.createElement("div",{style:{fontSize:14,color:"var(--pr-text-secondary)",textTransform:"uppercase",letterSpacing:"0.06em",fontWeight:600}},f.count," ",f.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"}},f.acc,"%"),React.createElement("div",{style:{fontSize:14,color:"var(--pr-text-body)"}},f.sub))))),React.createElement("div",{style:{fontSize:16,color:"var(--pr-text-primary)",marginTop:12,lineHeight:1.55,fontWeight:500}},l>10?`Your accuracy drops ${l}% under time pressure, a major leak. Try to keep more time on the clock for critical decisions.`:l>5?`Your accuracy drops ${l}% when low on time. Consider playing faster in the opening to save time for complex positions.`:`Your accuracy only drops ${l}% under time pressure, which is solid clock management.`)),o&&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 ",u," moves where you spent more than ",Math.round(g)," seconds thinking."),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:"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,{cursor:!1,content:f=>React.createElement(ChartTip,{...f,formatter:(v,y,m)=>[`${v}% (${m.payload.count} moves)`,m.payload.name]})}),React.createElement(Bar,{activeBar:{fillOpacity:1,style:{filter:"brightness(1.5) saturate(1.35)"}},dataKey:"pct",radius:[3,3,0,0]},n.map((f,v)=>React.createElement(Cell,{key:v,fill:f.fill})))))),React.createElement("div",{style:{fontSize:16,color:"var(--pr-text-primary)",marginTop:8,lineHeight:1.55,fontWeight:500}},c>=30?`${c}% of your long thinks result in a mistake or blunder. Your calculation may be leading you astray. Practice complex positions to improve decision-making.`:c>=15?`${c}% of long thinks end in a mistake or blunder. Mostly your extra thinking time pays off.`:`Only ${c}% of long thinks end in a mistake or blunder. 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:d},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,{cursor:!1,content:ChartTip}),React.createElement(Bar,{activeBar:{fillOpacity:1,style:{filter:"brightness(1.5) saturate(1.35)"}},dataKey:"count",radius:[4,4,0,0]},d.map((f,v)=>React.createElement(Cell,{key:v,fill:f.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}){let t,a,r,o,n,c;if(e.__slim){const g=e.metrics.colorAsym;if(!g)return null;({whiteAcc:t,blackAcc:a,whiteErrors:r,blackErrors:o,whiteCount:n,blackCount:c}=g)}else{const g=(e.analyzedGames||[]).filter(x=>!x.isQuickMode);if(g.length<4)return null;const p=["inaccuracy","mistake","blunder"],h=g.filter(x=>x.playerColor==="w"),w=g.filter(x=>x.playerColor==="b");if(h.length<2||w.length<2)return null;const S=x=>{let f=0;return x.forEach(v=>v.moveAnalysis.filter(y=>y.isPlayerMove).forEach(y=>{p.includes(y.classification)&&f++})),f};r=(S(h)/h.length).toFixed(1),o=(S(w)/w.length).toFixed(1),t=Math.round(h.reduce((x,f)=>x+f.playerAccuracy,0)/h.length*10)/10,a=Math.round(w.reduce((x,f)=>x+f.playerAccuracy,0)/w.length*10)/10,n=h.length,c=w.length}const i=[{side:"White",acc:t,errors:r,count:n,stripe:"#E8E4E0"},{side:"Black",acc:a,errors:o,count:c,stripe:"#6B9FD4"}],s=Math.abs(t-a),l=t>a?"Black":"White",d=t>a?"White":"Black",u=s<1?`Your accuracy is essentially identical with both colours (${t}% vs ${a}%). That is rare. Most players are 2 to 4 points better with one side. Suggests your opening repertoire is balanced and you adapt well to both colour rhythms.`:s<3?`You're slightly stronger as ${d} (${d==="White"?t:a}% vs ${d==="White"?a:t}%) but the gap is small. Both sides are working; no urgent opening fix needed.`:`Your ${l} play is ${s.toFixed(1)} accuracy points weaker (${d==="White"?t:a}% vs ${d==="White"?a:t}%). The gap is meaningful. Focus opening study on your ${l} 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"}},i.map(g=>React.createElement("div",{key:g.side,style:{background:"rgba(255,255,255,0.04)",borderRadius:10,padding:"16px 18px"}},React.createElement("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",marginBottom:14}},React.createElement("div",{style:{fontSize:16,fontWeight:700,color:g.stripe}},"As ",g.side),React.createElement("div",{style:{fontSize:14,color:"var(--pr-text-secondary)",textTransform:"uppercase",letterSpacing:"0.06em",fontWeight:600}},g.count," ",g.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"}},g.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)"}},g.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. The engine punishes positions you do not know."}),React.createElement(DimCoach,{title:"Your performance",body:u})))}function AccuracyByPieceInsight({analysis:e}){let t;if(e.__slim)t=e.metrics.pieceAcc||[];else{const i=(e.analyzedGames||[]).filter(s=>!s.isQuickMode);if(i.length===0)return null;t=computePieceAccuracy(i)}if(t.length===0)return null;const a=t.reduce((i,s)=>i.accuracy>s.accuracy?i:s),r=t.reduce((i,s)=>i.accuracy<s.accuracy?i:s),o={Pawn:"pawn breaks and structure decisions",Knight:"outpost choice and forking geometry",Bishop:"long-diagonal tactics and good-vs-bad bishop trades",Rook:"open-file timing and endgame technique",Queen:"tactical calculation and avoiding early trades",King:"endgame activity and safety calls"},n=a.accuracy-r.accuracy,c=n<4?`Your accuracy is balanced across pieces (${r.accuracy}-${a.accuracy}%). No single piece is dragging you down, and your decisions carry equal weight whichever piece is moving.`:`Your ${a.name.toLowerCase()} play is ${n.toFixed(1)} points sharper than your ${r.name.toLowerCase()} play (${a.accuracy}% vs ${r.accuracy}%). Your ${r.name.toLowerCase()} moves are where the points are leaking${o[r.name]?`, so work on ${o[r.name]}`:""}.`;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: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,{cursor:!1,content:i=>React.createElement(ChartTip,{...i,formatter:(s,l,d)=>[`${s}% (${d.payload.moves} moves)`,d.payload.name]})}),React.createElement(Bar,{activeBar:{fillOpacity:1,style:{filter:"brightness(1.5) saturate(1.35)"}},dataKey:"accuracy",radius:[0,4,4,0]},t.map((i,s)=>React.createElement(Cell,{key:s,fill:i.color}))))))),React.createElement("div",{className:"pr-grid-2"},React.createElement("div",null,React.createElement("div",{className:"pr-font-bold",style:{color:"#5DB67D",fontSize:15}},"Best Piece"),React.createElement("div",{className:"pr-font-bold",style:{color:"#9ED6B2",fontSize:22,display:"flex",alignItems:"center",gap:8,marginTop:2}},React.createElement("img",{src:pieceIconUrl(a.piece),alt:"",width:36,height:36,style:{display:"block",flexShrink:0}}),a.name," (",a.accuracy,"%)")),React.createElement("div",null,React.createElement("div",{className:"pr-font-bold",style:{color:"#CF6E6E",fontSize:15}},"Weakest Piece"),React.createElement("div",{className:"pr-font-bold",style:{color:"#E3A8A8",fontSize:22,display:"flex",alignItems:"center",gap:8,marginTop:2}},React.createElement("img",{src:pieceIconUrl(r.piece),alt:"",width:36,height:36,style:{display:"block",flexShrink:0}}),r.name," (",r.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. Rook accuracy reflects endgame technique, knight reflects positional vision, and queen reflects tactical calculation."}),React.createElement(DimCoach,{title:"Your performance",body:c})))}function AdditionalInsights({analysis:e,games:t,platform:a}){if(!e||e.isHeuristic)return null;const r=(e.analyzedGames||[]).filter(o=>!o.isQuickMode);return!e.__slim&&r.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,platform:a}),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:a,skipOpening:r=!1}){if(!e||e.isHeuristic)return null;const o=(e.analyzedGames||[]).filter(n=>!n.isQuickMode);return!e.__slim&&o.length===0?null:React.createElement(React.Fragment,null,!r&&React.createElement(OpeningDimension,{analysis:e,games:t}),React.createElement(TacticsDimension,{analysis:e,username:a}),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));
