// components/PriceDisplay.tsx
"use client";

import { useEffect, useState } from "react";
import { detectLocalPrice, LocalPrice } from "@/lib/currency";

interface PriceDisplayProps {
  usdAmount: number;
  nights?: number;
  perLabel?: string;
}

export default function PriceDisplay({ usdAmount, nights = 1, perLabel = "/ night" }: PriceDisplayProps) {
  const [local, setLocal] = useState<LocalPrice | null>(null);

  useEffect(() => {
    let cancelled = false;
    detectLocalPrice(usdAmount, nights).then((r) => { if (!cancelled) setLocal(r); });
    return () => { cancelled = true; };
  }, [usdAmount, nights]);

  const showLocal = local && local.currencyCode !== "USD";

  return (
    <div>
      <div className="flex items-baseline gap-1.5">
        <span className="font-display text-3xl font-semibold text-tealDark">
          ${usdAmount.toLocaleString()}
        </span>
        <span className="text-sm text-ink/60">{perLabel}</span>
      </div>

      {showLocal && (
        <p className="mt-0.5 text-sm text-ink/60">
          {local!.isFixedPrice ? "" : "≈ "}
          {local!.currencySymbol}{local!.amount.toLocaleString()} {perLabel}
        </p>
      )}
    </div>
  );
}
