import React, { useState, useEffect } from 'react';

const LikeButton = () => {
  const [likes, setLikes] = useState(0);
  const [serverLikes, setServerLikes] = useState(0);
  const [error, setError] = useState(null);
  const [requestId, setRequestId] = useState(0);
  const [debounceTimeout, setDebounceTimeout] = useState(null);

  useEffect(() => {
    const fetchLikes = async () => {
      try {
        const id = Date.now();
        setRequestId(id);
        const response = await fetch('/api/like');
        const data = await response.json();
        if (requestId === id) {
          setServerLikes(data.likes);
        }
        setError(null);
      } catch (error) {
        setError(error);
      }
    };

    const debouncedFetchLikes = () => {
      if (debounceTimeout) {
        clearTimeout(debounceTimeout);
      }

      setDebounceTimeout(
        setTimeout(() => {
          fetchLikes();
        }, 500)
      );
    };

    debouncedFetchLikes();