import { vi, it, expect } from "vite-plus/test";
import { commands } from "vite-plus/test/browser";
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
import "~/index.css";
const state = vi.hoisted(() => ({ projections: {} as Record<string, any>, environments: {} as Record<string, any>, parents: {} as Record<string, any>, providers: new Map() }));
vi.mock(import("../../state/query"), async original => ({ ...(await original()), useEnvironmentQuery: (() => ({data: {}, isSuccess: true, isPending: false})) as never }));
vi.mock(import("@effect/atom-react"), async original => ({ ...(await original()), useAtomValue: (() => false) as never }));
vi.mock(import("../../state/entities"), () => ({
 useQuietThreadShell: ((ref: any) => state.parents[ref?.threadId] ?? null) as never,
 useThreadProjection: ((ref: any) => ref ? {projection: state.projections[ref.threadId]} : null) as never,
 useThreadRelationshipShells: ((env: any) => Object.values(state.projections).filter((p:any) => p.thread.id === env?.threadId).map((p:any) => p.thread)) as never,
 useProjects: (()=>[]) as never, useHiddenThreadKeys: (()=>new Set()) as never, useAnyEnvironmentHiding: (()=>false) as never,
}));
vi.mock(import("../../state/environments"), () => ({useEnvironment: ((id:string) => state.environments[id] ?? null) as never, useEnvironmentProviders: (()=>state.providers) as never}));
vi.mock(import("../../lib/archivedThreadsState"), () => ({useArchivedThreadSnapshots: (()=>({snapshots:[]})) as never}));
vi.mock(import("../../state/use-atom-command"), () => ({useAtomCommand: (()=>async()=>undefined) as never}));
import { render } from "../../../test/render";
import { makeThreadProjectionFixture } from "../../test-fixtures";
import { ThreadRelationshipsPanel } from "./ThreadRelationshipsControl";
const longTitle="Audit relationship labels across the synthetic staging workspace";
const longLabel="QA Station with an intentionally very long synthetic environment name";
const unbrokenTitle="InvestigateSyntheticRemoteRelationshipLayoutAcrossEnvironments";
const unbrokenLabel="SyntheticEnvironmentWithAnIntentionallyVeryLongUnbrokenMachineLabel";
function projection(id:string) { const p:any=makeThreadProjectionFixture(); p.thread={...p.thread,id,title:id,modelSelection:{instanceId:"synthetic-provider",model:"synthetic"},providerInstanceId:"synthetic-provider"}; return p; }
function remote(id:string,title:string,label:string,status:string,known=true) {
 const env="env-"+id;
 if(known) state.environments[env]={id:env,label};
 if(known) state.providers.set(env,[{instanceId:"synthetic-provider",driver:"codex",displayName:"Synthetic provider",models:[],available:true}]);
 return {id,threadId:"active",runId:null,parentNodeId:null,origin:"app_owned",createdBy:"agent",driver:"codex",providerInstanceId:"synthetic-provider",providerThreadId:null,childThreadId:null,nativeTaskRef:null,prompt:"Synthetic evidence",title,model:null,status,result:null,startedAt:null,completedAt:null,updatedAt:makeThreadProjectionFixture().thread.updatedAt,remoteChild:{environmentId:env,threadId:"child-"+id,label}};
}
it("captures scoped synthetic evidence", async()=>{
 state.projections={}; state.environments={}; state.parents={}; state.providers=new Map();
 state.projections.active=projection("active");
 state.projections.active.subagents=[remote("R1","Scan","QA","pending"),remote("R2",longTitle,"QA","waiting"),remote("R3","Scan",longLabel,"running"),remote("R4",unbrokenTitle,unbrokenLabel,"running",false)];
 state.projections.previous=projection("previous");
 state.projections.previous.subagents=["completed","failed","cancelled","interrupted","idle"].map((status,i)=>remote("R5-"+status,i%2?unbrokenTitle:longTitle,i%2?unbrokenLabel:longLabel,status));
 const scenes=[{id:"active",label:"R1–R4 · active remote agents"},{id:"previous",label:"R5 · all five terminal statuses"}];
 for(const id of ["D1","D3","D4","D5"]) {
  const p=projection(id), env="parent-env-"+id, parent="parent-"+id;
  p.thread.delegatedFrom={environmentId:env,threadId:parent,title:id==="D5"?longTitle:"Old synthetic snapshot title"};
  p.thread.linkOrigin={label:id==="D5"?longLabel:"Old alias"};
  if(id!=="D5") {state.environments[env]={id:env,label:id==="D1"?"QA":longLabel};state.parents[parent]={...p.thread,id:parent,title:id==="D4"?longTitle:"Review"};}
  state.projections[id]=p;scenes.push({id,label:id+" · "+(id==="D5"?"unavailable parent":id==="D4"?"long live title + label":id==="D3"?"short live title + long label":"fit baseline / live label wins")});
 }
 using _clock=vi.spyOn(Date,"now").mockReturnValue(Date.parse("2026-01-01T12:00:00Z"));
 await using screen=await render(<main id="evidence-root"><header><h1>Component harness — synthetic data</h1><p id="coordinate">Lineage relationships · production 280px cards</p><p id="step">Resting rows · Previous agents expanded</p></header><div className="evidence-grid">{scenes.map(scene=><article data-fixture={scene.id} key={scene.id}><h2>{scene.label}</h2><div data-thread-details-card className="dropdown-glass isolate contain-paint overflow-hidden rounded-2xl" style={{width:280}}><ThreadRelationshipsPanel environmentId={EnvironmentId.make("synthetic")} threadId={ThreadId.make(scene.id)} showLineage showSideChats={false}/></div></article>)}</div><style>{`html,body {margin:0; min-height:100%;} body {background:var(--background);color:var(--foreground);} #evidence-root{padding:24px;font-family:var(--font-sans); min-height:100vh;} header{margin-bottom:24px;} h1{font-size:20px;font-weight:600;line-height:28px;} header p{font-size:13px;color:var(--muted-foreground);line-height:22px;} #step{min-height:44px;max-width:800px;color:var(--foreground);} .evidence-grid{display:grid;grid-template-columns:repeat(3,280px);gap:32px 28px;align-items:start;} article h2{font-size:12px;font-weight:500;line-height:18px;margin-bottom:8px;max-width:280px;} @media(max-width:600px){#evidence-root{padding:20px}.evidence-grid{grid-template-columns:280px;gap:24px;}}`}</style></main>);
 await screen.getByRole("button",{name:/Previous agents/}).click();
 await commands.captureEvidence();
 expect(document.querySelectorAll('[data-fixture]')).toHaveLength(6);
});
