import { useState } from 'react';
import { flushSync } from 'react-dom';
import { resolveIssueLinkTarget } from '@t3tools/client-runtime/issue-links';
import { useProjects } from '../state/entities';
import { usePrimaryEnvironmentId } from '../state/environments';
import ChatMarkdown from './ChatMarkdown';

const urls = Array.from({length:60}, (_,i)=>i%6===0 ? `https://github.com/perf-example/repo-${i%10}/issues/${i+1}` : `https://docs.example.com/guide/${i}`);
const markdown=urls.map((u,i)=>`[${i%6===0?'Issue':'Documentation'} ${i+1}](${u})`).join(' · ');
const median=(a:number[])=>[...a].sort((a,b)=>a-b)[Math.floor(a.length/2)];
export function IssuePerfEvidence(){
 const all=useProjects(); const environmentId=usePrimaryEnvironmentId();
 const projects=all.filter(p=>p.id.startsWith('perf-project-')).sort((a,b)=>Number(a.id.split('-').at(-1))-Number(b.id.split('-').at(-1)));
 const [tick,setTick]=useState(0); const [output,setOutput]=useState<any>(null);
 const run=async()=>{
  const rows=[]; const refs:any={};
  for(const count of [1,8,40,100]){
   const stable=projects.slice(0,count);
   for(const mode of ['warm','fresh']){
    const batches=[];
    const sweep=(ps:typeof stable)=>urls.map(url=>resolveIssueLinkTarget({url,projects:ps})?.ref??null);
    for(let w=0;w<100;w++)sweep(stable);
    for(let r=0;r<9;r++){
     await Promise.resolve();
     const inputs=Array.from({length:100},()=>mode==='fresh'?stable.map(p=>({...p,repositoryIdentity:p.repositoryIdentity?{...p.repositoryIdentity}:null})):stable);
     const start=performance.now();
     for(const ps of inputs){
      const result=sweep(ps);
      const key=`${count}-${mode}`;
      if(refs[key] && JSON.stringify(refs[key])!==JSON.stringify(result)) throw new Error('References changed');
      refs[key]=result;
     }
     batches.push((performance.now()-start)/100);
    }
    rows.push({projects:count,mode,medianMs:median(batches),minMs:Math.min(...batches),maxMs:Math.max(...batches),batchMedians:batches,resolved:refs[`${count}-${mode}`].filter(Boolean).length});
   }
  }
  const renders=[];
  for(let r=0;r<9;r++){
   await Promise.resolve();
   const samples=[];
   for(let s=0;s<20;s++){
    const start=performance.now(); flushSync(()=>setTick(t=>t+1)); samples.push(performance.now()-start);
   }
   renders.push(median(samples));
  }
  const result={timestamp:new Date().toISOString(),environment:{surface:'T3 web dev client',os:'Linux x86_64',browser:navigator.userAgent,viewport:[innerWidth,innerHeight],theme:'dark'},workload:'60 markdown links: 50 documentation, 10 GitHub issues; 100 synthetic repositories seeded through project API',rows,refs,render:{description:'Actual ChatMarkdown synchronous rerender, 100 projects; 9 batches of 20; text changes by trailing whitespace',medianMs:median(renders),minMs:Math.min(...renders),maxMs:Math.max(...renders),batchMedians:renders}};
  (window as any).issuePerfResult=result; setOutput(result);
 };
 (window as any).runIssuePerf=run;
 return <section style={{position:'fixed',inset:0,zIndex:99999,background:'#111318',color:'#e7e9ee',padding:32,overflow:'auto',fontFamily:'system-ui'}}>
 <h1 style={{fontSize:25}}>Markdown issue link classification</h1><p>{location.port === "6372" ? "Before · cbd1f04bca" : "After · 8af81892aa"}</p>
 <p>T3 Code web · Linux · Chromium · 100 synthetic repository bindings</p>
 <p>60 links per sweep: 50 documentation links and 10 issue links. Same workload on both commits.</p>
 <p>Loaded {projects.length} projects; {projects.filter(p=>p.repositoryIdentity).length} repository identities.</p>
 <button onClick={run} style={{padding:10,border:'1px solid #777'}}>Measure</button>
 {output&&<><table style={{width:'100%',marginTop:20,textAlign:'left',fontVariantNumeric:'tabular-nums'}}><thead><tr>{['Projects','Identity','Median ms','Batch median range ms','Resolved'].map(s=><th key={s}>{s}</th>)}</tr></thead><tbody>{output.rows.map((r:any)=><tr key={r.projects+r.mode}><td>{r.projects}</td><td>{r.mode}</td><td>{r.medianMs.toFixed(3)}</td><td>{r.minMs.toFixed(3)}–{r.maxMs.toFixed(3)}</td><td>{r.resolved}/60</td></tr>)}</tbody></table><p>Resolver: 9 batches × 100 sweeps; 100 warmup sweeps. Each batch times 100 sweeps together; fresh identities cloned before each timed batch.</p><p>Actual ChatMarkdown rerender (100 projects): median {output.render.medianMs.toFixed(3)} ms, batch median range {output.render.minMs.toFixed(3)}–{output.render.maxMs.toFixed(3)} ms (9 × 20 renders).</p></>}
 <div style={{marginTop:20,borderTop:'1px solid #444',paddingTop:14}}><ChatMarkdown text={markdown+' '.repeat(tick%2+1)} cwd={undefined} environmentId={environmentId??undefined}/></div>
 </section>
}
