// Standard API response shapes

export interface ApiSuccess<T> {
  data: T
}

export interface ApiPaginated<T> {
  data: T[]
  total: number
  page: number
  pageSize: number
  totalPages: number
}

export interface ApiError {
  error: string
  message: string
  statusCode: number
  [key: string]: unknown
}

// Plan prices in smallest currency unit (MAD, in centimes)
export const PLAN_PRICES: Record<string, Record<string, Record<string, number>>> = {
  STARTER: {
    MONTHLY: { MAD: 14900 },
    ANNUAL:  { MAD: 143040 },
  },
  GROWTH: {
    MONTHLY: { MAD: 29900 },
    ANNUAL:  { MAD: 287040 },
  },
  PRO: {
    MONTHLY: { MAD: 39900 },
    ANNUAL:  { MAD: 383040 },
  },
}

export const PLAN_FEATURES: Record<string, string[]> = {
  STARTER: [
    'Up to 10 vehicles',
    '1 user account',
    'Basic analytics',
    'Carplace listing',
  ],
  GROWTH: [
    'Up to 50 vehicles',
    '5 user accounts',
    'Full analytics',
    'Priority Carplace placement',
    'Custom branding',
  ],
  PRO: [
    'Unlimited vehicles',
    'Unlimited user accounts',
    'Advanced reports',
    'API access',
    'Dedicated support',
  ],
}

export type Locale = 'en' | 'fr' | 'ar'
export type SupportedCurrency = 'MAD'

function resolveLocale(locale?: Locale): Locale {
  if (locale) return locale

  const lang =
    typeof globalThis === 'object' && 'document' in globalThis
      ? (globalThis as { document?: { documentElement?: { lang?: string } } }).document?.documentElement?.lang
      : undefined

  if (lang === 'en' || lang === 'fr' || lang === 'ar') {
    return lang
  }

  return 'en'
}

export function getCurrencyLabel(locale?: Locale, _currency: SupportedCurrency = 'MAD'): string {
  return resolveLocale(locale) === 'ar' ? 'درهم' : 'MAD'
}

export function formatCurrency(amount: number, _currency: SupportedCurrency = 'MAD', locale?: Locale): string {
  const resolvedLocale = resolveLocale(locale)
  const divisor = 100
  const value = amount / divisor
  const localeMap: Record<Locale, string> = { en: 'en-US', fr: 'fr-FR', ar: 'ar-MA' }
  const formattedValue = new Intl.NumberFormat(localeMap[resolvedLocale], {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2,
  }).format(value)
  const currencyLabel = getCurrencyLabel(resolvedLocale, _currency)

  return resolvedLocale === 'en'
    ? `${currencyLabel} ${formattedValue}`
    : `${formattedValue} ${currencyLabel}`
}
