// @vitest-environment jsdom
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { VisualRuleBuilder } from './VisualRuleBuilder';

describe('VisualRuleBuilder save behavior', () => {
  afterEach(() => {
    vi.useRealTimers();
  });

  it('clears the saved message timeout when unmounted', async () => {
    const clearTimeoutSpy = vi.spyOn(globalThis, 'clearTimeout');
    const user = userEvent.setup();
    const onSave = vi.fn().mockResolvedValue(undefined);

    const { unmount } = render(<VisualRuleBuilder symbol="AAPL" onSave={onSave} />);
    await user.click(screen.getByRole('button', { name: /save strategy/i }));

    await waitFor(() => expect(screen.getByText('Strategy saved!')).toBeInTheDocument());
    unmount();

    expect(clearTimeoutSpy).toHaveBeenCalled();
    clearTimeoutSpy.mockRestore();
  });

  it('saves with Cmd/Ctrl-S inside the visual builder', async () => {
    const onSave = vi.fn().mockResolvedValue(undefined);

    render(<VisualRuleBuilder symbol="AAPL" onSave={onSave} />);
    fireEvent.keyDown(screen.getByRole('button', { name: /save strategy/i }), { key: 's', metaKey: true });

    await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1));
  });

  it('runs a visual backtest with Cmd/Ctrl-Enter inside the visual builder', () => {
    const onSave = vi.fn().mockResolvedValue(undefined);
    const onBacktest = vi.fn();

    render(<VisualRuleBuilder symbol="AAPL" onSave={onSave} onBacktest={onBacktest} />);
    fireEvent.keyDown(screen.getByRole('button', { name: /run backtest/i }), { key: 'Enter', metaKey: true });

    expect(onBacktest).toHaveBeenCalledTimes(1);
  });
});
