"use client";

import { fetchOnce } from "@/lib/fetch-once";

import { createContext, useContext, useEffect, useState } from "react";

type Locale = {
  country: string;
  language: string;
  currency: string;
  symbol: string;
  distanceUnit: string;
  detected: boolean;
};

const FALLBACK: Locale = {
  country: "United Kingdom",
  language: "English",
  currency: "USD",
  symbol: "$",
  distanceUnit: "kilometer",
  detected: false,
};

const Ctx = createContext<Locale>(FALLBACK);

/** Makes the detected locale available anywhere in the app. */
export function LocaleProvider({ children }: { children: React.ReactNode }) {
  const [locale, setLocale] = useState<Locale>(FALLBACK);

  useEffect(() => {
    fetchOnce<Locale>("/api/locale")
      .then((d) => d)
      .then((d) => d && setLocale(d))
      .catch(() => {});
  }, []);

  return <Ctx.Provider value={locale}>{children}</Ctx.Provider>;
}

export const useLocale = () => useContext(Ctx);

/** Formats an amount in the visitor's currency. */
export function useMoney() {
  const { symbol } = useLocale();
  return (amount: number) =>
    `${symbol}${amount.toLocaleString(undefined, { maximumFractionDigits: 2 })}`;
}

/** Distance in whichever unit the admin chose. */
export function useDistance() {
  const { distanceUnit } = useLocale();
  return (km: number) =>
    distanceUnit === "mile"
      ? `${(km * 0.621371).toFixed(1)} mi`
      : `${km.toFixed(1)} km`;
}
