/**
 * @jest-environment jsdom
 *
 * Tests for the PerformanceMetrics dashboard widget (PR #902).
 * Focus: the admin-bypass amber note (rendered only when stats.adminBypass is
 * present) and the corresponding `locked` MetricCards, plus the
 * upgrade_required short-circuit. The wrapping next/link is mocked to a plain
 * anchor (same pattern as DealerResourceCenter.test.tsx).
 */

import React from 'react';
import { render, screen, waitFor } from '@testing-library/react';
import '@testing-library/jest-dom';
import { PerformanceMetrics } from '../PerformanceMetrics';

jest.mock('next/link', () => {
  return function MockLink({ children, href }: { children: React.ReactNode; href: string }) {
    return <a href={href}>{children}</a>;
  };
});

const LOCK_LABEL = "Not available on dealer's plan";

function metric(current: number, changePercent = 0) {
  return { current, previous: current, changePercent };
}

const BASE_STATS = {
  traffic: metric(900, 5),
  inquiries: metric(30, -2),
  clicks: {
    amsoil: metric(1),
    internal: metric(2),
    social: metric(3),
    external: metric(4),
  },
  period: {
    type: '30d',
    start: '2024-05-01',
    end: '2024-05-31',
    previousStart: '2024-04-01',
    previousEnd: '2024-04-30',
  },
};

function okResponse(body: unknown): Response {
  return { ok: true, status: 200, json: async () => body } as Response;
}

function errResponse(body: unknown, status = 403): Response {
  return { ok: false, status, json: async () => body } as Response;
}

describe('PerformanceMetrics', () => {
  const realFetch = global.fetch;

  afterEach(() => {
    global.fetch = realFetch;
    jest.clearAllMocks();
  });

  it('shows no admin note and unlocked metrics for a normal dealer', async () => {
    global.fetch = jest.fn().mockResolvedValue(okResponse(BASE_STATS)) as unknown as typeof fetch;

    render(<PerformanceMetrics />);

    await waitFor(() => {
      expect(screen.getByText('900')).toBeInTheDocument();
    });
    expect(screen.queryByText(/Admin view/i)).not.toBeInTheDocument();
    expect(screen.queryByLabelText(LOCK_LABEL)).not.toBeInTheDocument();
  });

  it('renders the amber admin note and locked metrics when adminBypass is present', async () => {
    global.fetch = jest
      .fn()
      .mockResolvedValue(okResponse({ ...BASE_STATS, adminBypass: { dealerTier: 'starter' } })) as unknown as typeof fetch;

    render(<PerformanceMetrics />);

    await waitFor(() => {
      expect(screen.getByText(/Admin view/i)).toBeInTheDocument();
    });
    // Note names the dealer's tier.
    expect(screen.getByText(/starter plan/i)).toBeInTheDocument();
    // Both MetricCards render their lock affordance.
    expect(screen.getAllByLabelText(LOCK_LABEL).length).toBe(2);
  });

  it('renders the upgrade prompt instead of metrics when error is upgrade_required', async () => {
    global.fetch = jest
      .fn()
      .mockResolvedValue(errResponse({ error: 'upgrade_required' })) as unknown as typeof fetch;

    render(<PerformanceMetrics />);

    await waitFor(() => {
      expect(screen.getByText(/Upgrade to Enhanced/i)).toBeInTheDocument();
    });
    // No metric grid / admin note in the upgrade path.
    expect(screen.queryByText(/Admin view/i)).not.toBeInTheDocument();
  });
});
