export interface StoreCurrency {
  code: string;
  symbol: string;
}

const CURRENCY_SYMBOLS: Record<string, string> = {
  USD: "$",
  CAD: "CA$",
  AUD: "A$",
  GBP: "£",
  EUR: "€",
  INR: "₹",
  JPY: "¥",
  CNY: "¥",
  SGD: "S$",
  NZD: "NZ$",
  AED: "AED ",
  SAR: "SAR ",
  BRL: "R$",
  MXN: "MX$",
  CHF: "CHF ",
  SEK: " kr",
  NOK: " kr",
  DKK: " kr",
  PLN: " zł",
  THB: "฿",
  MYR: "RM ",
  PHP: "₱",
  ZAR: "R ",
};

/**
 * Returns the symbol for a given currency code.
 */
export function getCurrencySymbol(currencyCode?: string): string {
  if (!currencyCode) return "$";
  const code = currencyCode.toUpperCase().trim();
  return CURRENCY_SYMBOLS[code] || `${code} `;
}

/**
 * Formats a monetary amount according to the store's currency code.
 * Example:
 * formatCurrency(49.99, "USD") -> "$49.99"
 * formatCurrency(299, "INR") -> "₹299.00"
 * formatCurrency(15.5, "EUR") -> "€15.50"
 * formatCurrency(100, "AED") -> "AED 100.00"
 */
export function formatCurrency(
  amount: number | string | null | undefined,
  currencyCode?: string
): string {
  if (amount === null || amount === undefined || amount === "") return "";
  const num = typeof amount === "string" ? parseFloat(amount) : amount;
  if (isNaN(num)) return String(amount);

  const code = (currencyCode || "USD").toUpperCase().trim();
  const symbol = getCurrencySymbol(code);

  const formattedNum = num.toLocaleString("en-US", {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  });

  if (symbol.startsWith(" ")) {
    return `${formattedNum}${symbol}`;
  }
  return `${symbol}${formattedNum}`;
}

/**
 * Detects the store currency by checking the storefront cart/localization endpoint.
 */
export async function detectStoreCurrency(shopDomain: string): Promise<string> {
  const cleanDomain = shopDomain.replace(/^https?:\/\//, "").replace(/\/.*$/, "");
  try {
    const res = await fetch(`https://${cleanDomain}/cart.js`);
    if (res.ok) {
      const data = await res.json();
      if (data.currency) {
        return String(data.currency).toUpperCase();
      }
    }
  } catch (e) {}

  try {
    const res = await fetch(`https://${cleanDomain}/localization.json`);
    if (res.ok) {
      const data = await res.json();
      if (data.country?.currency?.iso_code) {
        return String(data.country.currency.iso_code).toUpperCase();
      }
      if (data.currency?.iso_code) {
        return String(data.currency.iso_code).toUpperCase();
      }
    }
  } catch (e) {}

  return "USD";
}
