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

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

  test("typing after bold delimiter does not trap cursor", async ({ page }) => {
    const blockIds = await page.evaluate(() =>
      window.__testUtils__?.getBlockIds(),
    )
    // Second block contains "**block**" in its content
    const id = blockIds?.[1]
    // Position cursor after "**block**" (14 chars into the paragraph text)
    await page.evaluate(
      ({ bid, from, to }: { bid: string; from: number; to: number }) =>
        window.__testUtils__?.selectText(bid, from, to),
      { bid: id, from: 14, to: 14 },
    )

    await page.keyboard.type("XX")

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

  test("typing before bold delimiter flows continuously", async ({ page }) => {
    const blockIds = await page.evaluate(() =>
      window.__testUtils__?.getBlockIds(),
    )
    const id = blockIds?.[1]
    // Position cursor right before "**block**" — "Each **" = 5 chars
    await page.evaluate(
      ({ bid, from, to }: { bid: string; from: number; to: number }) =>
        window.__testUtils__?.selectText(bid, from, to),
      { bid: id, from: 5, to: 5 },
    )

    await page.keyboard.type("YY")

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

  test("typing after strikethrough delimiter does not trap cursor", async ({
    page,
  }) => {
    // The initial content doesn't have ~~strikethrough~~, so use replaceContent
    const blockIds = await page.evaluate(() =>
      window.__testUtils__?.getBlockIds(),
    )
    const id = blockIds?.[0]
    await page.evaluate(
      ({ bid }: { bid: string }) =>
        window.__testUtils__?.replaceContent(bid, "hello ~~world~~ test"),
      { bid: id },
    )
    await page.evaluate(
      ({ bid, from, to }: { bid: string; from: number; to: number }) =>
        window.__testUtils__?.selectText(bid, from, to),
      { bid: id, from: 16, to: 16 },
    )

    await page.keyboard.type("ZZ")

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