import { writeFile, unlink } from "node:fs/promises";
import { expect } from "e2e";
import { test, WEB } from "./t3.ts";

const icon = '<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64"><rect width="64" height="64" rx="12" fill="#16a34a"/><path d="M14 32l12 12 24-26" fill="none" stroke="white" stroke-width="8"/></svg>';

test("Reselecting a restored repository icon displays it immediately", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Icon Demo", { "project-icon.svg": icon });
  await t3.open();
  await screen.getByRole("button", "Add project").waitFor({ state: "visible" });
  await app.open("/settings/projects");
  await screen.getByRole("button", "Project scope: All projects").tap();
  await screen.getByText("Icon Demo", { exact: true }).last().tap();
  const choose = screen.getByRole("button", "Choose a project icon file");
  const pick = async () => {
    await choose.tap();
    await screen.getByRole("combobox", "Search image files…").fill("project-icon");
    await browser.locator('[role="option"]').filter({ hasText: "project-icon.svg" }).first().tap();
    await screen.getByRole("dialog", "Choose project icon").waitFor({ state: "hidden" });
    await choose.waitFor({ state: "visible" });
  };
  await pick();
  await unlink(`${project}/project-icon.svg`);
  await browser.reload();
  await choose.waitFor({ state: "visible" });
  await browser.locator('div:has(> button[aria-label="Choose a project icon file"]) svg text').waitFor({ state: "visible" });
  await app.screenshot("missing-icon");
  await writeFile(`${project}/project-icon.svg`, icon);
  await pick();
  await app.screenshot("reselected-icon");
  const rowIcon = browser.locator('div:has(> button[aria-label="Choose a project icon file"]) img').last();
  await expect(rowIcon).toBeVisible();
  await app.screenshot("restored-icon");
});
