import React from 'react';
import { render, screen, waitFor } from '@testing-library/react';
import { MemoryRouter } from 'react-router-dom';
import { ThemeProvider } from 'styled-components';
import Header2 from './Header2';
import { AuthContext } from '../../contexts/AuthContext';
import { AccountContext } from '../../contexts/AccountContext';
import { resetSubscriptionCache } from '../../hooks/useSubscription';

const mockGet = jest.fn();
const mockPost = jest.fn();

jest.mock('../../../axiosApi', () => ({
  axiosInstance: {
    get: (...args: unknown[]) => mockGet(...args),
    post: (...args: unknown[]) => mockPost(...args),
    defaults: { headers: { common: {} as Record<string, string | null> } },
  },
  applyAccessToken: jest.fn(),
}));

jest.mock('../../utils/revenueCat', () => ({
  logOutRevenueCat: () => Promise.resolve(),
}));

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

const renderHeader = (props: { onOpenConversations?: () => void } = {}) =>
  render(
    <MemoryRouter>
      <ThemeProvider theme={theme as never}>
        <AuthContext.Provider
          value={{
            authenticated: true,
            setAuthentication: jest.fn(),
            needsNewPassword: false,
            setNeedsNewPassword: jest.fn(),
            loading: false,
          }}
        >
          <AccountContext.Provider value={{ account: undefined, setAccount: jest.fn() }}>
            <Header2 {...props} />
          </AccountContext.Provider>
        </AuthContext.Provider>
      </ThemeProvider>
    </MemoryRouter>
  );

const subscriptionWithRag = (rag: boolean) => ({
  data: {
    plan: {
      slug: rag ? 'pro' : 'standard',
      name: rag ? 'Pro' : 'Standard',
      features: {
        text_generation: true,
        image_generation: rag,
        rag,
        all_future_features: false,
      },
    },
    status: 'active',
    source: 'stripe',
    needs_checkout: false,
    stripe_subscription_id: 'sub_1',
    usage: {},
  },
});

describe('Header2 (#81 subscription-aware Documents nav link)', () => {
  beforeEach(() => {
    mockGet.mockReset();
    mockPost.mockReset();
    resetSubscriptionCache();
  });

  it('hides the Documents link while the plan does not include RAG', async () => {
    mockGet.mockResolvedValue(subscriptionWithRag(false));

    renderHeader();

    await waitFor(() => expect(mockGet).toHaveBeenCalledWith('/monetization/subscription/'));
    expect(screen.queryByText('Documents')).not.toBeInTheDocument();
  });

  it('shows the Documents link once the plan includes RAG', async () => {
    mockGet.mockResolvedValue(subscriptionWithRag(true));

    renderHeader();

    // Desktop nav + mobile dropdown both render a "Documents" link.
    expect(await screen.findAllByText('Documents')).toHaveLength(2);
  });
});

describe('Header2 (#87 conversations toggle beside logo)', () => {
  beforeEach(() => {
    mockGet.mockReset();
    mockPost.mockReset();
    resetSubscriptionCache();
    mockGet.mockResolvedValue(subscriptionWithRag(false));
  });

  it('does not render conversations toggle when callback is omitted', () => {
    renderHeader();
    expect(screen.queryByRole('button', { name: /open conversations/i })).not.toBeInTheDocument();
  });

  it('renders conversations toggle next to brand when callback is provided', () => {
    const onOpenConversations = jest.fn();
    renderHeader({ onOpenConversations });

    // Mobile-only via CSS (display:none in jsdom desktop width); query by aria-label.
    const toggle = screen.getByLabelText('Open conversations');
    expect(toggle).toBeInTheDocument();
    expect(screen.getByText('Hesychia')).toBeInTheDocument();
    toggle.click();
    expect(onOpenConversations).toHaveBeenCalledTimes(1);
  });
});
