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

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

  async function pasteIntoFocused(page: any, text: string) {
    // Dispatch a paste event on the focused PM editable element.
    // Control+V doesn't trigger paste reliably across platforms in headless
    // mode, so we use the ClipboardEvent constructor directly.
    await page.evaluate(async (t: string) => {
      const el = document.activeElement
      if (!el) return
      const dt = new DataTransfer()
      dt.setData("text/plain", t)
      el.dispatchEvent(
        new ClipboardEvent("paste", {
          clipboardData: dt,
          bubbles: true,
          cancelable: true,
        }),
      )
    }, text)
    // Allow PM to process the paste transaction
    await page.waitForTimeout(100)
  }

  test("pastes single line into focused block", async ({ page }) => {
    const blockIds = await page.evaluate(() =>
      window.__testUtils__?.getBlockIds(),
    )
    const lastId = blockIds?.[blockIds?.length - 1]
    await page.evaluate(
      (bid: string) => window.__testUtils__?.focusAtEnd(bid),
      lastId,
    )
    await pasteIntoFocused(page, "pasted text")

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

  test("pastes multi-line uniform text into same block", async ({ page }) => {
    const blockIds = await page.evaluate(() =>
      window.__testUtils__?.getBlockIds(),
    )
    const lastId = blockIds?.[blockIds?.length - 1]
    await page.evaluate(
      (bid: string) => window.__testUtils__?.focusAtEnd(bid),
      lastId,
    )
    await pasteIntoFocused(page, "line1\nline2\nline3")

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

  test("pastes multi-line with mixed types into new block", async ({
    page,
  }) => {
    const blockIds = await page.evaluate(() =>
      window.__testUtils__?.getBlockIds(),
    )
    const lastId = blockIds?.[blockIds?.length - 1]
    await page.evaluate(
      (bid: string) => window.__testUtils__?.focusAtEnd(bid),
      lastId,
    )

    const beforeCount = blockIds?.length
    await pasteIntoFocused(page, "text\n> blockquote")

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