"use client";

import { useState } from "react";

// Tiny client component for the heart button on EscortCard. Wired to the
// favorites API the same way as FavoriteButton (Round-7 hotfix fixed the
// payload shape). Stops propagation so clicking it doesn't navigate to
// the profile via the parent Link.
export function HeartFavoriteButton({
  userId,
  initialFavorited = false,
}: {
  userId: number;
  initialFavorited?: boolean;
}) {
  const [isFavorited, setIsFavorited] = useState(initialFavorited);
  const [pending, setPending] = useState(false);

  async function handleClick(e: React.MouseEvent) {
    e.preventDefault();
    e.stopPropagation();
    if (pending) return;
    const optimistic = !isFavorited;
    setIsFavorited(optimistic);
    setPending(true);
    try {
      const res = await fetch("/api/favorites", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          markable_type: "App\\Models\\User",
          markable_id: userId,
        }),
      });
      if (!res.ok) throw new Error("Failed");
      const data = await res.json();
      setIsFavorited(data.toggled === "added");
    } catch {
      setIsFavorited(!optimistic);
    } finally {
      setPending(false);
    }
  }

  return (
    <button
      type="button"
      onClick={handleClick}
      aria-label={isFavorited ? "Remove from favourites" : "Add to favourites"}
      aria-pressed={isFavorited}
      className="flex h-10 w-10 items-center justify-center rounded-full bg-black/40 backdrop-blur-sm text-white/80 hover:text-primary transition-colors disabled:opacity-50"
      disabled={pending}
    >
      <svg className="h-4 w-4" fill={isFavorited ? "currentColor" : "none"} stroke="currentColor" viewBox="0 0 24 24">
        <path
          strokeLinecap="round"
          strokeLinejoin="round"
          strokeWidth={2}
          d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z"
        />
      </svg>
    </button>
  );
}
