import { useState, useOptimistic, useTransition } from 'react';

export let SHOULD_FAIL = false;

type State = {
  liked: boolean;
  count: number;
};

function fakeToggleLikeOnServer({ liked, count }: State): Promise<State> {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (SHOULD_FAIL) {
        reject(new Error('Server error'));
      } else {
        resolve({
          liked: !liked,
          count: liked ? count - 1 : count + 1,
        });
      }
    }, 800);
  });
}

const App: React.FC = () => {
  const [state, setState] = useState<State>({
    liked: false,
    count: 10,
  });

  const [, startTransition] = useTransition();

  const [optimisticState, addOptimistic] = useOptimistic<State, boolean>(
    state,
    (current, nextLiked) => ({
      liked: nextLiked,
      count: nextLiked ? current.count + 1 : current.count - 1,
    })
  );

  async function toggleLike() {
    const nextLiked = !optimisticState.liked;

    startTransition(async () => {
      addOptimistic(nextLiked);

      try {
        const result = await fakeToggleLikeOnServer(state);
        setState(result);
      } catch (err) {
        console.error('Fehler beim Speichern:', err);
        setState(state);
      }
    });
  }

  return (
    <button onClick={toggleLike}>
      {optimisticState.liked ? '\u2665' : '\u2661'} {optimisticState.count}
    </button>
  );
};

export default App;

