'use client'

/**
 * useAnalyticsLifecycle
 *
 * Wires the telemetry singleton to app-level state:
 *   - initializes telemetry on mount
 *   - fires a pageView when pathname or search params change
 *   - identifies the user when auth state settles, and resets on logout
 *
 * Framework-agnostic — the caller supplies the pathname, search params, and
 * user state from wherever they come from (Next's `usePathname()`, SvelteKit,
 * plain React Router, etc.).
 *
 * Apps typically call this once in a client component mounted inside their
 * root layout, replacing ad-hoc AnalyticsProvider.tsx copies.
 *
 * @example
 * 'use client'
 * import { useAnalyticsLifecycle } from '@startsimpli/analytics/hooks'
 * import { usePathname, useSearchParams } from 'next/navigation'
 * import { useAuth } from '@startsimpli/auth'
 *
 * export function AnalyticsLifecycle() {
 *   const pathname = usePathname()
 *   const searchParams = useSearchParams()
 *   const { user, isLoading } = useAuth()
 *   useAnalyticsLifecycle({ pathname, searchParams, user, isLoading })
 *   return null
 * }
 */

import { useEffect, useRef } from 'react'
import { telemetry } from '../telemetry'

export interface AnalyticsLifecycleUser {
  id?: string | null
  email?: string | null
  firstName?: string | null
  lastName?: string | null
  name?: string | null
}

export interface UseAnalyticsLifecycleArgs {
  /** Current route path — e.g. Next.js `usePathname()`. */
  pathname: string | null | undefined
  /** URLSearchParams-like object or null. Used to form the full URL for page views. */
  searchParams?: URLSearchParams | { toString(): string } | null
  /** The authenticated user, or null when logged out. undefined while loading. */
  user?: AnalyticsLifecycleUser | null
  /** True while the auth state is still hydrating. Prevents premature identify/reset churn. */
  isLoading?: boolean
  /**
   * False until the visitor may be tracked (see ConsentProvider's `trackingAllowed`). Nothing is
   * initialized, identified or page-viewed while false. Default true.
   */
  trackingAllowed?: boolean
}

function resolveName(user: AnalyticsLifecycleUser): string | undefined {
  if (user.name) return user.name
  const full = [user.firstName, user.lastName].filter(Boolean).join(' ')
  return full || undefined
}

export function useAnalyticsLifecycle({
  pathname,
  searchParams,
  user,
  isLoading,
  trackingAllowed = true,
}: UseAnalyticsLifecycleArgs): void {
  const initializedRef = useRef(false)
  const identifiedRef = useRef<string | null>(null)

  // Initialize telemetry once per mount.
  useEffect(() => {
    if (!trackingAllowed) return
    if (initializedRef.current) return
    initializedRef.current = true
    telemetry.initialize()
  }, [trackingAllowed])

  // Fire pageView on pathname/searchParams change.
  const searchKey = searchParams?.toString() ?? ''
  useEffect(() => {
    if (!pathname || !trackingAllowed) return
    const url = searchKey ? `${pathname}?${searchKey}` : pathname
    const title = typeof document !== 'undefined' ? document.title : undefined
    // Before the page view, so first-touch and click ids ride on it (and fill GA ids once gtag has set them).
    telemetry.captureAttribution()
    telemetry.pageView(url, title)
  }, [pathname, searchKey, trackingAllowed])

  // Identify user when auth settles; reset on logout.
  useEffect(() => {
    if (isLoading || !trackingAllowed) return

    if (user) {
      const userId = user.id || user.email || ''
      if (!userId) return
      if (identifiedRef.current !== userId) {
        identifiedRef.current = userId
        telemetry.identify({
          userId,
          email: user.email || undefined,
          name: resolveName(user),
        })
      }
    } else if (identifiedRef.current) {
      identifiedRef.current = null
      telemetry.reset()
    }
  }, [user, isLoading, trackingAllowed])
}
