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

const logo = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#ef2929"/><circle cx="16" cy="16" r="9" fill="#ffdf00"/></svg>';

test("Later local icons survive earlier unsupported icon links", WEB, async ({ t3, app, browser, screen }) => {
  const definitions = [
    ["html-later-icon", { "index.html": '<html><head><link rel="icon" href="data:image/svg+xml,%3Csvg%3E%3C/svg%3E"><link rel="icon" href="https://cdn.example.com/favicon.ico"><link rel="icon" href="/brand/logo.svg"></head></html>' }],
    ["root-route-later-icon", { "src/routes/__root.tsx": "export const Route = createRootRoute({ head: () => ({ links: [{ rel: 'icon', href: 'https://cdn.example.com/favicon.ico' }, { rel: 'icon', type: 'image/svg+xml', href: '/brand/logo.svg' }] }) });" }],
    ["control-first-icon", { "index.html": '<html><head><link rel="icon" href="/brand/logo.svg"></head></html>' }],
  ] as const;
  const threads = [];
  for (const [name, files] of definitions) {
    const project = await t3.project(name, { ...files, "public/brand/logo.svg": logo });
    threads.push(await t3.thread({ project, title: name, messages: ["first"], model: "multi-turn" }));
  }
  const monograms: string[] = [];
  for (const [index, thread] of threads.entries()) {
    await t3.open(thread);
    await screen.getByText("first fixture turn complete", { exact: false }).waitFor();
    await screen.getByText("Syncing messages...", { exact: true }).waitFor({ state: "hidden" });
    // Wait for the control logo, which is visible in the sidebar on both commits.
    await expect.poll(() => browser.evaluate(() => [...document.images].filter(i => i.complete && i.naturalWidth > 0 && i.getBoundingClientRect().width > 0).length)).toBeGreaterThan(0);
    await app.screenshot(definitions[index]![0]);
    monograms.push(...await browser.evaluate(() => [...document.querySelectorAll('[data-slot="project-monogram"]')].filter(e => ["HI", "RI"].includes(e.textContent ?? "") && e.getBoundingClientRect().width > 0).map(e => e.textContent!)));
  }
  await screen.getByRole("combobox", /^Projects/).tap();
  await app.screenshot("project-picker");
  monograms.push(...await browser.evaluate(() => [...document.querySelectorAll('[data-slot="project-monogram"]')].filter(e => ["HI", "RI"].includes(e.textContent ?? "") && e.getBoundingClientRect().width > 0).map(e => e.textContent!)));
  expect(monograms, "Every reported surface uses the local logo rather than HI / RI monograms").toEqual([]);
});
