/**
 * Currency Configuration
 *
 * Maps countries to their currencies and provides formatting rules.
 * Used by the user currency detection service.
 */

import type { Currency } from "@/lib/types/pricing";

// Country code (ISO 3166-1 alpha-2) to Currency mapping
export const COUNTRY_TO_CURRENCY: Record<string, Currency> = {
  // GCC Countries (Primary Market)
  QA: "QAR", // Qatar
  AE: "AED", // United Arab Emirates
  SA: "SAR", // Saudi Arabia
  KW: "KWD", // Kuwait
  BH: "BHD", // Bahrain
  OM: "OMR", // Oman

  // Western Countries
  GB: "GBP", // United Kingdom
  US: "USD", // United States

  // Euro Zone
  DE: "EUR", // Germany
  FR: "EUR", // France
  IT: "EUR", // Italy
  ES: "EUR", // Spain
  NL: "EUR", // Netherlands
  BE: "EUR", // Belgium
  AT: "EUR", // Austria
  IE: "EUR", // Ireland
  PT: "EUR", // Portugal
  GR: "EUR", // Greece
  FI: "EUR", // Finland
  LU: "EUR", // Luxembourg
  EE: "EUR", // Estonia
  LV: "EUR", // Latvia
  LT: "EUR", // Lithuania
  SK: "EUR", // Slovakia
  SI: "EUR", // Slovenia
  CY: "EUR", // Cyprus
  MT: "EUR", // Malta
  HR: "EUR", // Croatia
};

// Full currency configuration with formatting rules
export interface CurrencyConfig {
  code: Currency;
  name: string;
  nameAr: string;
  symbol: string;
  symbolPosition: "before" | "after";
  decimalPlaces: number;
  thousandsSeparator: string;
  decimalSeparator: string;
  isRTL: boolean;
  stripeSupported: boolean;
  minChargeAmount: number; // In smallest currency unit (e.g., cents, fils)
}

export const CURRENCY_CONFIG: Record<Currency, CurrencyConfig> = {
  GBP: {
    code: "GBP",
    name: "British Pound",
    nameAr: "الجنيه الإسترليني",
    symbol: "£",
    symbolPosition: "before",
    decimalPlaces: 2,
    thousandsSeparator: ",",
    decimalSeparator: ".",
    isRTL: false,
    stripeSupported: true,
    minChargeAmount: 30, // 30 pence
  },
  USD: {
    code: "USD",
    name: "US Dollar",
    nameAr: "الدولار الأمريكي",
    symbol: "$",
    symbolPosition: "before",
    decimalPlaces: 2,
    thousandsSeparator: ",",
    decimalSeparator: ".",
    isRTL: false,
    stripeSupported: true,
    minChargeAmount: 50, // 50 cents
  },
  EUR: {
    code: "EUR",
    name: "Euro",
    nameAr: "اليورو",
    symbol: "€",
    symbolPosition: "before",
    decimalPlaces: 2,
    thousandsSeparator: ".",
    decimalSeparator: ",",
    isRTL: false,
    stripeSupported: true,
    minChargeAmount: 50, // 50 euro cents
  },
  QAR: {
    code: "QAR",
    name: "Qatari Riyal",
    nameAr: "الريال القطري",
    symbol: "ر.ق",
    symbolPosition: "after",
    decimalPlaces: 2,
    thousandsSeparator: ",",
    decimalSeparator: ".",
    isRTL: true,
    stripeSupported: true, // Stripe supports via presentment
    minChargeAmount: 200, // 2 QAR
  },
  AED: {
    code: "AED",
    name: "UAE Dirham",
    nameAr: "الدرهم الإماراتي",
    symbol: "د.إ",
    symbolPosition: "after",
    decimalPlaces: 2,
    thousandsSeparator: ",",
    decimalSeparator: ".",
    isRTL: true,
    stripeSupported: true,
    minChargeAmount: 200, // 2 AED
  },
  SAR: {
    code: "SAR",
    name: "Saudi Riyal",
    nameAr: "الريال السعودي",
    symbol: "ر.س",
    symbolPosition: "after",
    decimalPlaces: 2,
    thousandsSeparator: ",",
    decimalSeparator: ".",
    isRTL: true,
    stripeSupported: true,
    minChargeAmount: 200, // 2 SAR
  },
  KWD: {
    code: "KWD",
    name: "Kuwaiti Dinar",
    nameAr: "الدينار الكويتي",
    symbol: "د.ك",
    symbolPosition: "after",
    decimalPlaces: 3, // KWD uses 3 decimal places
    thousandsSeparator: ",",
    decimalSeparator: ".",
    isRTL: true,
    stripeSupported: false, // May need verification
    minChargeAmount: 100, // 0.100 KWD
  },
  BHD: {
    code: "BHD",
    name: "Bahraini Dinar",
    nameAr: "الدينار البحريني",
    symbol: "د.ب",
    symbolPosition: "after",
    decimalPlaces: 3, // BHD uses 3 decimal places
    thousandsSeparator: ",",
    decimalSeparator: ".",
    isRTL: true,
    stripeSupported: false, // May need verification
    minChargeAmount: 100, // 0.100 BHD
  },
  OMR: {
    code: "OMR",
    name: "Omani Rial",
    nameAr: "الريال العماني",
    symbol: "ر.ع",
    symbolPosition: "after",
    decimalPlaces: 3, // OMR uses 3 decimal places
    thousandsSeparator: ",",
    decimalSeparator: ".",
    isRTL: true,
    stripeSupported: false, // May need verification
    minChargeAmount: 100, // 0.100 OMR
  },
};

// Timezone to country code mapping (for browser fallback)
export const TIMEZONE_TO_COUNTRY: Record<string, string> = {
  // GCC
  "Asia/Qatar": "QA",
  "Asia/Doha": "QA",
  "Asia/Dubai": "AE",
  "Asia/Abu_Dhabi": "AE",
  "Asia/Riyadh": "SA",
  "Asia/Kuwait": "KW",
  "Asia/Bahrain": "BH",
  "Asia/Muscat": "OM",

  // UK
  "Europe/London": "GB",

  // USA (major zones)
  "America/New_York": "US",
  "America/Chicago": "US",
  "America/Denver": "US",
  "America/Los_Angeles": "US",
  "America/Phoenix": "US",
  "America/Anchorage": "US",
  "Pacific/Honolulu": "US",

  // Euro Zone (major cities)
  "Europe/Paris": "FR",
  "Europe/Berlin": "DE",
  "Europe/Madrid": "ES",
  "Europe/Rome": "IT",
  "Europe/Amsterdam": "NL",
  "Europe/Brussels": "BE",
  "Europe/Vienna": "AT",
  "Europe/Dublin": "IE",
  "Europe/Lisbon": "PT",
  "Europe/Athens": "GR",
  "Europe/Helsinki": "FI",
  "Europe/Stockholm": "SE", // Not in eurozone but often grouped
  "Europe/Copenhagen": "DK", // Not in eurozone
  "Europe/Prague": "CZ", // Not in eurozone
  "Europe/Warsaw": "PL", // Not in eurozone
  "Europe/Luxembourg": "LU",
};

// Accept-Language header to country code mapping
export const LOCALE_TO_COUNTRY: Record<string, string> = {
  // GCC specific
  "ar-QA": "QA",
  "ar-AE": "AE",
  "ar-SA": "SA",
  "ar-KW": "KW",
  "ar-BH": "BH",
  "ar-OM": "OM",

  // Generic Arabic defaults to QAR (GCC focus)
  ar: "QA",

  // UK
  "en-GB": "GB",

  // USA
  "en-US": "US",

  // Europe
  "de-DE": "DE",
  "fr-FR": "FR",
  "it-IT": "IT",
  "es-ES": "ES",
  "nl-NL": "NL",
  "pt-PT": "PT",

  // Generic fallbacks
  de: "DE",
  fr: "FR",
  it: "IT",
  es: "ES",
  nl: "NL",
  pt: "PT",
};

// Default currency for unknown regions (GCC focus)
export const DEFAULT_CURRENCY: Currency = "QAR";

// Fallback currency when all detection fails
export const FALLBACK_CURRENCY: Currency = "GBP";

// Supported currencies list (for validation)
export const SUPPORTED_CURRENCIES: Currency[] = [
  "GBP",
  "USD",
  "EUR",
  "QAR",
  "AED",
  "SAR",
  "KWD",
  "BHD",
  "OMR",
];

/**
 * Get currency code from country code
 */
export function getCurrencyFromCountry(countryCode: string): Currency | null {
  const upperCode = countryCode.toUpperCase();
  return COUNTRY_TO_CURRENCY[upperCode] || null;
}

/**
 * Get currency config
 */
export function getCurrencyConfig(currency: Currency): CurrencyConfig {
  return CURRENCY_CONFIG[currency];
}

/**
 * Check if currency is supported
 */
export function isSupportedCurrency(currency: string): currency is Currency {
  return SUPPORTED_CURRENCIES.includes(currency as Currency);
}

/**
 * Format price with currency symbol
 */
export function formatCurrencyAmount(
  amount: number,
  currency: Currency,
  options?: { showDecimals?: boolean },
): string {
  const config = CURRENCY_CONFIG[currency];
  const { showDecimals = true } = options || {};

  const formattedAmount = showDecimals
    ? amount.toFixed(config.decimalPlaces)
    : Math.round(amount).toString();

  // Add thousands separator
  const parts = formattedAmount.split(".");
  parts[0] = parts[0].replace(
    /\B(?=(\d{3})+(?!\d))/g,
    config.thousandsSeparator,
  );
  const finalAmount = parts.join(config.decimalSeparator);

  return config.symbolPosition === "before"
    ? `${config.symbol}${finalAmount}`
    : `${finalAmount} ${config.symbol}`;
}
