import { Heart } from 'lucide-react';
import type { FavoriteKind } from './shared';
import { useMusicFavorites } from './useMusicFavorites';

/**
 * A heart toggle for a favoritable thing (track / album / artist). Reads and writes the shared
 * favorites cache, so every heart for the same key stays in sync and flips optimistically. Stops click
 * propagation so it works inside clickable rows/cards. Renders nothing without a key.
 */
export const MusicHeart = ({
  kind,
  favKey,
  size = 18,
  className = '',
  hoverReveal = false,
}: {
  kind: FavoriteKind;
  favKey: string;
  size?: number;
  className?: string;
  /** When set, a NOT-favorited heart is hidden until the enclosing `group` is hovered/focused; a
   *  favorited (filled) heart always stays visible. Keeps dense lists uncluttered. */
  hoverReveal?: boolean;
}) => {
  const { isFavorite, toggle } = useMusicFavorites();
  if (!favKey) return null;
  const on = isFavorite(kind, favKey);
  const reveal = hoverReveal && !on ? 'opacity-0 group-hover:opacity-100 focus:opacity-100' : '';
  return (
    <button
      type="button"
      onClick={(e) => {
        e.stopPropagation();
        toggle(kind, favKey);
      }}
      title={on ? 'Remove from favorites' : 'Add to favorites'}
      aria-label={on ? 'Remove from favorites' : 'Add to favorites'}
      className={`flex cursor-pointer items-center justify-center transition-colors ${reveal} ${className}`}
    >
      <Heart size={size} className={on ? 'fill-red-500 text-red-500' : 'text-muted-foreground hover:text-foreground'} />
    </button>
  );
};
