import { expect, test } from "@playwright/test"

test.describe("IME composition", () => {
  test.beforeEach(async ({ page }) => {
    await page.goto("/editor?e2e=true")
  })

  test("typing / during composition does not open suggestion menu", async ({
    page,
  }) => {
    // Focus the PM editor
    const pm = page.locator('[role="textbox"][data-block-id]').first()
    await pm.click()

    // Simulate IME composition starting, then committing "/" as part of
    // composed text — the suggestion menu should not appear because the
    // text was not typed as individual keystrokes.
    await page.evaluate(() => {
      const el = document.activeElement
      if (!el) return

      // Start composition
      el.dispatchEvent(new CompositionEvent("compositionstart", { data: "" }))

      // Simulate the composition text being entered (beforeinput with
      // insertCompositionText type). PM's composition handling processes
      // this and dispatches a transaction with the composed text.
      if ("InputEvent" in window) {
        el.dispatchEvent(
          new InputEvent("beforeinput", {
            inputType: "insertCompositionText",
            data: "/",
            bubbles: true,
            cancelable: true,
          }),
        )
      }

      // End composition (commit the text)
      el.dispatchEvent(new CompositionEvent("compositionend", { data: "/" }))
    })

    await page.waitForTimeout(200)

    // The suggestion menu should NOT be visible — IME composition text
    // is committed as a single block, not as individual keystrokes.
    const menu = page.locator("[data-command-palette]")
    await expect(menu).not.toBeVisible()
  })
})
