'use client'; import {useEffect,useState} from 'react'; import {Activity,CheckCircle2,AlertTriangle,ArrowRight,Clock3,Search,ShieldCheck,Package,ScrollText,Users,Timer} from 'lucide-react'; import type {Attention,Perf} from '@/core/realm-outcomes'; import type {Evidence} from '@/core/realm-insights'; type Recovery={name:string;at:number;status:string;result:string;detail:string;checkedAt:number|null}; type BotResult={name:string;zone:string;grouped:boolean;groupBots:string[];totals:Record}; type Data={collectedAt:number|null;attention:Attention[];outcomes:{at:number|null;startedAt:number|null;windowStart:number;totals:Record;bots:BotResult[];recent:Evidence[]};recoveryResults:Recovery[];performance:{latest:Perf|null;history:{at:number;averageTickMs:number;ticks:number}[]}}; const stamp=(at:number|null)=>at?new Date(at*1000).toLocaleString():'Awaiting observations'; const labels:Record={resumed:'Progress resumed',no_progress:'No progress observed',pending:'Verification pending',unverified:'Could not verify'}; function Metric({label,value,note,icon:Icon=Activity,tone=''}:{label:string;value:string|number;note:string;icon?:typeof Activity;tone?:string}){return
{label}
{value}{note}
} export function RealmDiagnostics({page,onNavigate,initialQuery=''}:{page:string;initialQuery?:string;onNavigate:(page:string,name?:string)=>void}){ const [data,setData]=useState(null),[error,setError]=useState(''),[query,setQuery]=useState(initialQuery),[filter,setFilter]=useState('all'); useEffect(()=>{setQuery(initialQuery);setFilter('all');},[page,initialQuery]); useEffect(()=>{let stop=false;const poll=async()=>{try{const r=await fetch('/api/realm-insights');if(!r.ok)throw new Error('Realm diagnostics unavailable');const d=await r.json() as Data;if(!stop){setData(d);setError('');}}catch{if(!stop)setError('Connection interrupted. Previously loaded readings may be stale.');}};void poll();const timer=setInterval(poll,15000);return()=>{stop=true;clearInterval(timer);};},[]); if(!data)return
{error||'Gathering realm evidence…'}
; const critical=data.attention.filter(a=>a.severity==='critical').length,perf=data.performance.latest,o=data.outcomes; const stale=!data.collectedAt||Date.now()/1000-data.collectedAt>180; const metrics=o.totals,recoveries=data.recoveryResults; const visibleBots=o.bots.filter(b=>(b.name+' '+b.zone).toLowerCase().includes(query.toLowerCase())&&(filter!=='grouped'||b.grouped)); const attempts=recoveries.filter(r=>r.name.toLowerCase().includes(query.toLowerCase())&&(filter==='all'||r.status===filter)); return
EVIDENCE FROM YOUR REALM

{page==='Needs attention'?'A clear view of what needs you.':page==='Gameplay Results'?'Plans become progress.':page==='Recovery Results'?'Did the recovery help?':'Inside the bot engine.'}

{page==='Needs attention'?'Prioritized signals, with a direct path to the details.':page==='Gameplay Results'?'Native quest, loot, and group observations from the last 24 hours.':page==='Recovery Results'?'Native follow-up separates an attempted fix from observed progress.':'Measured execution time, sampled every five minutes.'}

{stale?'Collection delayed':'Collector active'}

Last collection {stamp(data.collectedAt)} · View refreshes every 15 seconds

{error&&
{error}
} {page==='Needs attention'&&<>

Follow-up queue

Critical signals first
{data.attention.length?
{data.attention.map(a=>)}
:

No current attention signals

The monitored checks are clear. This is not proof that every gameplay path is bug-free.

}
{['Gameplay Results','Recovery Results','Bot Performance'].map(p=>)}
} {page==='Gameplay Results'&&<>
Evidence since {stamp(o.startedAt)}. Native counters last collected {stamp(o.at)}. Quest rewards count newly recorded quest IDs; repeated rewards for an already recorded quest may not increase this count. Quest objectives completed: {metrics.quests??0}. Party actions rejected: {metrics.partyFailed??0}. Gaps or a server reload can miss unflushed events.
{visibleBots.map(b=>
{b.name[0]}

{b.name}

{b.zone}
{b.grouped?'Grouped':'Solo / unknown'}
{b.totals.rewarded}Quest rewards
{b.totals.lootItems}Items looted
{b.totals.partyKills}Shared kills
Evidence details

Objectives completed: {b.totals.quests} · Abandoned: {b.totals.abandoned} · Loot collections: {b.totals.lootEvents}

Observed bot companions: {b.groupBots.filter(n=>n!==b.name).join(', ')||'None reported'}

)}
{!visibleBots.length&&
No residents match your filter.
}
Recent evidence ({o.recent.length}){o.recent.map(e=>
{stamp(e.at)}{e.name}

{e.detail} · +{e.amount}

)}
} {page==='Recovery Results'&&<>
{['resumed','no_progress','pending','unverified'].map(status=>r.status===status).length} note="Among the latest 100 retained attempts" tone={status==='resumed'?'good':status==='no_progress'?'warning':''} icon={status==='resumed'?CheckCircle2:Clock3}/>)}

Progress resumed means native movement over five yards, a map change, or a level change was observed within the follow-up window. It does not prove lasting recovery or that the intervention caused it. Three minutes without that evidence is flagged for review. Restarts or unavailable residents may prevent verification.

{attempts.map((r,i)=>

{r.name}

{stamp(r.at)}
{labels[r.status]}

{r.result}

Attempt details

{r.detail}

Checked: {stamp(r.checkedAt)}
)}
{!attempts.length&&

No matching recovery attempts

Results appear after the native guard attempts a recovery. No intervention is forced to populate this view.

}} {page==='Bot Performance'&&<>
{(!perf||Date.now()/1000-perf.at>720)&&
Profiler data is missing or stale. Measurements below are not current.
}

Average full-tick history

Milliseconds · cumulative average
{data.performance.history.slice(-48).map(p=>
x.averageTickMs)))+'%'}}/>)}

{stamp(data.performance.history[0]?.at??null)} — {stamp(perf?.at??null)}. Timers can overlap; they must not be added together or interpreted as CPU utilization.

Most expensive measured operations

Sorted by accumulated time
{perf?.rows.map((r,i)=>)}
OperationCallsMeanMaximumPer full tick
{r.name}{r.category}{Math.round(r.calls).toLocaleString()}{r.averageMs.toFixed(3)} ms{r.maxMs.toFixed(3)} ms{r.perTickMs.toFixed(3)} ms
{!perf?.rows.length&&

Waiting for the first native profiler export.

}
}
; }