// @vitest-environment jsdom
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter } from 'react-router-dom';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { AppContext, type AppContextValue } from '../context/AppContext';
import { ScreenerView } from './ScreenerView';

vi.mock('../lib/authSession', () => ({
  getPlatformAccessToken: vi.fn(async () => 'test-token'),
}));

vi.mock('../lib/runtime', () => ({
  tradingRuntime: { tradingApiUrl: 'https://trading.test' },
}));

const appContext: AppContextValue = {
  botState: {
    settings: { isAlgoEnabled: true },
    symbols: {},
    health: { tradingLoopHealthy: true, reconciliationLoopHealthy: true, capitalInvariantViolations: 0 },
    alerts: [],
    positions: [],
    orders: [],
    history: [],
    uptime: 0,
  } as any,
  socket: null,
  connected: true,
  activeSymbol: '',
  setActiveSymbol: vi.fn(),
  isAdmin: false,
  user: { id: 'u1' },
  profile: {},
  showBacktestTab: false,
  showMarketplaceTab: false,
  handleSignOut: vi.fn(),
};

function renderScreener() {
  return render(
    <AppContext.Provider value={appContext}>
      <MemoryRouter>
        <ScreenerView />
      </MemoryRouter>
    </AppContext.Provider>,
  );
}

describe('ScreenerView sector filters', () => {
  beforeEach(() => {
    vi.spyOn(globalThis, 'fetch').mockResolvedValue({
      ok: true,
      json: async () => ({ results: [] }),
    } as Response);
  });

  it('visually highlights sectors selected from the More sectors dropdown', async () => {
    const user = userEvent.setup();
    renderScreener();

    const moreSectors = screen.getByLabelText('More sectors');
    await waitFor(() => expect(globalThis.fetch).toHaveBeenCalledTimes(1));

    await user.selectOptions(moreSectors, 'Energy');

    expect(moreSectors).toHaveValue('Energy');
    expect(moreSectors).toHaveStyle({
      background: '#EFF6FF',
      color: '#2563EB',
      fontWeight: '700',
    });
    await waitFor(() => expect(globalThis.fetch).toHaveBeenCalledTimes(2));
    expect(String((globalThis.fetch as any).mock.calls[1][0])).toContain('sector=Energy');
  });
});
