import planData from './plan.json';

const EUR_REGION_CODES = new Set([
  'EU', 'EUR', 'AT', 'BE', 'CY', 'DE', 'EE', 'ES', 'FI', 'FR', 'GR', 'HR', 'IE',
  'IT', 'LT', 'LU', 'LV', 'MT', 'NL', 'PT', 'SI', 'SK'
]);

export const getStoredCountryCode = () => {
  if (typeof window === 'undefined') return 'IN';
  return String(localStorage.getItem('country') || 'IN').toUpperCase();
};

export const isEurRegion = (countryCode?: string) => {
  const code = countryCode || getStoredCountryCode();
  return EUR_REGION_CODES.has(code);
};

export const isInrRegion = (countryCode?: string) => {
  const code = countryCode || getStoredCountryCode();
  return code === 'IN';
};

export const getCurrencyCode = (countryCode?: string) => {
  const code = countryCode || getStoredCountryCode();
  if (isInrRegion(code)) return 'INR';
  if (isEurRegion(code)) return 'EUR';
  return 'USD';
};

export const getCurrencySymbol = (currency?: string) => {
  const code = currency || getCurrencyCode();
  if (code === 'USD') return '$';
  if (code === 'EUR') return '€';
  if (code === 'INR') return '₹';
  return '₹';
};

export const formatMoney = (amount: number | string, currencyCode?: string) => {
  const numericAmount = Number(amount || 0);
  const targetCurrency = currencyCode || getCurrencyCode();
  if (targetCurrency === 'USD') {
    return `$${numericAmount.toLocaleString('en-US')}`;
  }
  if (targetCurrency === 'EUR') {
    return `€${numericAmount.toLocaleString('en-IE')}`;
  }
  return `₹${numericAmount.toLocaleString('en-IN')}`;
};

export const getPlanPrice = (
  planId: string,
  billingType: 'Month' | 'Quarter' | 'Year',
  countryCode?: string
): string | null => {
  const code = countryCode || getStoredCountryCode();
  const plan = (planData.planList || []).find((item: any) => String(item.planId) === String(planId));
  if (!plan) return null;

  const priceObj = plan.planPrice.find((item: any) => item.type === billingType);
  if (!priceObj) return null;

  // Resolve country code to matching plan.json entries (IN or US)
  const isINR = isInrRegion(code);
  const targetCountry = isINR ? 'IN' : 'US';

  const amountObj = priceObj.amount.find((row: any) => row.country === targetCountry);
  return amountObj ? amountObj.amount : null;
};

export const getPlanSaving = (
  planId: string,
  billingType: 'Month' | 'Quarter' | 'Year'
): string | null => {
  const plan = (planData.planList || []).find((item: any) => String(item.planId) === String(planId));
  if (!plan) return null;

  const priceObj = plan.planPrice.find((item: any) => item.type === billingType);
  return priceObj?.Saving || null;
};
