"use client";

import { useEffect, useRef, useState } from "react";
import Image from "next/image";
import { addToCart } from "../lib/cart";
import { useCartFly } from "./CartFly";

// Exported so consumers like RelatedProducts.tsx can delay their own
// follow-up UI changes (e.g. swapping out this exact card) until after
// the success state has actually had time to be seen.
export const FEEDBACK_MS = 2000;

/**
 * Add-to-cart button that stays on the page (unlike AddToCartButton, which
 * navigates to /cart) — used wherever a product grid lets you keep browsing,
 * so a click needs its own success confirmation instead of relying on the
 * navigation itself as feedback.
 */
export function AddToCartInlineButton({
  id,
  label = "In den Warenkorb",
  className,
}: {
  id: string;
  label?: string;
  className?: string;
}) {
  const [added, setAdded] = useState(false);
  const timeoutRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
  const buttonRef = useRef<HTMLButtonElement>(null);
  const { fly } = useCartFly();

  useEffect(() => () => clearTimeout(timeoutRef.current), []);

  function handleClick() {
    addToCart(id);
    if (buttonRef.current) fly(buttonRef.current);
    setAdded(true);
    clearTimeout(timeoutRef.current);
    timeoutRef.current = setTimeout(() => setAdded(false), FEEDBACK_MS);
  }

  const base =
    className ??
    "flex items-center justify-between px-5 py-3 rounded-sm border w-full transition-all duration-200 active:scale-[0.97] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-brand focus-visible:ring-offset-2 focus-visible:ring-offset-bg-base";
  // Branch the border/bg classes instead of appending an "override" on top
  // of the default ones — Tailwind v4 has no leading-`!` important prefix
  // anymore (it's a trailing `!` now), so two conflicting utilities like
  // border-border/border-success both being present would silently race on
  // CSS source order instead of one cleanly winning.
  const stateClasses = added
    ? "border-success bg-success-subtle"
    : "border-border hover:border-brand";

  return (
    <button ref={buttonRef} type="button" onClick={handleClick} className={`${base} ${stateClasses}`}>
      <span
        className={
          "text-body-sm transition-colors " +
          (added ? "font-semibold text-success" : "text-text-primary")
        }
      >
        {added ? "Hinzugefügt ✓" : label}
      </span>
      <Image alt="" src="/icon-cart-outline.png" width={32} height={30} className="h-[1.875rem] w-8 object-contain" />
    </button>
  );
}
