"use client";

import { useEffect, useState } from "react";
import { Currency } from "@/types/global";
import { useSettings } from "@/hook/use-settings";

interface PriceProps {
  number?: number | null;
  customCurrency?: Currency;
}

const formatAmount = (value?: number | null) =>
  Math.round(Number(value) || 0).toLocaleString("en-US");

const resolveSymbol = (symbol?: string | null) => {
  if (!symbol || symbol === "$" || symbol.toLowerCase() === "usd") return "تومان";
  return symbol;
};

export const Price = ({ number, customCurrency }: PriceProps) => {
  const [mounted, setMounted] = useState(false);
  const { currency } = useSettings();
  const tempCurrency = customCurrency || currency;
  const amount = formatAmount(number);
  const symbol = resolveSymbol(tempCurrency?.symbol);
  useEffect(() => {
    setMounted(true);
  }, []);
  if (!mounted) return null;
  if (tempCurrency?.position === "before") {
    return (
      <>
        {symbol} {amount}
      </>
    );
  }
  return (
    <>
      {amount} {symbol}
    </>
  );
};
