import { render, screen } from "@testing-library/react";
import { MemoryRouter, Route, Routes } from "react-router-dom";
import { describe, expect, it, vi } from "vitest";

import { ProtectedRoute } from "./ProtectedRoute";

const mockUseAuth = vi.fn();

vi.mock("../state/auth", () => ({
  useAuth: () => mockUseAuth()
}));

describe("ProtectedRoute", () => {
  it("shows loading while session is resolving", () => {
    mockUseAuth.mockReturnValue({ state: "loading" });

    render(
      <MemoryRouter initialEntries={["/"]}>
        <ProtectedRoute>
          <div>private content</div>
        </ProtectedRoute>
      </MemoryRouter>
    );

    expect(screen.getByText("Checking session...")).toBeInTheDocument();
  });

  it("redirects unauthenticated users to login", () => {
    mockUseAuth.mockReturnValue({ state: "unauthenticated" });

    render(
      <MemoryRouter initialEntries={["/settings"]}>
        <Routes>
          <Route
            path="/settings"
            element={
              <ProtectedRoute>
                <div>private content</div>
              </ProtectedRoute>
            }
          />
          <Route path="/login" element={<div>login page</div>} />
        </Routes>
      </MemoryRouter>
    );

    expect(screen.getByText("login page")).toBeInTheDocument();
  });
});
