// @vitest-environment jsdom
// Copyright: © 2026 TWWIM UG. All rights reserved. (www.twwim.com)
/**
 * Unit tests for CapturedContactBlock.
 *
 * Mocks useCapturedContact + useTranslation so the test exercises pure
 * render branches (null payload → render nothing; populated payload →
 * render all entries from values).
 */

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

vi.mock('../hooks/useCapturedContact', () => ({
  useCapturedContact: vi.fn(),
}));

vi.mock('@/i18n/TranslationProvider', () => ({
  useTranslation: () => ({
    t: (key: string, vars?: Record<string, string | number>) =>
      vars ? `${key}|${JSON.stringify(vars)}` : key,
    locale: 'en' as const,
    setLocale: () => undefined,
  }),
}));

import { useCapturedContact } from '../hooks/useCapturedContact';
import { CapturedContactBlock } from './CapturedContactBlock';

const mockedHook = vi.mocked(useCapturedContact);

afterEach(() => {
  cleanup();
  mockedHook.mockReset();
});

describe('CapturedContactBlock', () => {
  it('renders nothing when captured is null', () => {
    mockedHook.mockReturnValue({ data: { captured: null } } as ReturnType<typeof useCapturedContact>);
    const { container } = render(<CapturedContactBlock conversationId="conv-1" />);
    expect(container.firstChild).toBeNull();
  });

  it('renders nothing when data is undefined (still loading)', () => {
    mockedHook.mockReturnValue({ data: undefined } as ReturnType<typeof useCapturedContact>);
    const { container } = render(<CapturedContactBlock conversationId="conv-1" />);
    expect(container.firstChild).toBeNull();
  });

  it('renders every key/value pair from captured.values', () => {
    mockedHook.mockReturnValue({
      data: {
        captured: {
          values: { name: 'Sarah Chen', email: 'sarah@example.com', phone: '+49 30 1234567' },
          capturedAt: new Date(Date.now() - 5 * 60_000).toISOString(),
          formName: 'lead-capture',
        },
      },
    } as ReturnType<typeof useCapturedContact>);

    const { getByTestId } = render(<CapturedContactBlock conversationId="conv-1" />);
    expect(getByTestId('captured-contact-block')).toBeTruthy();
    expect(getByTestId('captured-name').textContent).toContain('Sarah Chen');
    expect(getByTestId('captured-email').textContent).toContain('sarah@example.com');
    expect(getByTestId('captured-phone').textContent).toContain('+49 30 1234567');
    expect(getByTestId('captured-at').textContent).toContain('conversations.captured.capturedAt');
  });
});
