/// <reference lib="dom" />
import { expect } from "e2e";
import { readFileSync } from "node:fs";
import { setTimeout as delay } from "node:timers/promises";
import * as Effect from "effect/Effect";
import { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts";
import { T3_HOME } from "../e2e.config.ts";
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";

test("HTTP URLs leave Hebrew prose RTL in collapsed pending questions", WEB, async ({ t3, app, browser }) => {
  await browser.emulateMedia({reducedMotion:"reduce",colorScheme:"light"});
  const project = await t3.project("URL direction");
  await runPromise(Effect.gen(function* () {
    const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
    yield* client["server.updateSettings"]({patch:{}, providerInstanceMutation:{operation:"upsert",instanceId:ProviderInstanceId.make("opencode"),instance:{driver:ProviderDriverKind.make("opencode"),enabled:true,config:{binaryPath:"opencode"}}}});
  }).pipe(Effect.scoped));
  const cases = [
    {label:"lowercase",text:"http://example.org שלום"},
    {label:"uppercase",text:"HTTP://example.org שלום"},
    {label:"autolink",text:"<https://example.org>שלום"},
  ];
  const threads = [];
  for (const item of cases) {
    const prompt = `Call your question tool immediately with exactly one question. The header must be "Question". The question text must be exactly ${JSON.stringify(item.text)}. Options must be "Yes" and "No" with English descriptions. Do not answer the question yourself. Do not use any other tool or write any explanation.`;
    const started = await runPromise(makeState(T3_HOME).cli(["thread","start",project,prompt,"--title",item.label,"--provider","opencode","--model","anthropic/claude-haiku-5-5","--wait","--json"],[2]));
    threads.push({...item,...JSON.parse(started.stdout)});
  }
  const directions = [];
  for (const item of threads) {
    await t3.open({threadId:item.threadId});
    await browser.locator('[data-pending-user-input-toggle="expanded"]').waitFor({timeout:60000});
    await browser.locator('[data-pending-user-input-toggle="expanded"]').click();
    await browser.locator('[data-pending-user-input-toggle="collapsed"]').waitFor();
    await browser.evaluate(async () => {
      await Promise.all(document.getAnimations().filter(a => Number.isFinite(a.effect?.getComputedTiming().endTime)).map(a => a.finished.catch(() => {})));
      return null;
    });
    let previous = await app.screenshot(`${item.label}-settling`);
    let stable = false;
    for (let attempt=0;attempt<6;attempt++) {
      await delay(500);
      const current = await app.screenshot(item.label);
      if (readFileSync(previous).equals(readFileSync(current))) {stable=true;break;}
      previous=current;
    }
    if (!stable) throw new Error(`The ${item.label} banner never settled`);
    await delay(1500);
    directions.push(await browser.evaluate(() => {
      const banner = document.querySelector('[data-pending-user-input-toggle="collapsed"]');
      return [...(banner?.querySelectorAll('span[dir],span.flex-1') ?? [])].map(e=>({text:e.textContent,dir:e.getAttribute('dir')}));
    }));
  }
  for (let i=0;i<cases.length;i++) {
    expect(directions[i]?.find(e=>e.text===cases[i]!.text)?.dir, cases[i]!.label).toBe("rtl");
  }
});
