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

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

  test("clicking a block focuses its PM editor", async ({ page }) => {
    const pm = page.locator('[role="textbox"][data-block-id]').nth(2)
    await pm.click()
    await expect(pm).toBeFocused()
  })

  test("typing after focus lands text in the correct block", async ({
    page,
  }) => {
    const blockIds = await page.evaluate(() =>
      window.__testUtils__?.getBlockIds(),
    )
    const firstId = blockIds?.[0]
    const secondId = blockIds?.[1]

    // Focus and type in first block
    const firstPm = page.locator(`[role="textbox"][data-block-id="${firstId}"]`)
    await firstPm.click()
    await expect(firstPm).toBeFocused()
    await page.keyboard.type("AAA")
    const afterFirstType = await page.evaluate(() =>
      window.__testUtils__?.getContent(),
    )
    expect(afterFirstType).toContain("AAA")

    // Click and type in second block
    const secondPm = page.locator(
      `[role="textbox"][data-block-id="${secondId}"]`,
    )
    await secondPm.click()
    await expect(secondPm).toBeFocused()
    await page.keyboard.type("BBB")
    const afterSecondType = await page.evaluate(() =>
      window.__testUtils__?.getContent(),
    )
    expect(afterSecondType).toContain("BBB")
  })

  test("clicking outside editor blurs active block", async ({ page }) => {
    const pm = page.locator('[role="textbox"][data-block-id]').first()
    await pm.click()
    await expect(pm).toBeFocused()

    // Click outside the editor to blur
    await page.locator("body").click({ position: { x: 0, y: 0 } })
    await expect(pm).not.toBeFocused()
  })
})
