import { describe, it, expect } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/react';
import { I18nProvider, useI18n } from '@/lib/i18n';

describe('i18n translation files', () => {
  it('de.json has at least 20 keys', async () => {
    const de = await import('@/messages/de.json');
    const keys = Object.keys(de.default || de);
    expect(keys.length).toBeGreaterThanOrEqual(20);
  });

  it('en.json has at least 20 keys', async () => {
    const en = await import('@/messages/en.json');
    const keys = Object.keys(en.default || en);
    expect(keys.length).toBeGreaterThanOrEqual(20);
  });

  it('de and en have matching keys', async () => {
    const de = await import('@/messages/de.json');
    const en = await import('@/messages/en.json');
    const deKeys = Object.keys(de.default || de).sort();
    const enKeys = Object.keys(en.default || en).sort();
    expect(deKeys).toEqual(enKeys);
  });
});

describe('i18n provider', () => {
  it('provides translation function', () => {
    function TestComp() {
      const { t } = useI18n();
      return <span data-testid="result">{t('common.save')}</span>;
    }
    render(
      <I18nProvider initialLocale="de">
        <TestComp />
      </I18nProvider>
    );
    expect(screen.getByTestId('result').textContent).toBe('Speichern');
  });

  it('supports parameter interpolation', () => {
    function TestComp() {
      const { t } = useI18n();
      return <span data-testid="result">{t('login.error.invalidCredentials')}</span>;
    }
    render(
      <I18nProvider initialLocale="en">
        <TestComp />
      </I18nProvider>
    );
    expect(screen.getByTestId('result').textContent).toBe('Invalid email or password');
  });

  it('falls back to key for unknown translations', () => {
    function TestComp() {
      const { t } = useI18n();
      return <span data-testid="result">{t('nonexistent.key')}</span>;
    }
    render(
      <I18nProvider initialLocale="de">
        <TestComp />
      </I18nProvider>
    );
    expect(screen.getByTestId('result').textContent).toBe('nonexistent.key');
  });
});
