/// <reference lib="dom" />
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

function catalog() {
  const lines = ['{', '  "catalog": "Synthetic tool catalog",', '  "version": 1,', '  "tools": ['];
  for (let i = 0; i < 300; i++) {
    const words = Array.from({ length: 60 + (i % 81) }, (_, n) => ['Inspect', 'synthetic', 'workspace', 'records', 'and', 'return', 'structured', 'results'][n % 8]).join(' ');
    lines.push('    {', `      "name": "tool_${i}",`, `      "description": "${words}",`, '      "input": {', '        "type": "object",', '        "properties": {', '          "limit": {', '            "maximum": 100,', '            "type": "integer"', '          }', '        }', '      },', '      "enabled": true', i === 299 ? '    }' : '    },');
  }
  lines.push('  ]', '}');
  // Keep the reported match positions while retaining valid JSON.
  for (const line of [3512, 3792, 4072]) lines[line - 1] = '            "maximum": 25,';
  return lines.join('\n');
}

test('File find reveals the third match below thousands of wrapped lines', WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project('wrap-proof', { 'tool-catalog.json': catalog() });
  const thread = await t3.thread({ project, title: 'File find wrap proof', messages: ['first'] });
  await t3.open(thread);
  await screen.getByText('first fixture turn complete', { exact: false }).waitFor();
  await screen.getByRole('button', 'Toggle right panel').tap();
  await screen.getByText('Files', { exact: true }).tap();
  await browser.keyboard.press('Control+p');
  await screen.getByPlaceholder('Search files…').fill('tool-catalog.json');
  await screen.getByRole('option', 'tool-catalog.json', { exact: false }).tap();
  await screen.getByRole('button', 'Disable word wrap', { exact: true }).waitFor();
  await browser.locator('[data-line="1"]').waitFor({ timeout: 120_000 });
  await browser.locator('[data-line="1"]').tap();
  await browser.keyboard.press('Control+f');
  await browser.keyboard.type('maximum": 25');
  await browser.keyboard.press('Enter');
  await browser.keyboard.press('Enter');
  const visible = () => browser.evaluate(() => {
    const viewport = document.querySelector('.file-preview-virtualizer')!.getBoundingClientRect();
    return [...document.querySelectorAll('*')].flatMap(h => h.shadowRoot ? [...h.shadowRoot.querySelectorAll<HTMLElement>('[data-line]')] : []).filter(row => {
      const r = row.getBoundingClientRect();
      return r.height > 0 && r.top >= viewport.top && r.bottom <= viewport.bottom;
    }).map(row => Number(row.getAttribute('data-line')));
  });
  try {
    await expect.poll(visible).toContain(4072);
  } finally {
    await app.screenshot('third-wrapped-find-match');
  }
});
