import React from 'react';
import { render, screen, waitFor, fireEvent, cleanup, act } from '@testing-library/react';
import App from '../App';

describe('Bulk-delete-all button dev feature', () => {
  const orig = process.env.REACT_APP_DEV_TOOLS;

  afterEach(() => {
    cleanup();
    if (orig === undefined) delete process.env.REACT_APP_DEV_TOOLS;
    else process.env.REACT_APP_DEV_TOOLS = orig;
  });

  async function renderAndCreateCampaign() {
    window.history.replaceState({}, '', '/');
    global.alert = jest.fn();
    global.window.open = jest.fn();
    render(<App />);
    await waitFor(() => screen.getByRole('button', { name: /Create Campaign/i }));
    await act(async () => {
      fireEvent.click(screen.getByRole('button', { name: /Create Campaign/i }));
    });
    await waitFor(() => screen.getByLabelText(/Campaign Name/i));
    await act(async () => {
      fireEvent.change(screen.getByLabelText(/Campaign Name/i), { target: { value: 'Gate Render Test' } });
      fireEvent.click(screen.getByRole('button', { name: /^Create$/i }));
      await new Promise(r => setTimeout(r, 200));
    });
  }

  test('dev: button present when DEV_TOOLS=1 and campaigns exist', async () => {
    process.env.REACT_APP_DEV_TOOLS = '1';
    await renderAndCreateCampaign();
    await waitFor(() => screen.getByText(/Delete All Campaigns/i), { timeout: 5000 });
  });
});
