import { setTimeout as delay } from "node:timers/promises";
import { spawnSync } from "node:child_process";
import { expect } from "e2e";
import { IOS, test } from "./t3-mobile.ts";

test("Searching finds an unhidden legacy model and clearing collapses it", IOS, async ({ t3, app, screen }) => {
  const capture = async (label: string) => {
    for (let attempt = 0; attempt < 8; attempt++) {
      const first = await app.screenshot(`${label}-settling`);
      await delay(500);
      const second = await app.screenshot(label);
      const compared = spawnSync("compare", ["-metric", "AE", first, second, "null:"], { encoding: "utf8" });
      if (compared.status === 0) return;
    }
    throw new Error("Screenshots did not stabilize");
  };
  const project = await t3.project("Model search demo");
  await t3.thread({ project, title: "Model search", messages: ["first"] });
  await t3.open();
  await screen.getByText("Model search", { exact: false }).first().tap();
  await screen.getByRole("button", "Model and reasoning settings", { exact: false }).tap();
  const search = screen.getByPlaceholder("Find a model");
  await search.fill("Opus 4.8");
  await capture("legacy-model-search");
  await expect(screen.getByRole("radio", "Claude Opus 4.8")).toBeVisible();
  await screen.getByRole("button", "Clear text").tap();
  await capture("cleared-search");
  await expect(screen.getByRole("radio", "Claude Opus 4.8")).not.toBeVisible();
  await search.fill("   ");
  await capture("spaces-search");
  await expect(screen.getByRole("radio", "Claude Opus 4.8")).not.toBeVisible();
});
