// Exercise 1: optimistic like button (basics)
//
// `LikeButton` should show the incremented like count IMMEDIATELY when
// clicked, before the simulated network request (`likePost`) resolves —
// using useOptimistic so there's no visible delay.
//
// TODO 1: implement incrementLikes (pure, no hooks) — the updateFn
// TODO 2: wire useOptimistic into LikeButton and call addOptimisticLike
//         inside the click handler, before awaiting likePost

import { useOptimistic, useState } from "react";

async function likePost(postId: string): Promise<number> {
  await new Promise((resolve) => setTimeout(resolve, 500)); // simulated network delay
  return 1; // pretend the server confirms +1 like
}

// TODO 1: given the current optimistic likes count and an (unused) payload,
// return current + 1. The updateFn signature for useOptimistic is always
// (currentState, optimisticValue) => newState, even if optimisticValue is
// unused here.
function incrementLikes(current: number, _payload: undefined): number {
  return current; // TODO: return current + 1
}

function LikeButton({ postId, initialLikes }: { postId: string; initialLikes: number }) {
  const [likes, setLikes] = useState(initialLikes);

  // TODO 2: const [optimisticLikes, addOptimisticLike] = useOptimistic(likes, incrementLikes);
  const optimisticLikes = likes;
  const addOptimisticLike = (_payload: undefined) => {};

  async function handleClick() {
    // TODO 2 (cont'd): call addOptimisticLike(undefined) here BEFORE awaiting
    // likePost, so the UI updates instantly. Once likePost resolves, update
    // the real `likes` state so optimisticLikes re-derives correctly.
    const delta = await likePost(postId);
    setLikes((prev) => prev + delta);
  }

  return <button onClick={handleClick}>{optimisticLikes} likes</button>;
}

export { LikeButton, incrementLikes, likePost };

// --- self-check: do not modify below this line ---
const check1 = incrementLikes(4, undefined) === 5;
const check2 = incrementLikes(0, undefined) === 1;
console.log(check1 && check2 ? "PASS (incrementLikes)" : "FAIL (incrementLikes)");

// Verify visually: mount <LikeButton postId="1" initialLikes={4} />, click
// it. The label should read "5 likes" INSTANTLY (before the 500ms delay
// elapses), not only after likePost resolves. After it resolves, the label
// should still read "5 likes" (now backed by real state, no flicker).
