import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, expect, it, vi } from 'vitest';

vi.mock('@/lib/analytics-api', () => ({
  analyticsApi: { getProjectAiAdvice: vi.fn().mockReturnValue(new Promise(() => {})) },
}));

vi.mock('@/lib/api-client', () => ({
  ApiError: class extends Error { status = 500; },
}));

vi.mock('@/lib/auth-store', () => ({
  useAuthStore: (selector: (s: { user: null }) => unknown) => selector({ user: null }),
}));

import { ProjectAiAdviceCard } from '../project-ai-advice-card';

function wrapper({ children }: { children: React.ReactNode }) {
  const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });
  return <QueryClientProvider client={qc}>{children}</QueryClientProvider>;
}

describe('ProjectAiAdviceCard', () => {
  it('renders trigger button initially', () => {
    render(<ProjectAiAdviceCard projectId="p1" />, { wrapper });
    expect(screen.getByText('Xem phân tích AI về dự án')).toBeInTheDocument();
  });

  it('shows loading state when clicked', async () => {
    const user = userEvent.setup();
    render(<ProjectAiAdviceCard projectId="p1" />, { wrapper });
    await user.click(screen.getByText('Xem phân tích AI về dự án'));
    expect(screen.getByText(/AI đang phân tích/)).toBeInTheDocument();
  });
});
