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

const NAME = "Catppuccin Mocha High Contrast Accessible Themes";
const STEM = "Catppuccin Mocha High Contrast Accessible Them";
const palettes = [["Classic", "#1e1e2e", "#cba6f7"], ["Violet", "#25203b", "#f5c2e7"], ["Evergreen", "#152a26", "#a6e3a1"]];

test("Distinct long-named palettes and a reserved numbered peer import separately", WEB, async ({ t3, app, screen, browser }) => {
  await t3.project("Theme import demo");
  await browser.setViewport({width: 1600, height: 1000});
  await t3.open("/settings/appearance");
  const results: Array<Array<{id: string; label: string; colors: {canvas: string}}>> = [];
  for (const reserved of [false, true]) {
    if (reserved) {
      await browser.evaluate(() => localStorage.removeItem("t3code:themes:v1"));
      await app.open("/settings/appearance");
    }
    await screen.getByRole("button", "Add theme", {exact: true}).tap();
    const files = palettes.map(([variant, background, focus], index) => ({
      filename: `${NAME} ${variant}.json`,
      content: JSON.stringify({name: reserved && index === 2 ? `${STEM} 2` : NAME, type: "dark", colors: {"editor.foreground": "#cdd6f4", "editor.background": background, "focusBorder": focus}}),
    }));
    await browser.evaluate((files) => {
      const transfer = new DataTransfer();
      for (const file of files) transfer.items.add(new File([file.content], file.filename, {type: "application/json"}));
      const input = document.querySelector<HTMLInputElement>('input[type="file"][multiple]')!;
      input.files = transfer.files;
      input.dispatchEvent(new Event("change", {bubbles: true}));
    }, files);
    // Let the import finish and the toast leave before recording the settled library.
    await browser.evaluate(() => new Promise<void>(resolve => setTimeout(resolve, 7000)));
    await app.screenshot(reserved ? "reserved-peer-import" : "three-palettes-imported");
    const themes = await browser.evaluate(() => JSON.parse(localStorage.getItem("t3code:themes:v1") ?? "[]"));
    results.push(themes);
    const conflicts = await browser.evaluate(() => document.body.textContent?.includes("Already installed") ?? false);
    if (conflicts) await screen.getByRole("button", "Cancel", {exact: true}).tap();
    for (let index = 0; index < themes.length; index++) {
      const theme = themes[index];
      await screen.getByRole("button", `Edit ${theme.label}`, {exact: true}).tap();
      await screen.getByRole("dialog", "Edit theme", {exact: true}).waitFor({state: "visible"});
      // Enlarge the actual resizable editor so the complete display name is visible.
      const rect = await browser.evaluate(() => {
        const r = document.querySelector('[data-theme-editor-panel]')!.getBoundingClientRect();
        return {x: r.x, y: r.y, width: r.width, height: r.height};
      });
      await browser.mouse.move(rect.x + 100, rect.y + 16);
      await browser.mouse.down();
      await browser.mouse.move(200, 96);
      await browser.mouse.up();
      const corner = await browser.evaluate(() => {
        const r = document.querySelector('[data-theme-editor-panel]')!.getBoundingClientRect();
        return {x: r.right - 5, y: r.bottom - 5};
      });
      await browser.mouse.move(corner.x, corner.y);
      await browser.mouse.down();
      await browser.mouse.move(1450, corner.y);
      await browser.mouse.up();
      await browser.evaluate(() => new Promise<void>(resolve => setTimeout(resolve, 600)));
      await app.screenshot(`${reserved ? "reserved" : "distinct"}-name-${index + 1}`);
      await screen.getByRole("button", "Close the theme editor", {exact: true}).tap();
    }
  }
  expect(results[0].map(t => t.label)).toEqual([NAME, `${STEM} 2`, `${STEM} 3`]);
  expect(new Set(results[0].map(t => t.id)).size).toBe(3);
  expect(results[1].map(t => t.label)).toEqual([NAME, `${STEM} 3`, `${STEM} 2`]);
  expect(results[1].find(t => t.label === `${STEM} 2`)?.colors.canvas).toBe("oklch(0.26585 0.02822 180.477)");
});
