import React from 'react';
import { fireEvent, render, screen } from '@testing-library/react';
import { vi } from 'vitest';
import { ToastProvider, useToast } from '../ToastHost';

function ToastTestHarness({ onAction }: { onAction: () => void }) {
  const toast = useToast();

  React.useEffect(() => {
    toast.push({
      text: 'Update ready',
      type: 'info',
      durationMs: 0,
      action: {
        label: 'Reload',
        onClick: onAction,
      },
    });
  }, [toast, onAction]);

  return null;
}

describe('ToastHost', () => {
  it('renders action toasts and dismisses after action click', async () => {
    const onAction = vi.fn();

    render(
      <ToastProvider>
        <ToastTestHarness onAction={onAction} />
      </ToastProvider>
    );

    expect(screen.getByText('Update ready')).toBeInTheDocument();
    const button = screen.getByRole('button', { name: 'Reload' });

    fireEvent.click(button);

    expect(onAction).toHaveBeenCalledTimes(1);
    expect(screen.queryByText('Update ready')).not.toBeInTheDocument();
  });
});
