import { fireEvent, screen, waitFor } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { renderWithProviders } from "../test/testHelpers";
import { LoginPage } from "./LoginPage";

const { mockSignInWithPassword, mockNavigate } = vi.hoisted(() => ({
  mockSignInWithPassword: vi.fn(),
  mockNavigate: vi.fn(),
}));

vi.mock("../lib/supabase", () => ({
  supabase: {
    auth: {
      signInWithPassword: mockSignInWithPassword,
    },
  },
}));

vi.mock("react-router-dom", async (importOriginal) => {
  const actual = await importOriginal<typeof import("react-router-dom")>();
  return {
    ...actual,
    useNavigate: () => mockNavigate,
  };
});

describe("LoginPage", () => {
  beforeEach(() => {
    vi.clearAllMocks();
    localStorage.clear();
    mockSignInWithPassword.mockResolvedValue({
      data: { user: { email_confirmed_at: new Date().toISOString() } },
      error: null,
    });
  });

  it("renders the shared auth shell and form", () => {
    renderWithProviders(<LoginPage />, { testUser: undefined });

    expect(screen.getByTestId("auth-card-shell")).toBeInTheDocument();
    expect(screen.getByLabelText("Email")).toBeInTheDocument();
    expect(screen.getByLabelText("Mot de passe")).toBeInTheDocument();
    expect(screen.getByRole("button", { name: "Connexion" })).toBeInTheDocument();
    expect(screen.getAllByAltText("Xtablo")[0]).toHaveAttribute(
      "src",
      "https://assets.xtablo.com/logo_dark.png"
    );
  });

  it("submits email/password login and resumes the stored redirect", async () => {
    localStorage.setItem("clients.redirectUrl", "/tablo/tablo-42");
    renderWithProviders(<LoginPage />, { testUser: undefined });

    fireEvent.change(screen.getByLabelText("Email"), { target: { value: "client@example.com" } });
    fireEvent.change(screen.getByLabelText("Mot de passe"), { target: { value: "password123" } });
    fireEvent.click(screen.getByRole("button", { name: "Connexion" }));

    await waitFor(() => {
      expect(mockSignInWithPassword).toHaveBeenCalledWith({
        email: "client@example.com",
        password: "password123",
      });
      expect(mockNavigate).toHaveBeenCalledWith("/tablo/tablo-42");
    });
  });
});
