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

test("Every font is reachable after wheel and keyboard scrolling in a short window", WEB, async ({ t3, app, screen, browser }) => {
  await browser.setViewport({ width: 1000, height: 520 });
  await t3.project("Font picker demo");
  await t3.open("/settings/appearance");
  await screen.getByRole("combobox", "Interface font family").tap();
  const box = await browser.evaluate(() => {
    const r = document.querySelector('[role="listbox"]')!.getBoundingClientRect();
    return { x: r.x + r.width / 2, y: r.y + Math.min(r.height / 2, 80) };
  });
  await browser.mouse.move(box.x, box.y);
  await browser.mouse.wheel(0, 4000);
  await browser.evaluate(() => new Promise(resolve => setTimeout(() => resolve(null), 500)));
  await app.screenshot("wheel-bottom");
  const bottom = await browser.evaluate(() => {
    const rows = [...document.querySelectorAll('[role="option"]')];
    const row = rows.find(e => e.textContent?.includes("Z003"));
    if (!row) return false;
    let r = row.getBoundingClientRect();
    for (let p = row.parentElement; p; p = p.parentElement) {
      if (/(hidden|auto|scroll)/.test(getComputedStyle(p).overflowY)) {
        const b = p.getBoundingClientRect();
        if (r.top < b.top || r.bottom > b.bottom + 1) return false;
      }
    }
    return r.top >= 0 && r.bottom <= innerHeight;
  });
  await browser.mouse.wheel(0, -4000);
  await browser.evaluate(() => new Promise(resolve => setTimeout(() => resolve(null), 500)));
  await browser.keyboard.press("End");
  await browser.evaluate(() => new Promise(resolve => setTimeout(() => resolve(null), 500)));
  await app.screenshot("keyboard-end");
  await browser.mouse.wheel(0, -4000);
  await browser.evaluate(() => new Promise(resolve => setTimeout(() => resolve(null), 500)));
  await app.screenshot("wheel-top-after-end");
  const top = await browser.evaluate(() => {
    const row = [...document.querySelectorAll('[role="option"]')].find(e => e.textContent?.includes("default"));
    if (!row) return false;
    const r = row.getBoundingClientRect();
    for (let p = row.parentElement; p; p = p.parentElement) {
      if (/(hidden|auto|scroll)/.test(getComputedStyle(p).overflowY)) {
        const b = p.getBoundingClientRect();
        if (r.top < b.top || r.bottom > b.bottom + 1) return false;
      }
    }
    return r.top >= 0 && r.bottom <= innerHeight;
  });
  await expect({ lastFontReachable: bottom, defaultReachableAfterEnd: top }).toEqual({ lastFontReachable: true, defaultReachableAfterEnd: true });
});
