import { afterEach, describe, expect, test, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/svelte';
import { mockQuery } from '../../../test-utils/query';

vi.mock('$lib/api/quarantine', () => ({
  createMyQuarantineQuery: vi.fn(),
  unflagTrack: vi.fn().mockResolvedValue(undefined)
}));

import HiddenPage from './+page.svelte';
import { createMyQuarantineQuery, unflagTrack } from '$lib/api/quarantine';
import type { LidarrQuarantineMineRow } from '$lib/api/types';

const baseRow: LidarrQuarantineMineRow = {
  track_id: 't1',
  reason: 'bad_rip',
  notes: 'crackles',
  created_at: new Date(Date.now() - 2 * 24 * 3_600_000).toISOString(), // 2 days ago
  track_title: 'Roygbiv',
  track_duration_ms: 200000,
  album_id: 'a1',
  album_title: 'Geogaddi',
  album_cover_art_path: null,
  artist_id: 'ar1',
  artist_name: 'Boards of Canada'
};

afterEach(() => vi.clearAllMocks());

describe('/library/hidden', () => {
  test('renders one row per quarantine with title + meta + reason pill + notes', () => {
    (createMyQuarantineQuery as ReturnType<typeof vi.fn>).mockReturnValue(mockQuery({ data: [baseRow] }));
    render(HiddenPage);
    expect(screen.getByText('Roygbiv')).toBeInTheDocument();
    expect(screen.getByText(/by boards of canada · geogaddi/i)).toBeInTheDocument();
    expect(screen.getByText('Bad rip')).toBeInTheDocument();
    expect(screen.getByText('crackles')).toBeInTheDocument();
  });

  test('un-hide button calls unflagTrack', async () => {
    (createMyQuarantineQuery as ReturnType<typeof vi.fn>).mockReturnValue(mockQuery({ data: [baseRow] }));
    render(HiddenPage);
    await fireEvent.click(screen.getByRole('button', { name: /un-hide roygbiv/i }));
    expect(unflagTrack).toHaveBeenCalledWith('t1');
  });

  test('empty state shows "Nothing hidden yet."', () => {
    (createMyQuarantineQuery as ReturnType<typeof vi.fn>).mockReturnValue(mockQuery({ data: [] }));
    render(HiddenPage);
    expect(screen.getByText(/nothing hidden yet/i)).toBeInTheDocument();
  });

  test('notes are absent when row.notes is null', () => {
    const row = { ...baseRow, notes: null };
    (createMyQuarantineQuery as ReturnType<typeof vi.fn>).mockReturnValue(mockQuery({ data: [row] }));
    render(HiddenPage);
    expect(screen.queryByText('crackles')).not.toBeInTheDocument();
  });
});
