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

const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="12" fill="#e52432"/><path d="M12 22h40L32 55z" fill="#ffda35"/><circle cx="32" cy="18" r="10" fill="#ffda35"/></svg>`;
const files = (name: string) => ({
  "src/routes/__root.tsx": `export const Route = createRootRoute({ head: () => ({ links: [{ rel: "icon", href: "/brand/${name}.svg#mark" }] }) });\n`,
  [`public/brand/${name}.svg`]: svg,
});

test("A route metadata favicon path containing an apostrophe displays its icon", WEB, async ({ t3, app, screen, browser }) => {
  const quoted = await t3.project("Chef's Hat", files("chef's-hat"));
  const control = await t3.project("Chefs Hat", files("chefs-hat"));
  const quotedThread = await t3.thread({ project: quoted, title: "Apostrophe favicon", messages: ["first"] });
  const controlThread = await t3.thread({ project: control, title: "Control favicon", messages: ["first"] });
  await t3.open(controlThread);
  await screen.getByText("first fixture turn complete", { exact: false }).waitFor();
  await t3.open(quotedThread);
  await screen.getByText("first fixture turn complete", { exact: false }).waitFor();
  await app.screenshot("apostrophe-thread-header");
  await screen.getByRole("combobox", "Projects", { exact: true }).tap();
  await screen.getByRole("option", /^Chefs Hat/).waitFor();
  try {
    await expect.poll(() => browser.evaluate(() => {
      const row = Array.from(document.querySelectorAll('[role="option"]')).find((el) => el.textContent?.includes("Chef's Hat"));
      return !!row && Array.from(row.querySelectorAll('img')).some((img) => img.complete && img.naturalWidth > 0 && getComputedStyle(img).display !== "none");
    }), { message: "Chef's Hat displays its declared SVG favicon in the Projects picker" }).toBe(true);
  } finally {
    await app.screenshot("project-picker-favicons");
  }
});
