"use client";

import { useCallback, useEffect, useState } from "react";
import {
  getFavoritesSnapshot,
  onFavoritesChange,
  toggleFavorite,
} from "@/lib/storage";

interface FavoriteButtonProps {
  slug: string;
  title: string;
  variant?: "icon" | "full";
}

/**
 * Favorite toggle persisted in the browser (no account needed).
 * Stays in sync across tabs and same-page instances.
 */
export function FavoriteButton({
  slug,
  title,
  variant = "icon",
}: FavoriteButtonProps) {
  // Lazy initializer reads storage during render (client-only); the effect
  // below only subscribes to external changes.
  const [isFavorite, setIsFavorite] = useState<boolean>(() =>
    typeof window === "undefined"
      ? false
      : getFavoritesSnapshot().includes(slug),
  );

  useEffect(
    () =>
      onFavoritesChange(() => {
        setIsFavorite(getFavoritesSnapshot().includes(slug));
      }),
    [slug],
  );

  const onToggle = useCallback(() => {
    setIsFavorite(toggleFavorite(slug).includes(slug));
  }, [slug]);

  const label = isFavorite
    ? `Remove ${title} from favorites`
    : `Save ${title} to favorites`;

  if (variant === "full") {
    return (
      <button
        type="button"
        onClick={onToggle}
        aria-pressed={isFavorite}
        aria-label={label}
        className={`inline-flex h-12 items-center gap-2 rounded-xl border px-5 text-base font-semibold transition-colors ${
          isFavorite
            ? "border-brand-500/60 bg-brand-600/20 text-white hover:bg-brand-600/30"
            : "border-slate-700 bg-slate-900 text-slate-200 hover:border-slate-500 hover:text-white"
        }`}
      >
        <span aria-hidden="true" className={isFavorite ? "text-brand-300" : ""}>
          {isFavorite ? "♥" : "♡"}
        </span>
        {isFavorite ? "Favorited" : "Favorite"}
      </button>
    );
  }

  return (
    <button
      type="button"
      onClick={(e) => {
        e.preventDefault();
        e.stopPropagation();
        onToggle();
      }}
      aria-pressed={isFavorite}
      aria-label={label}
      title={isFavorite ? "Remove from favorites" : "Save to favorites"}
      className={`flex h-9 w-9 items-center justify-center rounded-full text-lg shadow-lg backdrop-blur transition-colors ${
        isFavorite
          ? "bg-brand-600 text-white hover:bg-brand-500"
          : "bg-slate-950/70 text-slate-300 hover:bg-slate-950/90 hover:text-white"
      }`}
    >
      <span aria-hidden="true">{isFavorite ? "♥" : "♡"}</span>
    </button>
  );
}
