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

import { usePage } from '@inertiajs/react';

import { FeatureGateTeaser } from './FeatureGateTeaser';

vi.mock('@/lib/analytics', () => ({ trackEvent: vi.fn() }));

vi.mock('@inertiajs/react', async () => {
  const actual = await vi.importActual('@inertiajs/react');
  return {
    ...actual,
    usePage: vi.fn(),
    Link: ({
      children,
      href,
      onClick,
      ...props
    }: {
      children: React.ReactNode;
      href: string;
      onClick?: () => void;
    }) => (
      <a href={href} onClick={onClick} {...props}>
        {children}
      </a>
    ),
  };
});

function mockUsePage(billingEnabled: boolean) {
  vi.mocked(usePage).mockReturnValue({
    props: {
      features: {
        billing: billingEnabled,
        socialAuth: false,
        emailVerification: false,
        apiTokens: false,
        userSettings: false,
        notifications: false,
        onboarding: false,
        apiDocs: false,
        twoFactor: false,
        webhooks: false,
        admin: false,
      },
      auth: { user: null },
      errors: {},
      flash: {},
    },
    url: 'http://localhost/test',
    component: 'Test',
    version: null,
    rememberedState: {},
  } as unknown as ReturnType<typeof usePage>);
}

describe('FeatureGateTeaser', () => {
  beforeEach(async () => {
    const { trackEvent } = await import('@/lib/analytics');
    vi.mocked(trackEvent).mockClear();
  });

  it('renders null when billing is disabled', () => {
    mockUsePage(false);

    const { container } = render(
      <FeatureGateTeaser
        featureName="Traffic Alerts"
        description="Get notified of traffic drops."
      />,
    );

    expect(container.firstChild).toBeNull();
  });

  it('does not fire FEATURE_GATE_TEASER_SHOWN when billing is disabled', async () => {
    mockUsePage(false);

    const { trackEvent } = await import('@/lib/analytics');
    render(
      <FeatureGateTeaser
        featureName="Traffic Alerts"
        description="Get notified of traffic drops."
      />,
    );

    expect(trackEvent).not.toHaveBeenCalled();
  });

  it('fires FEATURE_GATE_TEASER_SHOWN on mount when billing is enabled', async () => {
    mockUsePage(true);

    const { trackEvent } = await import('@/lib/analytics');
    render(
      <FeatureGateTeaser
        featureName="Traffic Alerts"
        description="Get notified of traffic drops."
      />,
    );

    expect(trackEvent).toHaveBeenCalledWith(
      'feature_gate_teaser_shown',
      expect.objectContaining({
        feature_name: 'Traffic Alerts',
      }),
    );
  });

  it('fires FEATURE_GATE_UPGRADE_CLICKED on CTA click', async () => {
    mockUsePage(true);

    const { trackEvent } = await import('@/lib/analytics');
    render(
      <FeatureGateTeaser
        featureName="Traffic Alerts"
        description="Get notified of traffic drops."
      />,
    );

    vi.mocked(trackEvent).mockClear();

    const link = screen.getByRole('link');
    fireEvent.click(link);

    expect(trackEvent).toHaveBeenCalledWith(
      'feature_gate_upgrade_clicked',
      expect.objectContaining({
        feature_name: 'Traffic Alerts',
      }),
    );
  });

  it('renders the default ctaLabel when none is provided', () => {
    mockUsePage(true);

    render(
      <FeatureGateTeaser
        featureName="Traffic Alerts"
        description="Get notified of traffic drops."
      />,
    );

    expect(screen.getByRole('button', { name: /unlock with pro/i })).toBeInTheDocument();
  });

  it('renders a custom ctaLabel when provided', () => {
    mockUsePage(true);

    render(
      <FeatureGateTeaser
        featureName="Traffic Alerts"
        description="Get notified of traffic drops."
        ctaLabel="Upgrade Now"
      />,
    );

    expect(screen.getByRole('button', { name: /upgrade now/i })).toBeInTheDocument();
  });

  it('renders feature-specific ctaLabel for ROI Tracking (ONBOARD-006)', () => {
    mockUsePage(true);

    render(
      <FeatureGateTeaser
        featureName="ROI Tracking"
        description="Track ROI."
        ctaLabel="Unlock ROI Tracking"
      />,
    );

    expect(screen.getByRole('button', { name: /unlock roi tracking/i })).toBeInTheDocument();
  });

  it('renders feature-specific ctaLabel for Traffic Anomaly Alerts (ONBOARD-006)', () => {
    mockUsePage(true);

    render(
      <FeatureGateTeaser
        featureName="Traffic Anomaly Alerts"
        description="Get notified of anomalies."
        ctaLabel="Unlock Anomaly Alerts"
      />,
    );

    expect(screen.getByRole('button', { name: /unlock anomaly alerts/i })).toBeInTheDocument();
  });
});
