import React from 'react';
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, act, fireEvent } from '@testing-library/react';
import { ToastContainer, useToast } from '@/components/ui/Toast';
import { useUIStore } from '@/store/uiStore';

describe('Toast', () => {
  beforeEach(() => {
    useUIStore.setState({ toasts: [] });
  });

  it('renders toast container', () => {
    render(<ToastContainer />);
    expect(screen.getByTestId('toast-container')).toBeInTheDocument();
  });

  it('displays toast when added to store', () => {
    useUIStore.setState({
      toasts: [{ id: '1', type: 'success', message: 'Erfolgreich gespeichert' }],
    });
    render(<ToastContainer />);
    expect(screen.getByText('Erfolgreich gespeichert')).toBeInTheDocument();
  });

  it('toast has role=alert for accessibility', () => {
    useUIStore.setState({
      toasts: [{ id: '1', type: 'error', message: 'Fehler aufgetreten' }],
    });
    render(<ToastContainer />);
    expect(screen.getByRole('alert')).toHaveTextContent('Fehler aufgetreten');
  });

  it('auto-dismisses after duration', () => {
    vi.useFakeTimers();
    useUIStore.setState({
      toasts: [{ id: '1', type: 'info', message: 'Info', duration: 1000 }],
    });
    render(<ToastContainer />);
    expect(screen.getByText('Info')).toBeInTheDocument();
    act(() => {
      vi.advanceTimersByTime(1000);
    });
    expect(screen.queryByText('Info')).not.toBeInTheDocument();
    vi.useRealTimers();
  });

  it('can be manually dismissed', () => {
    useUIStore.setState({
      toasts: [{ id: '1', type: 'warning', message: 'Warnung' }],
    });
    render(<ToastContainer />);
    const closeBtn = screen.getByLabelText('Close notification');
    fireEvent.click(closeBtn);
    expect(screen.queryByText('Warnung')).not.toBeInTheDocument();
  });
});
