/// <reference lib="dom" />
import { expect } from "e2e";

import { test, WEB } from "./t3.ts";

const SEARCH_KEPT = "a".repeat(198);
const AUTHOR_KEPT = "b".repeat(198);
const LABEL_KEPT = "c".repeat(198);
const SAVED_KEPT = "d".repeat(198);
// A flag's two regional indicators straddle unit 200, where Pull Requests filters are bounded.
const FLAG_SEARCH = `${SEARCH_KEPT}🇺🇸 rest`;

test(
  "Long Pull Requests URL and saved filters keep a flag intact",
  WEB,
  async ({ t3, app, browser, screen }) => {
    await t3.project("demo");
    const showSearchEnd = () =>
      browser.evaluate(() => {
        const input = document.querySelector<HTMLInputElement>('[role="searchbox"]')!;
        input.scrollLeft = input.scrollWidth;
        return null;
      });

    await t3.open(
      `/pull-requests?${new URLSearchParams({
        q: FLAG_SEARCH,
        author: `${AUTHOR_KEPT}🇺🇸`,
        labels: `${LABEL_KEPT}🇺🇸`,
      })}`,
    );
    const searchbox = screen.getByRole("searchbox", "Search pull requests");
    await searchbox.waitFor({ timeout: 60_000 });
    await showSearchEnd();
    await app.screenshot("pull-requests-search-flag");
    await expect(searchbox).toHaveValue(SEARCH_KEPT);

    await screen.getByRole("button", /^Filters/).tap();
    await expect(screen.getByRole("menuitem", /^Author/)).toHaveText(`Author ${AUTHOR_KEPT}`);
    await screen.getByRole("menuitem", /^Labels/).hover();
    await expect(browser.locator('[role="menuitemcheckbox"][aria-checked="true"]')).toHaveText(
      LABEL_KEPT,
    );
    await browser.keyboard.press("Escape");
    await browser.keyboard.press("Escape");

    // Writing a long search saves t3.pullRequests.preferences through the same grapheme cap.
    await searchbox.fill(`${SAVED_KEPT}🇺🇸 rest`);
    const saved = await browser.evaluate(() =>
      JSON.parse(window.localStorage.getItem("t3.pullRequests.preferences") ?? "null"),
    );
    expect(saved).toMatchObject({
      q: SAVED_KEPT,
      author: AUTHOR_KEPT,
      labels: [LABEL_KEPT],
    });

    await t3.open();
    await screen.getByRole("button", "Pull requests").tap();
    await searchbox.waitFor({ timeout: 60_000 });
    await expect(searchbox).toHaveValue(SAVED_KEPT);
  },
);
