export type UTMParams = {
  utm_source?: string | null
  utm_medium?: string | null
  utm_campaign?: string | null
  utm_content?: string | null
  utm_term?: string | null
}

const UTM_STORAGE_KEY = 'utm_params'

function parseUTMFromSearch(search: string): UTMParams {
  const params = new URLSearchParams(search)
  return {
    utm_source: params.get('utm_source'),
    utm_medium: params.get('utm_medium'),
    utm_campaign: params.get('utm_campaign'),
    utm_content: params.get('utm_content'),
    utm_term: params.get('utm_term'),
  }
}

export function initUTMTracking(customSearch?: string) {
  if (typeof window === 'undefined') return
  const search = typeof customSearch === 'string' ? customSearch : window.location.search
  if (!search) return
  const utm = parseUTMFromSearch(search)
  const hasAny = Object.values(utm).some(Boolean)
  if (!hasAny) return
  window.localStorage.setItem(UTM_STORAGE_KEY, JSON.stringify(utm))
}

export function getStoredUTMParams(): UTMParams {
  if (typeof window === 'undefined') return {}
  const raw = window.localStorage.getItem(UTM_STORAGE_KEY)
  if (!raw) return {}
  try {
    return JSON.parse(raw) as UTMParams
  } catch {
    return {}
  }
}

export function attachUTMToPayload<T extends object>(payload: T): T & UTMParams {
  const utm = getStoredUTMParams()
  return {
    ...payload,
    ...utm,
  }
}

declare global {
  interface Window {
    fbq?: (...args: any[]) => void
  }
}

type PixelLeadOptions = {
  eventName?: string
  value?: number
  currency?: string
  extra?: Record<string, any>
}

export function trackLeadWithPixel(options: PixelLeadOptions = {}) {
  if (typeof window === 'undefined' || typeof window.fbq !== 'function') return

  const utm = getStoredUTMParams()
  const eventName = options.eventName || 'Lead'

  const payload: Record<string, any> = {
    ...utm,
    ...options.extra,
  }

  if (typeof options.value === 'number') {
    payload.value = options.value
  }

  if (options.currency) {
    payload.currency = options.currency
  }

  window.fbq('track', eventName, payload)
}

