/**
 * First-party conversion-funnel step tracker.
 *
 * Each step posts one anonymous event to your own endpoint, at most once per
 * page view, and never holds up a navigation: navigator.sendBeacon, falling
 * back to fetch keepalive. No PII leaves the browser: a random visitor id kept
 * in localStorage (a cookie when storage is blocked), the path WITHOUT its
 * query, the referrer's host, and booleans for utm_source / gclid. Step names
 * and the endpoint are the app's config.
 */

export interface FunnelTrackerConfig<S extends string = string> {
  /** Where each step is POSTed (text/plain JSON body). */
  endpoint: string
  /** Prefix for the localStorage / sessionStorage / cookie keys, e.g. `myapp`. */
  storagePrefix: string
  /** Known step names; `isStep` narrows to these. Not enforced on `track`. */
  steps?: readonly S[]
  /** Max chars kept of `props.message`. Default 200. */
  messageMax?: number
}

export interface FunnelProps {
  signedIn?: boolean
  /** Free-form string attributes (plan, source, ...) sent as-is when set. */
  extra?: Record<string, string>
  message?: string
}

export interface FunnelTracker<S extends string = string> {
  track(step: S, props?: FunnelProps): void
  isStep(value: unknown): value is S
  /** Forget what this page view has sent (tests, soft navigation). */
  resetPageView(): void
  /** Report the page view's uncaught errors/rejections as `errorStep`. Returns the uninstaller. */
  installErrorCapture(errorStep: S, getSignedIn: () => boolean): () => void
}

function randomId(): string {
  try {
    if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') return crypto.randomUUID()
  } catch {
    /* fall through */
  }
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
    const r = (Math.random() * 16) | 0
    return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16)
  })
}

function readCookie(name: string): string | null {
  try {
    const m = document.cookie.match(new RegExp(`(?:^|; )${name}=([^;]*)`))
    return m ? decodeURIComponent(m[1]) : null
  } catch {
    return null
  }
}

function referrerHost(): string | null {
  try {
    return document.referrer ? new URL(document.referrer).host || null : null
  } catch {
    return null
  }
}

/** Mobile or desktop, from a user agent (server side: the request's own). */
export function deviceClass(userAgent: string | null | undefined): 'mobile' | 'desktop' {
  return userAgent && /Mobi|Android|iPhone|iPad|iPod|Windows Phone/i.test(userAgent) ? 'mobile' : 'desktop'
}

export function createFunnelTracker<S extends string = string>(config: FunnelTrackerConfig<S>): FunnelTracker<S> {
  const visitorKey = `${config.storagePrefix}:vid`
  const adKey = `${config.storagePrefix}:ad`
  const cookieName = `${config.storagePrefix}_vid`
  const messageMax = config.messageMax ?? 200
  let sent = new Set<string>()
  let memoryVisitorId: string | null = null
  let memoryAd = false

  function visitorId(): string {
    try {
      const stored = localStorage.getItem(visitorKey)
      if (stored) return stored
      const id = randomId()
      localStorage.setItem(visitorKey, id)
      return id
    } catch {
      /* storage blocked: try a cookie */
    }
    const fromCookie = readCookie(cookieName)
    if (fromCookie) return fromCookie
    memoryVisitorId ??= randomId()
    try {
      document.cookie = `${cookieName}=${memoryVisitorId}; path=/; max-age=31536000; samesite=lax`
    } catch {
      /* ignore */
    }
    return memoryVisitorId
  }

  /** Whether this visit landed from an ad, remembered for the visit so a sign-up round trip still says so. */
  function adVisit(params: URLSearchParams): boolean {
    const fromAd = params.has('utm_source') || params.has('gclid')
    try {
      if (fromAd) sessionStorage.setItem(adKey, '1')
      return fromAd || sessionStorage.getItem(adKey) === '1'
    } catch {
      memoryAd ||= fromAd
      return memoryAd
    }
  }

  function send(body: string): void {
    try {
      if (typeof navigator !== 'undefined' && typeof navigator.sendBeacon === 'function' && navigator.sendBeacon(config.endpoint, body)) return
    } catch {
      /* fall back */
    }
    try {
      void fetch(config.endpoint, { method: 'POST', body, keepalive: true, headers: { 'content-type': 'text/plain' } }).catch(() => {})
    } catch {
      /* nothing else to try */
    }
  }

  const tracker: FunnelTracker<S> = {
    track(step, props = {}) {
      try {
        if (typeof window === 'undefined') return
        const pathname = window.location.pathname
        const key = `${pathname}|${step}`
        if (sent.has(key)) return
        sent.add(key)
        const params = new URLSearchParams(window.location.search)
        const body: Record<string, unknown> = {
          step,
          visitorId: visitorId(),
          path: pathname,
          referrerHost: referrerHost(),
          utmSource: params.has('utm_source'),
          gclid: params.has('gclid'),
          ad: adVisit(params),
          signedIn: props.signedIn === true,
          ...props.extra,
        }
        if (typeof props.message === 'string') body.message = props.message.slice(0, messageMax)
        send(JSON.stringify(body))
      } catch {
        /* tracking must never break the page */
      }
    },
    isStep(value): value is S {
      return config.steps ? (config.steps as readonly unknown[]).includes(value) : typeof value === 'string'
    },
    resetPageView() {
      sent = new Set()
    },
    installErrorCapture(errorStep, getSignedIn) {
      if (typeof window === 'undefined') return () => {}
      const report = (message: unknown) => tracker.track(errorStep, { signedIn: getSignedIn(), message: String(message ?? 'unknown error') })
      const onError = (e: ErrorEvent) => report(e.message || e.error?.message)
      const onRejection = (e: PromiseRejectionEvent) => {
        const reason = e.reason as { message?: unknown } | undefined
        report(reason?.message ?? reason)
      }
      window.addEventListener('error', onError)
      window.addEventListener('unhandledrejection', onRejection)
      return () => {
        window.removeEventListener('error', onError)
        window.removeEventListener('unhandledrejection', onRejection)
      }
    },
  }
  return tracker
}
