import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

test("Opening an unsent draft's existing thread leaves unrelated sidebar rows untouched", WEB, async ({t3, app, screen, browser}) => {
  await browser.setViewport({width:1440, height:1100});
  await browser.addInitScript(() => {
    const w = window as any;
    w.rowProbe = { armed: false, counts: {}, changes: {}, reset() { this.counts = {}; this.changes = {}; this.armed = true; } };
    let id = 0;
    w.__REACT_DEVTOOLS_GLOBAL_HOOK__ = {
      supportsFiber: true, renderers: new Map(),
      inject(renderer: any) { this.renderers.set(++id, renderer); return id; },
      onCommitFiberUnmount() {},
      onCommitFiberRoot(_id: any, root: any) {
        const p = w.rowProbe;
        const visit = (f: any) => {
          const name = f.type?.displayName || f.type?.name || '';
          if (p.armed && name === 'SidebarThreadRow' && (f.flags & 1)) {
            const props = f.memoizedProps;
            const title = props.thread?.title || props.title || 'unknown';
            p.counts[title] = (p.counts[title] || 0) + 1;
            p.changes[title] = [...new Set([...(p.changes[title] || []), ...Object.keys(props).filter(k => f.alternate && props[k] !== f.alternate.memoizedProps[k])])];
          }
          if (!f.alternate || f.child !== f.alternate.child) {
            for (let c = f.child; c; c = c.sibling) visit(c);
          }
        };
        visit(root.current);
        if (p.armed) {
          let box = document.getElementById('row-render-probe');
          if (!box) { box = document.createElement('pre'); box.id = 'row-render-probe'; document.body.append(box); }
          box.style.cssText = 'position:fixed;right:24px;top:70px;z-index:99999;background:#101820;color:#e5f4ff;border:2px solid #5ebfff;padding:20px;font:15px/1.7 monospace;max-width:680px;white-space:pre-wrap;pointer-events:none';
          box.textContent = 'MEMOIZED SIDEBAR ROW RENDERS\nDraft → Demo thread 5\n' + Array.from({length:9}, (_,i) => { const t = 'Demo thread '+(i+1); return t+': '+(p.counts[t] || 0)+' renders  '+(p.changes[t] || []).join(', '); }).join('\n');
        }
      },
    };
  });
  const project = await t3.project('demo-project');
  const threads = [];
  for (let i=1; i<=9; i++) threads.push(await t3.thread({project, title:`Demo thread ${i}`, messages:['hello']}));
  await t3.open(threads[0]);
  await screen.getByRole('button', 'Demo thread 3,', {exact: false}).tap();
  await screen.getByRole('button', 'New thread', {exact:false}).first().tap();
  await screen.getByText('demo-project', {exact:true}).last().tap();
  await screen.getByRole('textbox', 'Message', {exact:false}).fill('unsent draft text');
  await browser.keyboard.press('Escape');
  await app.screenshot('unsent-draft');
  await browser.evaluate(() => (window as any).rowProbe.reset());
  await screen.getByRole('button', 'Demo thread 5,', {exact:false}).tap();
  await browser.evaluate(() => new Promise(resolve => setTimeout(() => resolve(true), 1500)));
  await app.screenshot('draft-to-existing-thread-render-counts');
  const counts = await browser.evaluate(() => (window as any).rowProbe.counts);
  expect(counts['Demo thread 5'] > 0).toBe(true);
  expect(Object.entries(counts).filter(([title]) => title !== 'Demo thread 5')).toEqual([]);
});
