// @vitest-environment jsdom
import { describe, expect, it, vi } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { BacktestRunnerPanel } from './BacktestRunnerPanel';
import type { BacktestResult } from '../types';

const mockRunBacktestApi = vi.fn();

vi.mock('../api', () => ({
    runBacktestApi: (...args: any[]) => mockRunBacktestApi(...args)
}));

vi.mock('./BacktestConfigurator', () => ({
    BacktestConfigurator: ({ onRun, running }: any) => (
        <button
            disabled={running}
            onClick={() => onRun({
                mode: 'backtest',
                symbols: ['BTC/USDT'],
                timeframe: '15m',
                dateRange: {
                    from: '2025-01-01T00:00:00.000Z',
                    to: '2025-02-01T00:00:00.000Z'
                },
                dataSource: {
                    type: 'csv',
                    payload: 'symbol,timeframe,timestamp,open,high,low,close,volume'
                }
            })}
        >
            Trigger Run
        </button>
    )
}));

const mockResult: BacktestResult = {
    mode: 'backtest',
    trades: [],
    summary: {
        netPnlUsd: 12.34,
        winRate: 60,
        maxDrawdownPct: 4.2,
        sharpe: 1.22,
        totalTrades: 10
    },
    timeline: [
        { timestamp: 1704067200000, equityUsd: 1000, drawdownPct: 0, cashUsd: 900, reservedUsd: 0 },
        { timestamp: 1704153600000, equityUsd: 1012.34, drawdownPct: 0.2, cashUsd: 905, reservedUsd: 0 }
    ],
    window: {
        fromTimestamp: 1704067200000,
        toTimestamp: 1704153600000,
        fromIso: '2024-01-01T00:00:00.000Z',
        toIso: '2024-01-02T00:00:00.000Z',
        timezone: 'UTC',
        includesWarmupCandles: true,
        endOfWindowPolicy: 'OPEN_AT_END'
    },
    warmup: {
        startTimestamp: 1704067200000,
        endTimestamp: 1704070800000,
        candlesRequired: { '15m': 40, '1h': 20, '4h': 21 },
        signalsIgnored: 3
    },
    openPositionsAtEnd: [],
    assumptions: {
        fillModel: 'market@candle_close',
        slippageModel: 'deterministic 5 bps',
        feeModel: 'deterministic 10 bps',
        latencyModel: 'signal@bar_close -> fill@next_bar_open',
        intraCandleModel: 'ohlc_path',
        triggerResolution: '1m trigger candles',
        warmupEnforced: true,
        deterministicReplay: true,
        replayWindow: '2024-01-01 -> 2024-01-02 (UTC)',
        endOfWindowPolicy: 'OPEN_AT_END',
        disclaimer: 'Backtests are deterministic simulations and do not guarantee live outcomes.'
    },
    diagnostics: {
        blockedRuleCounts: { TrendBiasRule: 2 },
        entryRejections: { INSUFFICIENT_CAPITAL: 1 },
        lossReasons: { STOP_LOSS: 1 },
        connectorCalls: { fetchOHLCV: 120, placeOrder: 0, getPosition: 0 }
    }
};

describe('BacktestRunnerPanel DOM', () => {
    it('runs backtest and renders assumptions + warmup metadata', async () => {
        mockRunBacktestApi.mockResolvedValue(mockResult);
        const user = userEvent.setup();

        render(
            <BacktestRunnerPanel
                strategyConfig={{ rules: [] }}
                symbols={['BTC/USDT']}
                initialCapitalUsd={1000}
            />
        );

        await user.click(screen.getByText('Trigger Run'));
        await waitFor(() => expect(mockRunBacktestApi).toHaveBeenCalledTimes(1));

        expect(screen.getByTestId('backtest-replay-controls')).toBeInTheDocument();
        expect(screen.getByTestId('backtest-assumptions-panel')).toBeInTheDocument();
        expect(screen.getByTestId('backtest-warmup-meta')).toBeInTheDocument();
        expect(screen.getByText(/signals ignored/i)).toBeInTheDocument();

        const cursorBefore = screen.getByTestId('backtest-replay-cursor').textContent || '';
        await user.click(screen.getByRole('button', { name: /step/i }));
        const cursorAfter = screen.getByTestId('backtest-replay-cursor').textContent || '';
        expect(cursorAfter).not.toEqual(cursorBefore);
        expect(mockRunBacktestApi).toHaveBeenCalledTimes(1);
    });
});
