"use client";

import { useCart } from "@/context/CartContext";
import { ShoppingCart } from "lucide-react";
import { ensureColorContrast, getReadableTextColor } from "@/lib/color-contrast";

type CartTriggerProps = {
  primaryColor: string;
  iconColor?: string;
  badgeBackgroundColor?: string;
  badgeTextColor?: string;
  hoverBackgroundColor?: string;
  surfaceColor?: string;
  iconSize?: number;
  iconStrokeWidth?: number;
};

export default function CartTrigger({
  primaryColor,
  iconColor,
  badgeBackgroundColor,
  badgeTextColor,
  hoverBackgroundColor,
  surfaceColor = "#FFFFFF",
  iconSize = 24,
  iconStrokeWidth = 2,
}: CartTriggerProps) {
  const { toggleCart, cartCount } = useCart();
  const resolvedIconColor = iconColor || ensureColorContrast(primaryColor, surfaceColor, { minRatio: 3 });
  const resolvedBadgeBackground = badgeBackgroundColor || resolvedIconColor;
  const resolvedBadgeText = badgeTextColor || getReadableTextColor(resolvedBadgeBackground);
  const resolvedHoverBackground =
    hoverBackgroundColor ||
    (resolvedIconColor === "#FFFFFF" ? "rgba(255,255,255,0.12)" : "rgba(17,24,39,0.10)");

  return (
    <button
      onClick={toggleCart}
      className="relative p-2 rounded-lg transition-colors flex items-center justify-center"
      onMouseEnter={(event) => {
        event.currentTarget.style.backgroundColor = resolvedHoverBackground;
      }}
      onMouseLeave={(event) => {
        event.currentTarget.style.backgroundColor = "transparent";
      }}
    >
      <ShoppingCart size={iconSize} strokeWidth={iconStrokeWidth} style={{ color: resolvedIconColor }} />
      {cartCount > 0 && (
        <span
          suppressHydrationWarning
          className="absolute -top-1 -right-1 text-[10px] font-bold px-1.5 py-0.5 rounded-full min-w-[18px] h-[18px] flex items-center justify-center"
          style={{ backgroundColor: resolvedBadgeBackground, color: resolvedBadgeText }}
        >
          {cartCount}
        </span>
      )}
    </button>
  );
}
