"use client";

import { useRouter } from "next/navigation";
import { useState } from "react";
import { useWishlist } from "../lib/useWishlist";

// Heart-toggle for a product card/detail page. Login-gated (unlike the
// cart, which works for guests) — a logged-out click redirects to
// /konto/login?redirect=<back-here> instead of silently failing, since
// there's no local-storage fallback that would make sense for a wishlist
// (see useWishlist.ts's own comment on why this can't reuse cart.ts's
// guest-friendly pattern).
export function WishlistButton({
  productId,
  variant = "",
  className = "",
  revealOnHover = false,
}: {
  productId: number;
  variant?: string;
  className?: string;
  /** false (default): always visible — right for /konto/merkliste (every
   * card there is already-wishlisted, so hover-reveal would be pointless)
   * and the product detail page. true: invisible until the card is
   * hovered/focused, unless the product is already wishlisted (a filled
   * heart stays as a permanent status indicator) — right for any grid or
   * card-like feature (ProductGrid.tsx, ProductSpotlight.tsx) where a
   * heart sitting there unprompted reads as visual noise. Relies on the
   * parent card already carrying `group`/`focus-within` (see
   * ProductGrid.tsx/ProductSpotlight.tsx).
   *
   * On coarse-pointer (touch) devices, hover-reveal can't work at all —
   * touch has no persistent `:hover`, so a tap on the card never reliably
   * reveals a `group-hover`-gated element the way a mouse hover does.
   * Rather than falling back to "always visible at full size" (which
   * recreates the exact "a heart on every card" visual noise this mode
   * exists to avoid), touch devices get a smaller variant with a lighter
   * (not removed — fully transparent made it invisible against some
   * product photos) background instead — present and tappable everywhere,
   * but visually quieter than the full-size default. Applies to
   * already-wishlisted hearts too (not just the hover-revealed ones) —
   * consistent sizing across every heart on a touch device, rather than
   * only the not-yet-wishlisted ones shrinking. This smaller touch sizing
   * is applied regardless of `revealOnHover` (see the className below) —
   * a heart reading visually "quieter" on a touch screen is a general
   * touch-device trait, not specific to the multi-card-grid use case it
   * was first built for. */
  revealOnHover?: boolean;
}) {
  const { isWishlisted, toggle } = useWishlist();
  const [pending, setPending] = useState(false);
  const router = useRouter();
  const wishlisted = isWishlisted(productId, variant);

  async function handleClick(e: React.MouseEvent) {
    e.preventDefault();
    e.stopPropagation();
    if (pending) return;

    const res = await fetch("/api/account/wishlist", { method: "GET", cache: "no-store" });
    if (res.status === 401) {
      router.push(`/konto/login?redirect=${encodeURIComponent(window.location.pathname)}`);
      return;
    }

    setPending(true);
    await toggle(productId, variant);
    setPending(false);
  }

  return (
    <button
      type="button"
      onClick={handleClick}
      aria-label={wishlisted ? "Von der Merkliste entfernen" : "Zur Merkliste hinzufügen"}
      aria-pressed={wishlisted}
      disabled={pending}
      className={`flex h-9 w-9 items-center justify-center rounded-full bg-bg-base/90 backdrop-blur-sm transition-all active:scale-90 disabled:opacity-60 pointer-coarse:h-7 pointer-coarse:w-7 pointer-coarse:bg-bg-base/60 ${
        revealOnHover && !wishlisted
          ? "opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 focus-visible:opacity-100 pointer-coarse:opacity-100"
          : ""
      } ${className}`}
    >
      <svg
        width="20"
        height="18"
        viewBox="0 0 20 18"
        fill={wishlisted ? "currentColor" : "none"}
        className={`${wishlisted ? "text-brand" : "text-text-primary"} pointer-coarse:scale-75`}
      >
        <path
          d="M10 17S1 11.5 1 5.8C1 2.6 3.4 1 5.8 1c1.6 0 3.2.9 4.2 2.4C11 1.9 12.6 1 14.2 1 16.6 1 19 2.6 19 5.8 19 11.5 10 17 10 17Z"
          stroke="currentColor"
          strokeWidth="1.5"
          strokeLinejoin="round"
        />
      </svg>
    </button>
  );
}
