import { afterEach, describe, expect, test, vi } from 'vitest';
import { render, screen, fireEvent } from '@testing-library/svelte';
import { readable } from 'svelte/store';

const cacheState = vi.hoisted(() => ({
  data: { track_ids: ['t1'] as string[], album_ids: [] as string[], artist_ids: [] as string[] }
}));

vi.mock('$lib/api/likes', () => ({
  createLikedIdsQuery: () => readable({ data: cacheState.data, isPending: false, isError: false }),
  likeEntity: vi.fn().mockResolvedValue(undefined),
  unlikeEntity: vi.fn().mockResolvedValue(undefined)
}));

import LikeButton from './LikeButton.svelte';
import { likeEntity, unlikeEntity } from '$lib/api/likes';

afterEach(() => {
  vi.clearAllMocks();
  cacheState.data = { track_ids: ['t1'], album_ids: [], artist_ids: [] };
});

describe('LikeButton', () => {
  test('renders filled heart when track id IS in the set', () => {
    render(LikeButton, { props: { entityType: 'track', entityId: 't1' } });
    const btn = screen.getByRole('button', { name: /unlike/i });
    expect(btn.getAttribute('aria-pressed')).toBe('true');
  });

  test('renders empty heart when track id is NOT in the set', () => {
    render(LikeButton, { props: { entityType: 'track', entityId: 't2' } });
    const btn = screen.getByRole('button', { name: /like/i });
    expect(btn.getAttribute('aria-pressed')).toBe('false');
  });

  test('click on empty heart calls likeEntity', async () => {
    render(LikeButton, { props: { entityType: 'track', entityId: 't2' } });
    await fireEvent.click(screen.getByRole('button', { name: /like/i }));
    expect(likeEntity).toHaveBeenCalledWith(expect.anything(), 'track', 't2');
  });

  test('click on filled heart calls unlikeEntity', async () => {
    render(LikeButton, { props: { entityType: 'track', entityId: 't1' } });
    await fireEvent.click(screen.getByRole('button', { name: /unlike/i }));
    expect(unlikeEntity).toHaveBeenCalledWith(expect.anything(), 'track', 't1');
  });

  test('click stops propagation', async () => {
    const parentClick = vi.fn();
    const { container } = render(LikeButton, { props: { entityType: 'track', entityId: 't2' } });
    const wrapper = container.parentElement!;
    wrapper.addEventListener('click', parentClick);
    await fireEvent.click(screen.getByRole('button', { name: /like/i }));
    expect(parentClick).not.toHaveBeenCalled();
  });

  test('album entityType reads from album_ids set', () => {
    cacheState.data = { track_ids: [], album_ids: ['al1'], artist_ids: [] };
    render(LikeButton, { props: { entityType: 'album', entityId: 'al1' } });
    expect(screen.getByRole('button', { name: /unlike/i }).getAttribute('aria-pressed')).toBe('true');
  });
});
