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

import { PageImpactTimeline, type PageTimeline } from './PageImpactTimeline';

// Mock recharts to avoid canvas/SVG layout issues in jsdom. We assert on the
// accessible text summary + marker presence, not the rendered SVG geometry.
vi.mock('recharts', () => ({
  ResponsiveContainer: ({ children }: { children: React.ReactNode }) => (
    <div data-testid="responsive-container">{children}</div>
  ),
  LineChart: ({ children }: { children: React.ReactNode }) => (
    <div data-testid="line-chart">{children}</div>
  ),
  Line: () => <div data-testid="line" />,
  CartesianGrid: () => null,
  XAxis: () => null,
  YAxis: () => null,
  Tooltip: () => null,
  ReferenceLine: ({ label }: { label?: { value?: string } }) => (
    <div data-testid="reference-line">{label?.value}</div>
  ),
  ReferenceArea: () => <div data-testid="reference-area" />,
}));

vi.mock('@/Components/theme', () => ({
  useTheme: () => ({ resolvedTheme: 'light' }),
}));

const timeline: PageTimeline = {
  series: [
    { date: '2026-05-01', clicks: 10, impressions: 100 },
    { date: '2026-05-02', clicks: 12, impressions: 110 },
    { date: '2026-05-10', clicks: 30, impressions: 200 },
    { date: '2026-05-11', clicks: 32, impressions: 210 },
  ],
  applied_date: '2026-05-10',
  before: { avg_clicks: 11, total_clicks: 22, days: 2 },
  after: { avg_clicks: 31, total_clicks: 62, days: 2 },
  measured_clicks_delta: 40,
  is_significant: true,
  measured_label: 'Measured before → after — your traffic, not a RankWizAI claim.',
};

describe('PageImpactTimeline', () => {
  it('renders the before and after measured averages', () => {
    render(<PageImpactTimeline timeline={timeline} />);

    expect(screen.getByText('Before')).toBeInTheDocument();
    expect(screen.getByText('After')).toBeInTheDocument();
    expect(screen.getByText('11 clicks/day')).toBeInTheDocument();
    expect(screen.getByText('31 clicks/day')).toBeInTheDocument();
  });

  it('renders the publish/applied marker', () => {
    render(<PageImpactTimeline timeline={timeline} />);

    expect(screen.getByTestId('reference-line')).toHaveTextContent('Applied');
  });

  it('renders before and after shading areas', () => {
    render(<PageImpactTimeline timeline={timeline} />);

    expect(screen.getAllByTestId('reference-area')).toHaveLength(2);
  });

  it('uses honest, non-causal labeling', () => {
    render(<PageImpactTimeline timeline={timeline} />);

    const label = screen.getByText(/Measured before/i);
    expect(label.textContent?.toLowerCase()).not.toContain('recovered by');
  });

  it('omits the marker when there is no applied date', () => {
    render(
      <PageImpactTimeline
        timeline={{ ...timeline, applied_date: null, before: null, after: null }}
      />,
    );

    expect(screen.queryByTestId('reference-line')).not.toBeInTheDocument();
  });
});
