import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
import { Heart } from '@remotion/shapes';
import { useCallback, useEffect, useState } from 'react';
import { REMOTION_PRO_ORIGIN } from './config';
import { formatLikeCount, getLikedIds, removeLikedId, saveLikedId, } from './prompt-helpers';
import { useHeartAnimation } from './use-heart-animation';
export const CardLikeButton = ({ submissionId, initialLikeCount }) => {
    const [liked, setLiked] = useState(false);
    const [likeCount, setLikeCount] = useState(initialLikeCount);
    const { scale, roundness, animate } = useHeartAnimation();
    useEffect(() => {
        setLiked(getLikedIds().has(submissionId));
    }, [submissionId]);
    const onClick = useCallback(async (e) => {
        e.preventDefault();
        if (liked) {
            setLiked(false);
            setLikeCount((c) => c - 1);
            removeLikedId(submissionId);
            try {
                await fetch(`${REMOTION_PRO_ORIGIN}/api/prompts/unlike`, {
                    method: 'POST',
                    headers: { 'content-type': 'application/json' },
                    body: JSON.stringify({ submissionId }),
                });
            }
            catch (_a) {
                // Optimistic
            }
        }
        else {
            animate();
            setLiked(true);
            setLikeCount((c) => c + 1);
            saveLikedId(submissionId);
            try {
                await fetch(`${REMOTION_PRO_ORIGIN}/api/prompts/like`, {
                    method: 'POST',
                    headers: { 'content-type': 'application/json' },
                    body: JSON.stringify({ submissionId }),
                });
            }
            catch (_b) {
                // Optimistic
            }
        }
    }, [liked, submissionId, animate]);
    return (_jsxs("button", { onClick: onClick, className: "flex items-center bg-transparent border-none cursor-pointer p-0", type: "button", children: [_jsx(Heart, { height: 16, fill: liked ? 'var(--color-brand)' : 'none', stroke: liked ? 'var(--color-brand)' : 'var(--text-color)', strokeWidth: 2, bottomRoundnessAdjustment: roundness, style: { transform: `scale(${scale})`, marginTop: 2 } }), _jsx("span", { className: "font-brand font-medium data-[liked=true]:text-brand data-[liked=false]:text-text", "data-liked": liked, style: { marginLeft: 8, flex: 1 }, children: formatLikeCount(likeCount) })] }));
};
