'use client'

/**
 * ConsentProvider: decides whether this visitor must opt in (by country), remembers the choice,
 * and turns analytics on or off to match: Google consent mode, PostHog (events and session
 * replay) and the telemetry singleton (which also gates click-id capture).
 *
 * Outside the consent regions (e.g. the US) nothing changes: tracking is on, no banner.
 * Inside them (or country unknown), nothing is tracked until the visitor accepts.
 *
 * Mount once in the root layout, above the analytics lifecycle component, and pass `country`
 * from the edge header (see countryFromHeaders).
 */

import { createContext, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useState, type ReactNode } from 'react'
import { telemetry } from '../telemetry'
import { gtag } from '../gtag-queue'
import { DEFAULT_CONSENT_REGIONS, consentRequired } from './regions'
import { CONSENT_KEY, clearConsent, effectiveChoice, writeConsent, type ConsentChoice } from './state'

export interface ConsentContextValue {
  /** The visitor is in a region that needs opt-in. */
  required: boolean
  /** Their choice, or null while undecided. */
  choice: ConsentChoice | null
  /** Analytics may run now: not required, or accepted. */
  trackingAllowed: boolean
  /** Show the banner: required and undecided, or the visitor reopened the settings. */
  bannerOpen: boolean
  accept(): void
  reject(): void
  /** Reopen the banner so the choice can be changed (footer link). */
  reopen(): void
}

const ConsentContext = createContext<ConsentContextValue>({
  required: false,
  choice: null,
  trackingAllowed: true,
  bannerOpen: false,
  accept() {},
  reject() {},
  reopen() {},
})

export function useConsent(): ConsentContextValue {
  return useContext(ConsentContext)
}

export interface ConsentProviderProps {
  /** ISO country of the visitor, when the host already knows it (e.g. read from a header in a dynamic layout). */
  country?: string | null
  /**
   * For static / cached pages: a same-origin endpoint returning `{ country: "DE" | null }` (see
   * countryFromHeaders). Fetched on mount; until it answers, nothing is tracked and no banner shows;
   * a failure or null counts as unknown = consent required. Used only when `country` is not passed.
   */
  geoEndpoint?: string
  /** Regions that need opt-in. Default: EEA + UK + Switzerland. */
  regions?: readonly string[]
  storageKey?: string
  children?: ReactNode
}

function applyGoogleConsent(granted: boolean) {
  const value = granted ? 'granted' : 'denied'
  gtag('consent', 'update', {
    ad_storage: value,
    ad_user_data: value,
    ad_personalization: value,
    analytics_storage: value,
  })
}

export function ConsentProvider({
  country: countryProp,
  geoEndpoint,
  regions = DEFAULT_CONSENT_REGIONS,
  storageKey = CONSENT_KEY,
  children,
}: ConsentProviderProps) {
  const [fetched, setFetched] = useState<{ country: string | null } | null>(null)
  const countryKnown = countryProp !== undefined || !geoEndpoint || fetched !== null
  const country = countryProp !== undefined ? countryProp : fetched?.country ?? null
  // Until the country is known, assume consent is required (nothing tracked, no banner yet).
  const required = countryKnown ? consentRequired(country, regions) : true
  // Read the stored choice after mount so server and first client render agree.
  const [choice, setChoice] = useState<ConsentChoice | null>(null)
  const [ready, setReady] = useState(false)
  const [reopened, setReopened] = useState(false)

  useEffect(() => {
    if (countryProp !== undefined || !geoEndpoint) return
    let live = true
    fetch(geoEndpoint, { cache: 'no-store' })
      .then((r) => (r.ok ? r.json() : null))
      .then((j: { country?: string | null } | null) => live && setFetched({ country: j?.country ?? null }))
      .catch(() => live && setFetched({ country: null }))
    return () => {
      live = false
    }
  }, [countryProp, geoEndpoint])

  useEffect(() => {
    setChoice(effectiveChoice(storageKey))
    setReady(true)
  }, [storageKey])

  const trackingAllowed = !required || choice === 'accepted'

  // A layout effect, so on the commit where Accept lets the children mount, the opt-in has already run before
  // their (passive) effects first call telemetry; otherwise those first events find it still opted out and are dropped.
  useLayoutEffect(() => {
    if (!ready || !countryKnown) return
    // Not required: grant (a host with a static page defaults Google to denied until the country is known).
    if (!required) {
      applyGoogleConsent(true)
      return
    }
    applyGoogleConsent(choice === 'accepted')
    if (choice === 'accepted') telemetry.optIn()
    else telemetry.optOut()
  }, [ready, required, choice, countryKnown])

  const accept = useCallback(() => {
    writeConsent('accepted', storageKey)
    setChoice('accepted')
    setReopened(false)
  }, [storageKey])
  const reject = useCallback(() => {
    writeConsent('rejected', storageKey)
    setChoice('rejected')
    setReopened(false)
  }, [storageKey])
  const reopen = useCallback(() => {
    clearConsent(storageKey)
    setReopened(true)
  }, [storageKey])

  const value = useMemo<ConsentContextValue>(
    () => ({
      required,
      choice,
      trackingAllowed,
      bannerOpen: ready && countryKnown && required && (choice === null || reopened),
      accept,
      reject,
      reopen,
    }),
    [required, choice, trackingAllowed, ready, countryKnown, reopened, accept, reject, reopen],
  )

  return <ConsentContext.Provider value={value}>{children}</ConsentContext.Provider>
}
