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

const favicon = Uint8Array.from(Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAAn0lEQVR4nO3Q0QmAMBAFwfRfk2XYjzZxYQzuwf4mj1nrup9fxwfo+AAdH6DjA3R8gI4P0PEBOj5Axwfo+AAdH6CbekheAAEEEEAAAQTwbYCpf8YLIIAAAggggAAC2A0wcQEEEEAAAQQQwJkAW8YHEEAAAQQQQAABBBBAAAEEEEAAFODY+AAdH6DjA3R8gI4P0PEBOj5Axwfo+AAdH4B7ASsWjn2lNrt/AAAAAElFTkSuQmCC", "base64"));
const flutter = {
  "pubspec.yaml": "name: flutter_fixture\ndependencies:\n  flutter:\n    sdk: flutter\n",
  "lib/main.dart": "void main() {}\n",
  "web/favicon.png": favicon,
};

test("Flutter favicon fallback preserves source-declared icons", WEB, async ({ t3, app, browser, screen }) => {
  await t3.project("Flutter only", flutter);
  await t3.project("Flutter with source", {
    ...flutter,
    "index.html": '<html><head><link rel="icon" href="/brand.svg"></head></html>',
    "brand.svg": '<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64"><rect width="64" height="64" rx="12" fill="#e53935"/><path d="M18 16h18c16 0 16 20 0 20H26v13h-8zm8 8v5h10c5 0 5-5 0-5z" fill="white"/></svg>',
  });
  await t3.open("/settings/projects");
  await screen.getByRole("button", "Flutter with source", { exact: false }).waitFor({ state: "visible" });
  // Redact fixture workspace paths; only the icon pixels are under test.
  await browser.evaluate(() => {
    const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
    for (let node = walker.nextNode(); node; node = walker.nextNode()) {
      if (node.textContent?.includes("/workspaces/w-")) {
        node.textContent = node.textContent.includes("Flutter with source") ? "/demo/flutter-with-source" : "/demo/flutter-only";
      }
    }
  });
  const pixel = (title: string) => browser.evaluate((name) => {
    const row = Array.from(document.querySelectorAll("button")).find(b => b.querySelector("span.block.truncate.text-sm")?.textContent?.trim() === name);
    const image = row?.querySelector("img:not(.hidden)");
    if (!(image instanceof HTMLImageElement) || !image.complete || !image.naturalWidth) return null;
    const canvas = document.createElement("canvas");
    canvas.width = canvas.height = 64;
    const context = canvas.getContext("2d")!;
    context.drawImage(image, 0, 0, 64, 64);
    return Array.from(context.getImageData(10, 32, 1, 1).data);
  }, title);
  try {
    await expect.poll(() => pixel("Flutter with source"), { message: "The source-declared red brand icon keeps priority" }).toEqual([229, 57, 53, 255]);
    await expect.poll(() => pixel("Flutter only"), { message: "The Flutter-only project displays its cyan web/favicon.png" }).toEqual([0, 188, 212, 255]);
  } finally {
    await app.screenshot("flutter-project-icons");
  }
});
