/**
 * Tests for Optimizer ContentSelector
 */
import { render, screen, waitFor, fireEvent } from '@testing-library/react';
import { BrowserRouter } from 'react-router';
import ContentSelector from '../ContentSelector';
import { optimizerApi } from '../../../api/optimizer.api';
import { fetchContent } from '../../../services/api';

vi.mock('../../../api/optimizer.api');
vi.mock('../../../services/api');
vi.mock('../../../store/sectorStore', () => ({
  useSectorStore: () => ({ activeSector: { id: 1, name: 'Test Sector' } }),
}));
vi.mock('../../../store/pageSizeStore', () => ({
  usePageSizeStore: () => ({ pageSize: 10 }),
}));
vi.mock('../../../components/ui/toast/ToastContainer', () => ({
  useToast: () => ({
    success: vi.fn(),
    error: vi.fn(),
  }),
}));

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

  it('renders content selector title', () => {
    (fetchContent as any).mockResolvedValue({ results: [], count: 0 });
    
    render(
      <BrowserRouter>
        <ContentSelector />
      </BrowserRouter>
    );
    
    expect(screen.getByText('Optimize Content')).toBeInTheDocument();
  });

  it('displays content items with checkboxes', async () => {
    (fetchContent as any).mockResolvedValue({
      results: [
        { id: 1, title: 'Test Content', source: 'igny8', sync_status: 'native', optimizer_version: 0 },
      ],
      count: 1,
    });
    
    render(
      <BrowserRouter>
        <ContentSelector />
      </BrowserRouter>
    );
    
    await waitFor(() => {
      expect(screen.getByText('Test Content')).toBeInTheDocument();
    });
  });

  it('calls optimizer API when Optimize button is clicked', async () => {
    (fetchContent as any).mockResolvedValue({
      results: [
        { id: 1, title: 'Test Content', source: 'igny8', sync_status: 'native', optimizer_version: 0 },
      ],
      count: 1,
    });
    
    (optimizerApi.optimize as any).mockResolvedValue({
      content_id: 1,
      optimizer_version: 1,
      scores_before: { overall_score: 50 },
      scores_after: { overall_score: 75 },
      task_id: 1,
      success: true,
    });
    
    render(
      <BrowserRouter>
        <ContentSelector />
      </BrowserRouter>
    );
    
    await waitFor(() => {
      const optimizeButton = screen.getByText('Optimize');
      fireEvent.click(optimizeButton);
    });
    
    await waitFor(() => {
      expect(optimizerApi.optimize).toHaveBeenCalledWith(1, 'auto');
    });
  });

  it('handles batch optimization', async () => {
    (fetchContent as any).mockResolvedValue({
      results: [
        { id: 1, title: 'Content 1', source: 'igny8', sync_status: 'native', optimizer_version: 0 },
        { id: 2, title: 'Content 2', source: 'igny8', sync_status: 'native', optimizer_version: 0 },
      ],
      count: 2,
    });
    
    (optimizerApi.batchOptimize as any).mockResolvedValue({
      results: [{ content_id: 1, success: true }, { content_id: 2, success: true }],
      errors: [],
      total: 2,
      succeeded: 2,
      failed: 0,
    });
    
    render(
      <BrowserRouter>
        <ContentSelector />
      </BrowserRouter>
    );
    
    await waitFor(() => {
      const checkboxes = screen.getAllByRole('checkbox');
      // Click first two checkboxes (skip the select-all checkbox)
      fireEvent.click(checkboxes[1]);
      fireEvent.click(checkboxes[2]);
      
      const batchButton = screen.getByText(/Optimize Selected/);
      fireEvent.click(batchButton);
    });
    
    await waitFor(() => {
      expect(optimizerApi.batchOptimize).toHaveBeenCalled();
    });
  });

  it('filters content by source', async () => {
    (fetchContent as any).mockResolvedValue({
      results: [
        { id: 1, title: 'IGNY8 Content', source: 'igny8', sync_status: 'native' },
        { id: 2, title: 'WordPress Content', source: 'wordpress', sync_status: 'synced' },
      ],
      count: 2,
    });
    
    render(
      <BrowserRouter>
        <ContentSelector />
      </BrowserRouter>
    );
    
    await waitFor(() => {
      const wordpressButton = screen.getByText('WordPress').closest('button');
      if (wordpressButton) {
        fireEvent.click(wordpressButton);
      }
    });
  });
});

