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

test.describe("Drag-and-drop block reorder", () => {
  test.beforeEach(async ({ page }) => {
    await page.goto("/editor?e2e=true")
  })

  test("drag block 0 to after block 2 reorders correctly", async ({ page }) => {
    const beforeIds = await page.evaluate(() =>
      window.__testUtils__?.getBlockIds(),
    )
    expect(beforeIds?.length).toBeGreaterThan(2)

    // Use programmatic reorderBlocks instead of HTML5 DnD, since Playwright
    // cannot reliably trigger the browser's drag-and-drop engine.
    await page.evaluate(() => {
      window.__testUtils__?.reorderBlocks(0, 2)
    })

    // Block 0 should now be at index 2 (after blocks 1 and 2)

    // Block 0 should now be at index 2 (after blocks 1 and 2)
    const afterIds = await page.evaluate(() =>
      window.__testUtils__?.getBlockIds(),
    )
    expect(afterIds?.[0]).toBe(beforeIds?.[1])
    expect(afterIds?.[1]).toBe(beforeIds?.[2])
    expect(afterIds?.[2]).toBe(beforeIds?.[0])
  })

  test("drag block 2 to before block 0 reorders correctly", async ({
    page,
  }) => {
    const beforeIds = await page.evaluate(() =>
      window.__testUtils__?.getBlockIds(),
    )
    expect(beforeIds?.length).toBeGreaterThan(2)

    // Move block at index 2 to before block 0
    await page.evaluate(() => {
      window.__testUtils__?.reorderBlocks(2, 0)
    })

    const afterIds = await page.evaluate(() =>
      window.__testUtils__?.getBlockIds(),
    )
    expect(afterIds?.[0]).toBe(beforeIds?.[2])
    expect(afterIds?.[1]).toBe(beforeIds?.[0])
    expect(afterIds?.[2]).toBe(beforeIds?.[1])
  })
})
