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

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

import { trackEvent } from '@/lib/analytics';
import { BYOK_LINK_CLICKED, UPGRADE_PROMPT_CLICKED } from '@/lib/event-catalog';
import type { PageProps } from '@/types';

import FirstRewriteBridge from './FirstRewriteBridge';

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

const mockedUsePage = vi.mocked(usePage);
const mockedTrackEvent = vi.mocked(trackEvent);

/**
 * Build a minimal usePage().props payload. Only the fields FirstRewriteBridge
 * reads are typed here; cast through unknown so we don't have to satisfy the
 * full PageProps surface in every case.
 */
function mockProps(overrides: {
  bundledRemaining?: number | null;
  plan?: string | null;
  trialActive?: boolean;
  billing?: boolean;
}) {
  const { bundledRemaining = null, plan = null, trialActive = false, billing = true } = overrides;
  mockedUsePage.mockReturnValue({
    props: {
      ai_status: bundledRemaining === undefined ? null : { bundled_remaining: bundledRemaining },
      plan,
      trial: { active: trialActive },
      features: { billing },
    },
  } as unknown as ReturnType<typeof usePage<PageProps>>);
}

describe('FirstRewriteBridge', () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  it('shows the bundled-credits CTA into the Action Queue when credits remain', () => {
    mockProps({ bundledRemaining: 5, plan: 'pro' });
    render(<FirstRewriteBridge siteId={'42'} />);

    const cta = screen.getByRole('link', {
      name: /generate your first ai rewrite from your action queue/i,
    });
    // W-A: the primary first-rewrite CTA now lands on the Action Queue.
    expect(cta).toHaveAttribute('href', '/sites/42/opportunity-map');
    // Pluralized credit count surfaced.
    expect(screen.getByText(/5 bundled AI drafts/i)).toBeInTheDocument();
  });

  it('shows upgrade-to-Pro for a trial user out of credits with billing enabled', () => {
    mockProps({ bundledRemaining: 0, plan: null, trialActive: true, billing: true });
    render(<FirstRewriteBridge siteId={'7'} />);

    const cta = screen.getByRole('link', { name: /upgrade to pro/i });
    expect(cta.getAttribute('href')).toContain('/billing/plans');
    expect(screen.queryByRole('link', { name: /openai key/i })).not.toBeInTheDocument();
  });

  it('shows upgrade-to-Pro for a free user out of credits with billing enabled', () => {
    mockProps({ bundledRemaining: 0, plan: null, trialActive: false, billing: true });
    render(<FirstRewriteBridge siteId={'9'} />);

    expect(
      screen.getByRole('link', { name: /upgrade to pro — 14-day free trial/i }),
    ).toBeInTheDocument();
  });

  it('shows the BYOK key CTA when there are no credits and no Pro path (billing off)', () => {
    mockProps({ bundledRemaining: null, plan: null, trialActive: false, billing: false });
    render(<FirstRewriteBridge siteId={'3'} />);

    const cta = screen.getByRole('link', { name: /set up your openai key to start rewriting/i });
    expect(cta).toHaveAttribute('href', '/settings/ai');
  });

  it('shows the BYOK key CTA for a Pro user out of bundled credits', () => {
    mockProps({ bundledRemaining: 0, plan: 'pro', trialActive: false, billing: true });
    render(<FirstRewriteBridge siteId={'11'} />);

    expect(
      screen.getByRole('link', { name: /set up your openai key to start rewriting/i }),
    ).toBeInTheDocument();
  });

  it('fires UPGRADE_PROMPT_CLICKED from the dashboard surface on upgrade click', () => {
    mockProps({ bundledRemaining: 0, plan: null, trialActive: false, billing: true });
    render(<FirstRewriteBridge siteId={'9'} />);

    screen.getByRole('link', { name: /upgrade to pro — 14-day free trial/i }).click();
    expect(mockedTrackEvent).toHaveBeenCalledWith(
      UPGRADE_PROMPT_CLICKED,
      expect.objectContaining({ surface: 'dashboard', source: 'first_rewrite_bridge_free', site_id: '9' }),
    );
  });

  it('fires BYOK_LINK_CLICKED with plan tier on the BYOK fallback click', () => {
    mockProps({ bundledRemaining: 0, plan: 'pro', trialActive: false, billing: true });
    render(<FirstRewriteBridge siteId={'11'} />);

    screen.getByRole('link', { name: /set up your openai key to start rewriting/i }).click();
    expect(mockedTrackEvent).toHaveBeenCalledWith(
      BYOK_LINK_CLICKED,
      expect.objectContaining({ site_id: '11', plan_tier: 'pro', source: 'byok_only_fallback' }),
    );
  });
});
