import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';

vi.mock('../../lib/analytics', () => ({ trackEvent: () => {} }));

vi.mock('react-i18next', async (importOriginal) => ({
  ...(await importOriginal<typeof import('react-i18next')>()),
  useTranslation: () => ({ t: (key: string) => key }),
  Trans: ({ i18nKey }: { i18nKey: string }) => <>{i18nKey}</>,
}));

import AuthModal from './AuthModal';

const noop = async () => {};

function renderModal(initialTab: 'login' | 'register' = 'login') {
  return render(
    <AuthModal
      onClose={() => {}}
      onLogin={noop}
      onRegister={noop}
      onOAuthLogin={noop}
      onForgotPassword={noop}
      loading={false}
      error={null}
      onClearError={() => {}}
      initialTab={initialTab}
    />
  );
}

afterEach(cleanup);

describe('AuthModal password visibility toggle', () => {
  it('starts hidden and reveals the password when clicked', () => {
    renderModal('login');

    const input = screen.getByLabelText('auth.password') as HTMLInputElement;
    expect(input.type).toBe('password');

    // Hidden state exposes a "show" toggle.
    const toggle = screen.getByRole('button', { name: 'auth.showPassword' });
    expect(toggle.getAttribute('type')).toBe('button');
    expect(toggle.getAttribute('aria-pressed')).toBe('false');

    fireEvent.click(toggle);

    expect(input.type).toBe('text');
    const hideToggle = screen.getByRole('button', { name: 'auth.hidePassword' });
    expect(hideToggle.getAttribute('aria-pressed')).toBe('true');

    fireEvent.click(hideToggle);
    expect(input.type).toBe('password');
  });

  it('offers the toggle on the register tab too', () => {
    renderModal('register');
    const input = screen.getByLabelText('auth.password') as HTMLInputElement;
    expect(input.type).toBe('password');
    fireEvent.click(screen.getByRole('button', { name: 'auth.showPassword' }));
    expect(input.type).toBe('text');
  });
});
