"use client";

import { useState, useTransition } from "react";
import { toggleConfessionLike } from "@/lib/confessions/actions";

export function ConfessionLikeButton({
  confessionId,
  initiallyLiked,
  likeCount,
}: {
  confessionId: string;
  initiallyLiked: boolean;
  likeCount: number;
}) {
  const [liked, setLiked] = useState(initiallyLiked);
  const [count, setCount] = useState(likeCount);
  const [isPending, startTransition] = useTransition();

  function handleClick() {
    const nextLiked = !liked;
    setLiked(nextLiked);
    setCount((c) => c + (nextLiked ? 1 : -1));

    startTransition(async () => {
      await toggleConfessionLike(confessionId);
    });
  }

  return (
    <button
      onClick={handleClick}
      disabled={isPending}
      className={`inline-flex items-center gap-1.5 text-[12.5px] font-semibold transition-colors ${
        liked ? "text-accent" : "text-text-muted hover:text-accent"
      }`}
    >
      <svg width="15" height="15" viewBox="0 0 24 24" fill={liked ? "currentColor" : "none"} stroke="currentColor" strokeWidth={1.9} strokeLinecap="round" strokeLinejoin="round">
        <path d="M12 20s-7-4.35-9.5-8.5C.5 8 2 4 6 4c2 0 3.5 1.2 4 2.5C10.5 5.2 12 4 14 4c4 0 5.5 4 3.5 7.5C19 15.65 12 20 12 20z" />
      </svg>
      {count > 0 ? count : "Beğen"}
    </button>
  );
}
