import { screen, fireEvent, waitFor } from '@testing-library/react';
import { renderWithProviders as render } from '../../../test/render';
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { CodeBlock } from './CodeBlock';
import React from 'react';

describe('CodeBlock', () => {
  const mockWriteText = vi.fn().mockResolvedValue(undefined);

  beforeEach(() => {
    vi.clearAllMocks();
    // Mock clipboard API safely
    vi.stubGlobal('navigator', {
      clipboard: {
        writeText: mockWriteText,
      },
    });
  });

  it('renders code correctly', () => {
    const code = 'const x = 1;';
    const { container } = render(<CodeBlock code={code} language="typescript" />);
    // Simple check: is the text present in the container?
    expect(container.textContent).toContain(code);
  });

  it('shows filename in header', () => {
    render(<CodeBlock code="code" filename="test.ts" />);
    expect(screen.getByText('test.ts')).toBeInTheDocument();
  });

  it('copies code to clipboard when button is clicked', async () => {
    const code = 'copy me';
    render(<CodeBlock code={code} />);

    const copyButton = screen.getByLabelText('Copiar código');
    fireEvent.click(copyButton);

    expect(mockWriteText).toHaveBeenCalledWith(code);

    await waitFor(() => {
      expect(screen.getByLabelText('Copiado')).toBeInTheDocument();
    });
  });
});
