import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, act } from '@testing-library/react';
import HoldCountdown from './HoldCountdown';

describe('HoldCountdown', () => {
  beforeEach(() => vi.useFakeTimers());
  afterEach(() => vi.useRealTimers());

  const nowSeconds = () => Math.floor(Date.now() / 1000);

  it('counts down from the server expiry', () => {
    render(<HoldCountdown expiresAt={nowSeconds() + 125} onExpired={() => {}} />);

    expect(screen.getByText(/2:05/)).toBeInTheDocument();

    act(() => { vi.advanceTimersByTime(5000); });

    expect(screen.getByText(/2:00/)).toBeInTheDocument();
  });

  /** ⭐ رزروی که در سکوت منقضی شود، اپراتور را با یک ۴۰۹ بی‌توضیح تنها می‌گذارد. */
  it('reports expiry to the parent exactly once it lapses', () => {
    const onExpired = vi.fn();
    render(<HoldCountdown expiresAt={nowSeconds() + 2} onExpired={onExpired} />);

    expect(onExpired).not.toHaveBeenCalled();

    act(() => { vi.advanceTimersByTime(3000); });

    expect(onExpired).toHaveBeenCalled();
    expect(screen.getByText('مهلت تمام شد')).toBeInTheDocument();
  });

  it('switches to the urgent style under a minute', () => {
    const { container } = render(<HoldCountdown expiresAt={nowSeconds() + 30} onExpired={() => {}} />);

    expect(container.querySelector('.badge.red')).not.toBeNull();
  });
});
