import { test, expect } from "@playwright/test"
import {
  fillCompose,
  gotoInbox,
  openCompose,
  scheduleComposeInOneHour,
  sendComposeNow,
} from "./helpers/mail-app"

test.beforeEach(async ({ page }) => {
  await page.addInitScript(() => {
    window.localStorage.clear()
    window.sessionStorage.clear()
  })
})

test.describe("mail journeys (mock data)", () => {
  test("reads a message from inbox", async ({ page }) => {
    await gotoInbox(page)

    await page.locator('[data-email-row-id="1"]').click()

    await expect(page).toHaveURL(/\/mail\/inbox\/message\/1/)
    await expect(page.getByTitle("Sujet du message")).toBeVisible()
    await expect(page.getByLabel("Répondre").first()).toBeVisible()
  })

  test("composes and sends a message", async ({ page }) => {
    const subject = `E2E send ${Date.now()}`

    await gotoInbox(page)
    await openCompose(page)
    await fillCompose(page, {
      to: "test@example.com",
      subject,
      body: "Playwright send journey",
    })
    await sendComposeNow(page)
  })

  test("schedules a message for later", async ({ page }) => {
    const subject = `E2E schedule ${Date.now()}`

    await gotoInbox(page)
    await openCompose(page)
    await fillCompose(page, {
      to: "scheduled@example.com",
      subject,
      body: "Playwright schedule journey",
    })
    await scheduleComposeInOneHour(page)

    await expect(page.getByText(/Ce mail sera envoyé le/)).toBeVisible()
    await page.waitForFunction(
      (expectedSubject) => {
        const raw = localStorage.getItem("ultimail-scheduled-state")
        return raw?.includes(expectedSubject) ?? false
      },
      subject,
      { timeout: 10_000 }
    )
  })

  test("searches messages", async ({ page }) => {
    await gotoInbox(page)

    const search = page.getByPlaceholder("Rechercher dans les messages")
    await search.fill("Uber")
    await search.press("Enter")

    await expect(page).toHaveURL(/\/mail\/search/)
    await expect(page.locator("[data-email-row-id]").first()).toContainText("Uber")
  })
})
