import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/svelte';
import HistoryRow from './HistoryRow.svelte';
import type { HistoryEvent } from '$lib/api/history';
import { makeTrack } from '$test-utils/fixtures/track';

const playQueue = vi.fn();

vi.mock('$lib/player/store.svelte', () => ({
  playQueue: (...args: unknown[]) => playQueue(...args)
}));

const sampleTrack = makeTrack({
  title: 'Song Title',
  album_title: 'Album',
  artist_name: 'Artist Name'
});

const sampleEvent: HistoryEvent = {
  id: 'event-1',
  played_at: new Date(Date.now() - 10 * 60 * 1000).toISOString(),
  track: sampleTrack
};

describe('HistoryRow', () => {
  beforeEach(() => {
    playQueue.mockClear();
  });

  it('renders track title, artist, and album', () => {
    render(HistoryRow, { props: { event: sampleEvent } });
    expect(screen.getByText('Song Title')).toBeInTheDocument();
    expect(screen.getByText(/Artist Name/)).toBeInTheDocument();
    expect(screen.getByText(/Album/)).toBeInTheDocument();
  });

  it('clicking the row calls playQueue([track], 0)', async () => {
    render(HistoryRow, { props: { event: sampleEvent } });
    const row = screen.getByRole('button', { name: /play song title/i });
    await fireEvent.click(row);
    expect(playQueue).toHaveBeenCalledWith([sampleTrack], 0);
  });

  it('renders a relative timestamp for events under 1 hour ago', () => {
    render(HistoryRow, { props: { event: sampleEvent } });
    expect(screen.getByText(/\d+m ago/)).toBeInTheDocument();
  });
});
