"use client";

import { AnimatePresence, motion } from "framer-motion";
import { useTranslations } from "next-intl";

import { cn } from "@/lib/utils";

interface PricingAnimatedPriceProps {
  price: number;
  compareAt: number | null;
  billing: string;
  size?: "default" | "compact";
}

function formatPrice(value: number): string {
  return Number.isInteger(value) ? String(value) : value.toFixed(1);
}

export function PricingAnimatedPrice({
  price,
  compareAt,
  billing,
  size = "default",
}: PricingAnimatedPriceProps) {
  const isCompact = size === "compact";
  const t = useTranslations("auto.componentsSectionsPricingAnimatedPrice");

  return (
    <div className={isCompact ? "mt-2" : "mt-4"}>
      {compareAt != null ? (
        <p className="mb-1 flex items-baseline gap-2">
          <span
            className={cn(
              "text-neutral-400 line-through",
              isCompact ? "text-sm" : "text-lg"
            )}
          >
            ${formatPrice(compareAt)}
          </span>
        </p>
      ) : null}
      <div className="flex items-baseline justify-center gap-0.5">
        <AnimatePresence mode="wait" initial={false}>
          <motion.span
            key={`${price}-${billing}`}
            initial={{ opacity: 0, y: 12 }}
            animate={{ opacity: 1, y: 0 }}
            exit={{ opacity: 0, y: -12 }}
            transition={{ duration: 0.25, ease: "easeOut" }}
            className={cn(
              "font-heading font-bold tracking-tight text-rose-500",
              isCompact ? "text-2xl" : "text-4xl sm:text-[2.75rem]"
            )}
          >
            ${formatPrice(price)}
          </motion.span>
        </AnimatePresence>
        <span className="ml-1 text-sm font-normal text-neutral-500">{t("perMonth")}</span>
      </div>
    </div>
  );
}
