// frontend/tests/auth/LoginPage.test.tsx — phase-15 로그인 화면.
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";

const push = vi.fn();
vi.mock("next/navigation", () => ({
  useRouter: () => ({ push }),
  useSearchParams: () => new URLSearchParams(""),
}));

const login = vi.fn();
vi.mock("@/lib/auth", () => ({ login: (e: string, p: string) => login(e, p) }));

import LoginPage from "@/app/login/page";

describe("LoginPage", () => {
  it("이메일/비밀번호 입력과 로그인 버튼을 렌더한다", () => {
    render(<LoginPage />);
    expect(screen.getByPlaceholderText("이메일")).toBeInTheDocument();
    expect(screen.getByPlaceholderText("비밀번호")).toBeInTheDocument();
    expect(screen.getByRole("button", { name: "로그인" })).toBeInTheDocument();
  });

  it("입력이 비어 있으면 로그인 버튼이 비활성", () => {
    render(<LoginPage />);
    expect(screen.getByRole("button", { name: "로그인" })).toBeDisabled();
  });

  it("채우면 버튼이 활성화된다", () => {
    render(<LoginPage />);
    fireEvent.change(screen.getByPlaceholderText("이메일"), {
      target: { value: "jiwoo@lumi.co" },
    });
    fireEvent.change(screen.getByPlaceholderText("비밀번호"), {
      target: { value: "demo-1234" },
    });
    expect(screen.getByRole("button", { name: "로그인" })).toBeEnabled();
  });

  it("로그인 실패 시 에러 알림을 표시한다", async () => {
    login.mockRejectedValueOnce(new Error("이메일 또는 비밀번호가 올바르지 않아요"));
    render(<LoginPage />);
    fireEvent.change(screen.getByPlaceholderText("이메일"), {
      target: { value: "jiwoo@lumi.co" },
    });
    fireEvent.change(screen.getByPlaceholderText("비밀번호"), {
      target: { value: "wrong" },
    });
    fireEvent.click(screen.getByRole("button", { name: "로그인" }));

    await waitFor(() => expect(login).toHaveBeenCalledWith("jiwoo@lumi.co", "wrong"));
    const alert = await screen.findByRole("alert");
    expect(alert).toHaveTextContent("이메일 또는 비밀번호가 올바르지 않아요");
    expect(push).not.toHaveBeenCalled();
  });
});
