// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { ResetPassword } from './ResetPassword';

const { resetPlatformPasswordMock } = vi.hoisted(() => ({
    resetPlatformPasswordMock: vi.fn()
}));

vi.mock('../lib/authSession', () => ({
    resetPlatformPassword: resetPlatformPasswordMock
}));

describe('ResetPassword DOM flow', () => {
    beforeEach(() => {
        resetPlatformPasswordMock.mockReset();
        resetPlatformPasswordMock.mockResolvedValue(undefined);
        window.history.pushState({}, '', '/reset-callback#type=recovery');
    });

    afterEach(() => {
        vi.useRealTimers();
    });

    it('updates password and redirects back to login route', async () => {
        const user = userEvent.setup();
        render(<ResetPassword />);

        await user.type(screen.getByPlaceholderText('New password'), 'MyNewPassword123!');
        await user.click(screen.getByRole('button', { name: 'Update Password' }));

        await waitFor(() => {
            expect(resetPlatformPasswordMock).toHaveBeenCalledWith('MyNewPassword123!');
            expect(screen.getByText('Password updated successfully! You can now login.')).toBeInTheDocument();
        });
    }, 15000);

    it('shows provider error when password update fails', async () => {
        resetPlatformPasswordMock.mockRejectedValueOnce(new Error('Password is too weak'));
        const user = userEvent.setup();
        render(<ResetPassword />);

        await user.type(screen.getByPlaceholderText('New password'), '123');
        await user.click(screen.getByRole('button', { name: 'Update Password' }));

        await waitFor(() => {
            expect(resetPlatformPasswordMock).toHaveBeenCalled();
            expect(screen.getByText('Password is too weak')).toBeInTheDocument();
        });

        expect(screen.getByRole('button', { name: 'Update Password' })).toBeEnabled();
    }, 15000);
});
