"use client";

import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { motion, useAnimationControls, useReducedMotion } from "motion/react";
import Icon from "@/components/ui/Icon";
import { useAuth } from "@/store/auth";

/** Heart toggle for any item with a reviewable id. Signed-out visitors go to login and come back to this page. */
export default function SaveButton({ reviewableId, name }: { reviewableId: number; name: string }) {
  const router = useRouter();
  const path = usePathname();
  const search = useSearchParams().toString();
  const reduce = useReducedMotion();
  const pop = useAnimationControls();
  const status = useAuth((s) => s.status);
  const saved = useAuth((s) => s.favorites.has(reviewableId));
  const toggle = useAuth((s) => s.toggleFavorite);

  const click = async () => {
    if (status !== "user") {
      const here = search ? `${path}?${search}` : path;
      return router.push(`/login?next=${encodeURIComponent(here)}`);
    }
    // A short pop confirms the save; unsaving stays quiet.
    if (!saved && !reduce) void pop.start({ scale: [1, 1.25, 1], transition: { duration: 0.35, ease: [0.2, 0.7, 0.2, 1] } });
    await toggle(reviewableId);
  };

  return (
    <button type="button" className="lfd-save" aria-pressed={saved} onClick={click} disabled={status === "unknown"} aria-label={saved ? `Remove ${name} from saved` : `Save ${name}`}>
      <motion.span animate={pop} className="lfd-save-icon">
        <Icon name="favorite" filled={saved} />
      </motion.span>
      {saved ? "Saved" : "Save"}
    </button>
  );
}
