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

vi.mock('../tabs/MyStrategiesTab', () => ({
  MyStrategiesTab: () => <div>Strategies tab</div>,
}));

vi.mock('../tabs/SignalsTab', () => ({
  SignalsTab: () => <div>Signals tab</div>,
}));

vi.mock('../tabs/BacktestTab', () => ({
  BacktestTab: () => <div>Backtesting tab</div>,
}));

vi.mock('../components/strategy/CodeStrategyEditor', () => ({
  CodeStrategyEditor: () => <div>Code editor</div>,
}));

vi.mock('../components/strategy/VisualRuleBuilder', () => ({
  VisualRuleBuilder: ({ onBacktest }: any) => (
    <button
      type="button"
      onClick={() => onBacktest?.([{
        id: 'rule-1',
        indicator: 'RSI',
        condition: 'below',
        value: 30,
        action: 'BUY',
        quantity: 10,
        quantityType: 'shares',
      }])}
    >
      Run Backtest
    </button>
  ),
}));

vi.mock('../backtest/components/BacktestRunnerPanel', () => ({
  BacktestRunnerPanel: ({ title, strategyConfig, symbols, initialCapitalUsd }: any) => (
    <section aria-label="visual backtest runner">
      <h3>{title}</h3>
      <div>{symbols.join(',')}</div>
      <div>{initialCapitalUsd}</div>
      <pre>{JSON.stringify(strategyConfig)}</pre>
    </section>
  ),
}));

vi.mock('../lib/profileApi', () => ({
  createTradeProfile: vi.fn(),
}));

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

describe('ResearchView visual builder backtest wiring', () => {
  it('opens a backtest runner with the current visual rules', async () => {
    const user = userEvent.setup();
    render(
      <AppContext.Provider value={appContext}>
        <ResearchView />
      </AppContext.Provider>,
    );

    await user.click(screen.getByRole('button', { name: 'Visual Builder' }));
    await user.click(screen.getByRole('button', { name: 'Run Backtest' }));

    expect(screen.getByRole('region', { name: 'visual backtest runner' })).toBeInTheDocument();
    expect(screen.getByText('Backtest: Visual Strategy (AAPL)')).toBeInTheDocument();
    expect(screen.getByText('AAPL')).toBeInTheDocument();
    expect(screen.getByText('5000')).toBeInTheDocument();
    expect(screen.getByText(/"type":"visual"/)).toBeInTheDocument();
    expect(screen.getByText(/"indicator":"RSI"/)).toBeInTheDocument();
  });
});
