import { render, screen, within } from "@testing-library/react"
import { MemoryRouter } from "react-router-dom"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { vi, test, expect } from "vitest"
import { App } from "./App"
import { AuthProvider } from "@/auth/AuthContext"
import { api } from "@/api/client"

test("renders navigation and redirects to domains", async () => {
  vi.spyOn(api.auth, "me").mockResolvedValue({
    user: { id: "u1", email: "a@b.com" },
    project: { id: "p1", name: "Default" },
  })
  vi.spyOn(api, "listDomains").mockResolvedValue([])

  render(
    <QueryClientProvider client={new QueryClient()}>
      <AuthProvider>
        <MemoryRouter initialEntries={["/"]}>
          <App />
        </MemoryRouter>
      </AuthProvider>
    </QueryClientProvider>,
  )
  // Sidebar nav also renders a "Domains" link label, so scope the assertion
  // to the routed page content to unambiguously confirm the redirect + page.
  // Suspense is now scoped inside <main>, so <main> mounts with the loading
  // fallback first — await the lazy chunk resolving to the actual page text.
  const main = await screen.findByRole("main")
  expect(await within(main).findByText("Domains")).toBeInTheDocument()
  expect(screen.getByRole("link", { name: /domains/i })).toBeInTheDocument()
})
