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

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

interface BookingSummaryProps {
  checkIn: Date;
  checkOut: Date;
  rates: RateConfig;
}

export default function BookingSummary({ checkIn, checkOut, rates }: BookingSummaryProps) {
  const [local, setLocal] = useState<LocalPrice | null>(null);
  const breakdown = calculateStayTotal(checkIn, checkOut, rates);
  const nightCount = breakdown.nights.length;
  const sameRate = rates.weekdayRate === rates.weekendRate;

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

  return (
    <div className="rounded-lg border border-sandDark bg-white/50 p-4 space-y-2">
      {sameRate ? (
        <div className="flex justify-between text-sm text-ink/70">
          <span>${rates.weekdayRate} × {nightCount} night{nightCount !== 1 ? "s" : ""}</span>
          <span>${breakdown.total.toLocaleString()}</span>
        </div>
      ) : (
        <>
          {breakdown.weekdayNights > 0 && (
            <div className="flex justify-between text-sm text-ink/70">
              <span>${rates.weekdayRate} × {breakdown.weekdayNights} weeknight{breakdown.weekdayNights !== 1 ? "s" : ""}</span>
              <span>${(breakdown.weekdayNights * rates.weekdayRate).toLocaleString()}</span>
            </div>
          )}
          {breakdown.weekendNights > 0 && (
            <div className="flex justify-between text-sm text-ink/70">
              <span>${rates.weekendRate} × {breakdown.weekendNights} weekend night{breakdown.weekendNights !== 1 ? "s" : ""}</span>
              <span>${(breakdown.weekendNights * rates.weekendRate).toLocaleString()}</span>
            </div>
          )}
        </>
      )}

      <div className="border-t border-sandDark pt-2 flex justify-between items-start font-semibold">
        <span>Total</span>
        <div className="text-right">
          <div>${breakdown.total.toLocaleString()}</div>
          {local && local.currencyCode !== "USD" && (
            <div className="text-xs font-normal text-ink/55">
              {local.isFixedPrice ? "" : "≈ "}{local.currencySymbol}{local.amount.toLocaleString()}
            </div>
          )}
        </div>
      </div>

      <p className="text-xs text-ink/50">Charged in USD. Your bank handles any conversion.</p>
    </div>
  );
}
