import React from 'react';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter } from 'react-router-dom';
import { ThemeProvider } from 'styled-components';
import ConversationDetailCard, {
  injectCitationMarkers,
} from './ConversationDetailCard';

const theme = {
  main: '#336699',
  focus: '#224466',
  darkMode: true,
  colors: {
    text: '#ffffff',
    cardBackground: 'rgba(0,0,0,0.3)',
    cardBorder: 'rgba(255,255,255,0.1)',
  },
};

const renderCard = (props: React.ComponentProps<typeof ConversationDetailCard>) =>
  render(
    <MemoryRouter>
      <ThemeProvider theme={theme as never}>
        <ConversationDetailCard {...props} />
      </ThemeProvider>
    </MemoryRouter>,
  );

describe('ConversationDetailCard citations (#98)', () => {
  it('injects citation markers outside code fences', () => {
    const md = 'See [1] and [2, 3]\n\n```\n[9]\n```';
    const out = injectCitationMarkers(md);
    expect(out).toContain('<citation indices="1"></citation>');
    expect(out).toContain('<citation indices="2,3"></citation>');
    expect(out).toContain('```\n[9]\n```');
  });

  it('does not render Sources list card', () => {
    renderCard({
      message: 'Answer with [1]',
      user_created: false,
      citations: [
        {
          index: 1,
          title: 'Example Source',
          url: 'https://example.com/a',
          published_at: '2026-07-03',
        },
      ],
    });
    expect(screen.queryByLabelText('Sources')).not.toBeInTheDocument();
    expect(screen.getByRole('button', { name: 'Source 1' })).toBeInTheDocument();
  });

  it('opens citation URL in a new tab when inline marker clicked', async () => {
    const user = userEvent.setup();
    const openSpy = jest.spyOn(window, 'open').mockImplementation(() => null);
    renderCard({
      message: 'See [1]',
      user_created: false,
      citations: [
        { index: 1, title: 'Src', url: 'https://example.com', published_at: null },
      ],
    });
    await user.click(screen.getByRole('button', { name: 'Source 1' }));
    expect(openSpy).toHaveBeenCalledWith(
      'https://example.com',
      '_blank',
      'noopener,noreferrer',
    );
    openSpy.mockRestore();
  });
});
