import React from 'react';
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';
import DeathwatchRoller from '../components/DeathwatchRoller';

describe('DeathwatchRoller reset', () => {
  beforeEach(() => {
    localStorage.clear();
    fetch.mockImplementation(() => Promise.resolve({
      ok: true,
      status: 200,
      json: () => Promise.resolve([]),
    }));
  });

  test('reset clears pending combat flow and returns the roller to idle', async () => {
    render(<DeathwatchRoller authedPlayer="test-player" />);

    fireEvent.click(screen.getByLabelText(/Enable Manual Rolls/i));
    fireEvent.change(screen.getByPlaceholderText('e.g., 45'), { target: { value: '1' } });
    fireEvent.click(screen.getByRole('button', { name: 'Roll' }));

    expect(await screen.findByText('Incoming Attack!')).toBeInTheDocument();
    expect(screen.getByText(/Phase:/).parentElement).toHaveTextContent('defense');

    const tracker = screen.getByText('Enemy Wounds Tracker').closest('div').parentElement;
    fireEvent.click(within(tracker).getByRole('button', { name: 'Reset' }));

    await waitFor(() => {
      expect(screen.queryByText('Incoming Attack!')).not.toBeInTheDocument();
      expect(screen.getByText(/Phase:/).parentElement).toHaveTextContent('idle');
      expect(screen.getByText(/Last Applied:/).parentElement).toHaveTextContent('0');
    });
  });
});
