// @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 { updateUserMock } = vi.hoisted(() => ({
    updateUserMock: vi.fn()
}));

vi.mock('../lib/supabaseClient', () => ({
    supabase: {
        auth: {
            updateUser: updateUserMock
        }
    }
}));

describe('ResetPassword DOM flow', () => {
    beforeEach(() => {
        updateUserMock.mockReset();
        updateUserMock.mockResolvedValue({ error: null });
        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(updateUserMock).toHaveBeenCalledWith({ password: 'MyNewPassword123!' });
            expect(screen.getByText('Password updated successfully! You can now login.')).toBeInTheDocument();
        });
    }, 15000);

    it('shows provider error when password update fails', async () => {
        updateUserMock.mockResolvedValueOnce({ error: { message: '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(updateUserMock).toHaveBeenCalled();
            expect(screen.getByText('Password is too weak')).toBeInTheDocument();
        });

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