import { expect, test } from "@playwright/test"
import { focusLastBlockAtEnd } from "./helpers"

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

  test("Enter splits a block and creates a new one", async ({ page }) => {
    await focusLastBlockAtEnd(page)
    await page.keyboard.type("hello world")
    await page.keyboard.press("Enter")

    const content = await page.evaluate(() =>
      window.__testUtils__?.getContent(),
    )
    expect(content).toContain("hello")
    expect(content).toContain("world")
  })

  test("Shift+Enter creates a soft break, not a new block", async ({
    page,
  }) => {
    const blockIds = await page.evaluate(() =>
      window.__testUtils__?.getBlockIds(),
    )
    const before = blockIds?.length

    await focusLastBlockAtEnd(page)
    await page.keyboard.type("line1")
    await page.keyboard.press("Shift+Enter")
    await page.keyboard.type("line2")

    const afterIds = await page.evaluate(() =>
      window.__testUtils__?.getBlockIds(),
    )
    expect(afterIds?.length).toBe(before)
  })

  test("Backspace on new empty block removes it", async ({ page }) => {
    const blockIds = await page.evaluate(() =>
      window.__testUtils__?.getBlockIds(),
    )
    const before = blockIds?.length

    await focusLastBlockAtEnd(page)
    await page.keyboard.press("Enter")

    // The new empty block at the end should be focused. Backspace removes it.
    await page.keyboard.press("Backspace")

    const afterIds = await page.evaluate(() =>
      window.__testUtils__?.getBlockIds(),
    )
    expect(afterIds?.length).toBe(before)
  })

  test("ArrowDown navigates to next block", async ({ page }) => {
    const blockIds = await page.evaluate(() =>
      window.__testUtils__?.getBlockIds(),
    )
    const firstId = blockIds?.[0]
    const secondId = blockIds?.[1]
    await page.evaluate(
      (bid: string) => window.__testUtils__?.focusAtStart(bid),
      firstId,
    )
    await page.keyboard.type("First block ")
    await page.evaluate(
      (bid: string) => window.__testUtils__?.focusAtStart(bid),
      secondId,
    )
    await page.keyboard.type("Second block ")

    const content = await page.evaluate(() =>
      window.__testUtils__?.getContent(),
    )
    expect(content).toContain("First block")
    expect(content).toContain("Second block")
  })
})
