// @vitest-environment jsdom
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, expect, it, vi } from 'vitest';
import { MemoryRouter, Route, Routes } from 'react-router-dom';
import { ChatControl } from './ChatControl';
import { DEFAULT_BOT_STATE } from '../hooks/useWebSocket';
import type { BotState } from '../hooks/useWebSocket';

const { getPlatformAccessTokenMock } = vi.hoisted(() => ({
  getPlatformAccessTokenMock: vi.fn(),
}));

vi.mock('../lib/authSession', () => ({
  getPlatformAccessToken: getPlatformAccessTokenMock,
}));

const botStateFixture: BotState = {
  ...DEFAULT_BOT_STATE,
  positions: [
    {
      id: 'pos-1',
      symbol: 'BTC/USDT',
      side: 'BUY' as const,
      size: 0.25,
      entryPrice: 60000,
      currentPrice: 61500,
      stopLoss: 58500,
      takeProfit: 63000,
      unrealizedPnl: 375,
      unrealizedPnlPercent: 2.5,
      marketValue: 15375,
      profileId: 'p1',
      profileName: 'High Risk Scalper',
      tradeId: 'trade-1',
    }
  ],
  symbols: {},
  health: {
    ...DEFAULT_BOT_STATE.health!,
    reconciliationMismatchCount: 2,
  },
};

describe('Chat copilot route flow', () => {
  it('navigates from assistant quick links into real app routes', async () => {
    getPlatformAccessTokenMock.mockResolvedValue('token-route');
    vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
      ok: true,
      json: async () => ({
        summary: 'A Trade Plan would help manage BTC/USDT more explicitly from here.',
        reasoning: 'You already have a live holding on BTC/USDT.',
        action: 'recommend_trade_plan',
        quickLinks: [
          { kind: 'plans', label: 'Manage in Plans', mode: 'sell', symbol: 'BTC/USDT', tradeId: 'trade-1' }
        ]
      })
    } as any));

    const user = userEvent.setup();

    render(
      <MemoryRouter initialEntries={['/']}>
        <Routes>
          <Route path="/" element={<ChatControl profiles={[]} botState={botStateFixture} onApplyProfile={vi.fn()} />} />
          <Route path="/plans" element={<div>Plans route content</div>} />
          <Route path="/portfolio" element={<div>Portfolio route content</div>} />
          <Route path="/settings" element={<div>Settings route content</div>} />
        </Routes>
      </MemoryRouter>
    );

    await user.click(screen.getAllByRole('button')[0]);
    await user.type(screen.getByPlaceholderText(/Ask for a profile, holding explanation, or reconciliation help/i), 'Recommend a trade plan for BTC/USDT{enter}');

    await waitFor(() => {
      expect(screen.getByRole('button', { name: /Manage in Plans/i })).toBeInTheDocument();
    });

    await user.click(screen.getByRole('button', { name: /Manage in Plans/i }));

    await waitFor(() => {
      expect(screen.getByText('Plans route content')).toBeInTheDocument();
    });
  });
});
