
import { render, screen, fireEvent, waitFor } from "@testing-library/react"
import LoginPage from "./page"
import { login } from "@/lib/auth"

// Mocks
jest.mock("next/navigation", () => ({
    useRouter: () => ({ push: jest.fn() }),
}))

jest.mock("@/lib/auth", () => ({
    login: jest.fn(),
}))

jest.mock("@/lib/i18n", () => ({
    useTranslation: () => ({
        t: (key: string) => key,
    }),
}))

jest.mock("framer-motion", () => ({
    motion: {
        div: ({ children, ...props }: any) => <div {...props}>{children}</div>,
    },
}))

global.ResizeObserver = class {
    observe() { }
    unobserve() { }
    disconnect() { }
} as any

describe("LoginPage", () => {
    beforeEach(() => {
        jest.clearAllMocks()
    })

    it("renders login form", () => {
        render(<LoginPage />)
        // Adjust these to match actual keys or content if i18n is mocked to return keys
        expect(screen.getByPlaceholderText(/auth.login.fields.usernamePlaceholder/i)).toBeInTheDocument()
        expect(screen.getByPlaceholderText(/auth.login.fields.passwordPlaceholder/i)).toBeInTheDocument()
        expect(screen.getByRole("button", { name: /auth.login.submit/i })).toBeInTheDocument()
    })

    it("requires email and password", async () => {
        render(<LoginPage />)

        fireEvent.click(screen.getByRole("button", { name: /auth.login.submit/i }))

        await waitFor(() => {
            expect(screen.getByText(/auth.login.validation.username/i)).toBeInTheDocument()
            expect(screen.getByText(/auth.login.validation.password/i)).toBeInTheDocument()
        })
    })

    it("calls login function on valid submission", async () => {
        (login as jest.Mock).mockResolvedValue({ id: "1", email: "test@example.com" })
        render(<LoginPage />)

        fireEvent.change(screen.getByPlaceholderText(/auth.login.fields.usernamePlaceholder/i), { target: { value: "test@example.com" } })
        fireEvent.change(screen.getByPlaceholderText(/auth.login.fields.passwordPlaceholder/i), { target: { value: "password123" } })
        fireEvent.click(screen.getByRole("button", { name: /auth.login.submit/i }))

        await waitFor(() => {
            expect(login).toHaveBeenCalledWith("test@example.com", "password123")
        })
    })
})
