# All files / src/components/user FavoriteButton.tsx

0% Statements 0/47
0% Branches 0/34
0% Functions 0/5
0% Lines 0/46

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145

     'use client';

    import { useState, useEffect } from 'react';
    import { Heart } from 'lucide-react';
    import { toast } from 'sonner';
    import { useTranslation } from 'react-i18next';
    import { favoritesService, type ContentType } from '@/services/favorites';
    import { cn } from '@/lib/utils';

    interface FavoriteButtonProps {
      contentType: ContentType;
      contentId: string;
      className?: string;
      iconClassName?: string;
      showLabel?: boolean;
      variant?: 'default' | 'icon-only';
      onToggle?: (isFavorite: boolean) => void;
    }

    export function FavoriteButton({
      contentType,
      contentId,
      className,
      iconClassName,
      showLabel = false,
      variant = 'icon-only',
      onToggle}: FavoriteButtonProps) {
      const { t } = useTranslation();
      const [isFavorite, setIsFavorite] = useState(false);
      const [isLoading, setIsLoading] = useState(false);
      const [isChecking, setIsChecking] = useState(true);

      // Check if content is favorited on mount and when props change
      useEffect(() => {
        let mounted = true;

        const checkFavorite = async () => {
          try {
            setIsChecking(true);
            const result = await favoritesService.isFavorite(contentType, contentId);
            if (mounted) {
              setIsFavorite(result);
            }
          } catch (error) {
            console.error('Error checking favorite status:', error);
            if (mounted) {
              setIsFavorite(false);
            }
          } finally {
            if (mounted) {
              setIsChecking(false);
            }
          }
        };

        checkFavorite();

        return () => {
          mounted = false;
        };
      }, [contentType, contentId]);

      const handleToggle = async (e: React.MouseEvent) => {
        e.preventDefault();
        e.stopPropagation();

        if (isLoading) return;

        // Optimistically update UI
        const newState = !isFavorite;
        setIsFavorite(newState);
        setIsLoading(true);

        try {
          // Perform the actual operation
          if (newState) {
            await favoritesService.addFavorite(contentType, contentId);
            toast.success(t('favorites.added'));
          } else {
            await favoritesService.removeFavorite(contentType, contentId);
            toast.success(t('favorites.removed'));
          }

          // Notify parent component
          onToggle?.(newState);
        } catch (error) {
          console.error('Error toggling favorite:', error);
          // Revert on error
          setIsFavorite(!newState);
          toast.error(t('favorites.error'));
        } finally {
          setIsLoading(false);
        }
      };

      if (isChecking) {
        return (
          <button
            className={cn(
              'inline-flex items-center justify-center rounded-full transition-all duration-200',
              variant === 'icon-only' ? 'h-10 w-10' : 'px-4 py-2',
              'bg-slate-800/50 text-slate-400',
              className
            )}
            disabled
          >
            <Heart className={cn('h-5 w-5 animate-pulse', iconClassName)} />
            {showLabel && variant !== 'icon-only' && (
              <span className="ml-2 text-sm">{t('common.loading')}</span>
            )}
          </button>
        );
      }

      return (
        <button
          onClick={handleToggle}
          disabled={isLoading}
          className={cn(
            'inline-flex items-center justify-center rounded-full transition-all duration-200',
            variant === 'icon-only' ? 'h-10 w-10' : 'px-4 py-2',
            isFavorite
              ? 'bg-red-600/20 text-red-500 hover:bg-red-600/30'
              : 'bg-slate-800/50 text-slate-400 hover:bg-slate-700/50 hover:text-white',
            isLoading && 'opacity-50 cursor-not-allowed',
            className
          )}
          title={isFavorite ? t('favorites.remove') : t('favorites.add')}
        >
          <Heart
            className={cn(
              'h-5 w-5 transition-all duration-200',
              isFavorite && 'fill-current',
              isLoading && 'animate-pulse',
              iconClassName
            )}
          />
          {showLabel && variant !== 'icon-only' && (
            <span className="ml-2 text-sm">
              {isFavorite ? t('favorites.inFavorites') : t('favorites.add')}
            </span>
          )}
        </button>
      );
    }