/**
 * Currency Formatting Utilities
 * 
 * Uses WooCommerce currency settings from window.woonoowCustomer.currency
 */

interface CurrencySettings {
  code: string;
  symbol: string;
  position: 'left' | 'right' | 'left_space' | 'right_space';
  thousandSeparator: string;
  decimalSeparator: string;
  decimals: number;
}

/**
 * Get currency settings from window
 */
export function getCurrencySettings(): CurrencySettings {
  const settings = (window as any).woonoowCustomer?.currency;
  
  // Default to USD if not available
  return settings || {
    code: 'USD',
    symbol: '$',
    position: 'left',
    thousandSeparator: ',',
    decimalSeparator: '.',
    decimals: 2,
  };
}

/**
 * Format a number with thousand and decimal separators
 */
function formatNumber(
  value: number,
  decimals: number,
  decimalSeparator: string,
  thousandSeparator: string
): string {
  // Round to specified decimals
  const rounded = value.toFixed(decimals);
  
  // Split into integer and decimal parts
  const [integerPart, decimalPart] = rounded.split('.');
  
  // Add thousand separators to integer part
  const formattedInteger = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, thousandSeparator);
  
  // Combine with decimal part if decimals > 0
  if (decimals > 0 && decimalPart) {
    return `${formattedInteger}${decimalSeparator}${decimalPart}`;
  }
  
  return formattedInteger;
}

/**
 * Format a price using WooCommerce currency settings
 * 
 * @param price - The price value (number or string)
 * @param options - Optional overrides for currency settings
 * @returns Formatted price string with currency symbol
 * 
 * @example
 * formatPrice(1234.56) // "$1,234.56"
 * formatPrice(1234.56, { symbol: '€', position: 'right_space' }) // "1.234,56 €"
 */
export function formatPrice(
  price: number | string,
  options?: Partial<CurrencySettings>
): string {
  const settings = { ...getCurrencySettings(), ...options };
  const numericPrice = typeof price === 'string' ? parseFloat(price) : price;
  
  // Handle invalid prices
  if (isNaN(numericPrice)) {
    return settings.symbol + '0' + settings.decimalSeparator + '00';
  }
  
  // Format the number
  const formattedNumber = formatNumber(
    numericPrice,
    settings.decimals,
    settings.decimalSeparator,
    settings.thousandSeparator
  );
  
  // Apply currency symbol based on position
  switch (settings.position) {
    case 'left':
      return `${settings.symbol}${formattedNumber}`;
    case 'right':
      return `${formattedNumber}${settings.symbol}`;
    case 'left_space':
      return `${settings.symbol} ${formattedNumber}`;
    case 'right_space':
      return `${formattedNumber} ${settings.symbol}`;
    default:
      return `${settings.symbol}${formattedNumber}`;
  }
}

/**
 * Format price without currency symbol
 */
export function formatPriceValue(
  price: number | string,
  decimals?: number
): string {
  const settings = getCurrencySettings();
  const numericPrice = typeof price === 'string' ? parseFloat(price) : price;
  
  if (isNaN(numericPrice)) {
    return '0' + settings.decimalSeparator + '00';
  }
  
  return formatNumber(
    numericPrice,
    decimals ?? settings.decimals,
    settings.decimalSeparator,
    settings.thousandSeparator
  );
}

/**
 * Get currency symbol
 */
export function getCurrencySymbol(): string {
  return getCurrencySettings().symbol;
}

/**
 * Get currency code (e.g., 'USD', 'EUR')
 */
export function getCurrencyCode(): string {
  return getCurrencySettings().code;
}

/**
 * Parse a formatted price string back to a number
 */
export function parsePrice(formattedPrice: string): number {
  const settings = getCurrencySettings();
  
  // Remove currency symbol and spaces
  let cleaned = formattedPrice.replace(settings.symbol, '').trim();
  
  // Remove thousand separators
  cleaned = cleaned.replace(new RegExp(`\\${settings.thousandSeparator}`, 'g'), '');
  
  // Replace decimal separator with dot
  cleaned = cleaned.replace(settings.decimalSeparator, '.');
  
  return parseFloat(cleaned) || 0;
}

/**
 * Format a price range
 */
export function formatPriceRange(minPrice: number, maxPrice: number): string {
  if (minPrice === maxPrice) {
    return formatPrice(minPrice);
  }
  
  return `${formatPrice(minPrice)} - ${formatPrice(maxPrice)}`;
}

/**
 * Calculate and format a discount percentage
 */
export function formatDiscount(regularPrice: number, salePrice: number): string {
  if (regularPrice <= salePrice) {
    return '';
  }
  
  const discount = ((regularPrice - salePrice) / regularPrice) * 100;
  return `-${Math.round(discount)}%`;
}

/**
 * Format a price with tax label
 */
export function formatPriceWithTax(
  price: number,
  taxLabel: string = 'incl. tax'
): string {
  return `${formatPrice(price)} (${taxLabel})`;
}
