import { expect } from "e2e";
import { rpcClient, runPromise, test, WEB } from "./t3.ts";
import { CommandId, MessageId, ThreadId } from "@t3tools/contracts";
import * as Effect from "effect/Effect";
import { T3_HOME } from "../e2e.config.ts";

test("User HTML find respects paragraph, tight list and recovered list line breaks", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Scenario");
  const cases = [
    { label: "paragraph", text: 'Fix <Button\nvariant="outline"> and <Button variant="ghost">', query: '<Button variant', expected: '1/1' },
    { label: "tight-list", text: '- Fix <Button\n  variant="outline"> click\n- Also <Button variant="ghost">', query: '<Button variant', expected: '1/1' },
    { label: "recovered-list", text: '- <div>\n    hello\n  </div>\n\n  <!-- next -->', query: '<div>   hello', expected: '0/0' },
    { label: "plain-control", text: 'Control: Fix Button\nvariant outline and Button variant ghost', query: 'Button variant', expected: '1/1' },
  ];
  const threads = [];
  for (const item of cases) threads.push(await t3.thread({ project, title: item.label, messages: ['Start'] }));
  const actual = [];
  for (const [index, item] of cases.entries()) {
    await t3.open(threads[index]);
    await screen.getByText('first fixture turn complete').waitFor();
    const composer = screen.getByRole('textbox');
    if (item.label.includes('list')) {
      await runPromise(Effect.gen(function* () {
        const client = yield* rpcClient(T3_HOME, app.baseUrl ?? '');
        yield* client['orchestration.dispatchCommand']({
          type: 'message.dispatch',
          commandId: CommandId.make('scenario:' + item.label),
          messageId: MessageId.make('scenario:' + item.label),
          threadId: ThreadId.make(threads[index].threadId),
          createdBy: 'user', creationSource: 'web',
          text: item.text, attachments: [],
          dispatchMode: { type: 'start_immediately' },
        });
      }).pipe(Effect.scoped));
    } else {
      const [first, ...lines] = item.text.split('\n');
      await composer.fill(first);
      for (const line of lines) {
        await composer.press('Shift+Enter');
        if (line) await composer.pressSequentially(line);
      }
    }
    if (!item.label.includes('list')) await composer.press('Enter');
    await screen.getByText('second fixture turn complete').waitFor();
    await browser.keyboard.press('Control+f');
    const find = screen.getByRole('searchbox', 'Find in thread');
    await find.fill(item.query);
    const search = screen.getByRole('search', 'Find in thread');
    await search.getByText(/\d+\/\d+/, { exact: true }).last().waitFor();
    await app.screenshot(item.label + '-first');
    actual.push(await browser.locator('[role=search][aria-label="Find in thread"] span[aria-hidden]').textContent());
    if (item.label !== 'recovered-list') {
      await screen.getByRole('button', 'Next match', { exact: true }).tap();
      await app.screenshot(item.label + '-next');
    } else {
      await find.fill('hello');
      await search.getByText(/\d+\/\d+/, { exact: true }).last().waitFor();
      await app.screenshot('recovered-list-visible-word');
    }
    await screen.getByRole('button', 'Close find').tap();
  }
  console.log('FIND COUNTERS', actual);
  expect(actual).toEqual(cases.map(item => item.expected));
});
