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

test("Touch tablet: dismissing nested composer menus keeps the editor unfocused", WEB, async ({ t3, app, screen, browser }) => {
  const project = await t3.project("Tablet keyboard demo");
  const first = await t3.thread({ project, title: "First task", messages: ["Hello"] });
  await t3.thread({ project, title: "Second task", messages: ["Hello"] });
  await t3.open(first);
  await screen.getByTestId("composer-editor").waitFor({ state: "visible" });
  await browser.evaluate(() => {
    const audit = { calls: [] as { active: boolean }[] };
    (window as any).__focusAudit = audit;
    const focus = HTMLElement.prototype.focus;
    HTMLElement.prototype.focus = function (...args) {
      if (this.matches('[data-testid="composer-editor"], [data-testid="composer-editor"] *')) audit.calls.push({ active: navigator.userActivation.isActive });
      return focus.apply(this, args);
    };
    const panel = document.createElement("div");
    panel.id = "focus-proof";
    panel.style.cssText = "position:fixed;top:65px;right:20px;z-index:99999;background:#15202d;color:white;padding:14px;border:2px solid #8295ac;border-radius:8px;font:14px monospace;pointer-events:none;white-space:pre";
    panel.textContent = "Android tablet emulation · 1163 × 720\nCoarse pointer: " + matchMedia("(pointer: coarse)").matches + "\nWaiting for menu interaction";
    document.body.append(panel);
  });
  const touch = async (selector: string) => {
    await browser.locator(selector).tap();
  };
  await touch('[data-chat-provider-model-picker="true"]');
  await touch('[data-composer-permissions-trigger]');
  await browser.locator('[data-composer-permissions] [aria-checked="true"]').waitFor({ state: "visible" });
  await app.screenshot("nested-permissions-open");
  await browser.mouse.move(750, 250);
  await browser.mouse.down();
  await browser.mouse.up();
  await browser.locator('[data-slot="popover-popup"]').waitFor({ state: "detached" });
  const result = await browser.evaluate(() => {
    const calls = (window as any).__focusAudit.calls;
    const focused = !!document.activeElement?.matches('[data-testid="composer-editor"], [data-testid="composer-editor"] *');
    document.getElementById("focus-proof")!.textContent = "Android tablet emulation · 1163 × 720\nCoarse pointer: " + matchMedia("(pointer: coarse)").matches + "\nOpened model picker → Permissions → tapped outside\nComposer focus() calls: " + calls.length + "\nDuring user activation: " + calls.filter((c: any) => c.active).length + "\nComposer focused: " + focused;
    return { calls: calls.length, focused };
  });
  await app.screenshot("after-tapping-outside");
  await expect(result).toEqual({ calls: 0, focused: false });
});
