import { render, screen, fireEvent } from '@testing-library/react';
import { ThemeProvider } from '../../theme';

jest.mock('next-intl', () => ({ useTranslations: () => (k: string) => k, useLocale: () => 'en' }));

import AuditLogRow from './AuditLogRow';
import type { AuditLogEntry } from '@/services/admin/types';

const ENTRY: AuditLogEntry = {
  id: 1,
  entityType: 'PlatformConfig',
  entityId: 'vat_rate',
  action: 'updated',
  actorUserId: 3,
  occurredAt: '2026-01-01T00:00:00Z',
  changedFields: { Value: { old: '0.09', new: '0.10' } },
};

describe('<AuditLogRow/>', () => {
  const wrap = (ui: React.ReactNode) => render(<ThemeProvider>{ui}</ThemeProvider>);

  it('renders the entity and action', () => {
    wrap(<AuditLogRow entry={ENTRY} />);
    expect(screen.getByText('PlatformConfig #vat_rate')).toBeInTheDocument();
    expect(screen.getByText('updated')).toBeInTheDocument();
  });

  it('reveals the changed-fields diff on expand', () => {
    wrap(<AuditLogRow entry={ENTRY} />);
    // Collapsed diff is not visible; expand by clicking the row header.
    fireEvent.click(screen.getByText('PlatformConfig #vat_rate'));
    expect(screen.getByText('Value')).toBeInTheDocument();
    expect(screen.getByText('0.09')).toBeInTheDocument();
    expect(screen.getByText('0.10')).toBeInTheDocument();
  });

  it('toggles aria-expanded on the row header', () => {
    wrap(<AuditLogRow entry={ENTRY} />);
    const header = screen.getByRole('button');
    expect(header).toHaveAttribute('aria-expanded', 'false');
    fireEvent.click(header);
    expect(header).toHaveAttribute('aria-expanded', 'true');
  });

  it('falls back to #id when no actorLabel is resolved, else shows the name', () => {
    const { rerender } = wrap(<AuditLogRow entry={ENTRY} />);
    expect(screen.getByText('#3')).toBeInTheDocument();
    rerender(
      <ThemeProvider>
        <AuditLogRow entry={ENTRY} actorLabel="سارا کریمی" />
      </ThemeProvider>,
    );
    expect(screen.getByText('سارا کریمی')).toBeInTheDocument();
  });

  it('renders no button role for a row with no diff to expand', () => {
    wrap(<AuditLogRow entry={{ ...ENTRY, changedFields: null }} />);
    expect(screen.queryByRole('button')).not.toBeInTheDocument();
  });
});
