import { describe, it, expect, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";

vi.mock("@/api/driver", () => ({
  getBalance: vi.fn(async () => ({
    accounts: [
      { bucket: "Долг аренда", balance: -3200 },
      { bucket: "Депозит", balance: 5000 },
    ],
  })),
}));

import { BalancePage } from "./BalancePage";

function wrap() {
  const qc = new QueryClient();
  return render(
    <QueryClientProvider client={qc}>
      <MemoryRouter><BalancePage /></MemoryRouter>
    </QueryClientProvider>
  );
}

describe("BalancePage", () => {
  it("shows hero total (sum of negatives) and account rows", async () => {
    wrap();
    expect(await screen.findByText("Долг аренда")).toBeInTheDocument();
    expect(screen.getByText("Депозит")).toBeInTheDocument();
    // Appears in both the hero total and the single debt account row.
    expect(screen.getAllByText("−3 200 ₽").length).toBeGreaterThan(0);
    expect(screen.getByRole("button", { name: /Пополнить/i })).toBeInTheDocument();
  });

  it("shows an error state when balance fails to load", async () => {
    const driver = await import("@/api/driver");
    (driver.getBalance as any).mockRejectedValueOnce(new Error("boom"));
    // re-render fresh
    const { QueryClient, QueryClientProvider } = await import("@tanstack/react-query");
    const { MemoryRouter } = await import("react-router-dom");
    const { render, screen } = await import("@testing-library/react");
    const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
    render(<QueryClientProvider client={qc}><MemoryRouter><BalancePage /></MemoryRouter></QueryClientProvider>);
    expect(await screen.findByText(/Не удалось загрузить/i)).toBeInTheDocument();
  });
});
