const POSTHOG_KEY = process.env.NEXT_PUBLIC_POSTHOG_KEY
const POSTHOG_HOST = process.env.NEXT_PUBLIC_POSTHOG_HOST ?? 'https://eu.i.posthog.com'
const COOKIE_CONSENT_KEY = 'innungsapp_cookie_consent'
const COOKIE_CONSENT_EVENT = 'innungsapp:cookie-consent-granted'

export {}

type PostHogApi = {
  __SV?: number
  init?: (token: string, config: Record<string, unknown>) => void
  capture?: (event: string, properties?: Record<string, unknown>) => void
  opt_in_capturing?: () => void
  opt_out_capturing?: () => void
}

declare global {
  interface Window {
    posthog?: PostHogApi
    __innungsappPosthogInitialized?: boolean
  }
}

function ensurePosthogSnippetLoaded() {
  const w = window as any
  if (w.posthog?.__SV) return

  ;(function loadSnippet(doc: Document, ph: any) {
    const base: any = Array.isArray(ph) ? ph : []
    if (base.__SV) return

    w.posthog = base
    base._i = base._i || []

    base.init = function init(token: string, config: Record<string, unknown>, name?: string) {
      const target = name ? (base[name] = base[name] || []) : base

      const setMethod = (obj: any, method: string) => {
        obj[method] = function methodStub(...args: unknown[]) {
          obj.push([method, ...args])
        }
      }

      const methods = [
        'capture',
        'identify',
        'alias',
        'group',
        'set_config',
        'reset',
        'register',
        'register_once',
        'unregister',
        'opt_in_capturing',
        'opt_out_capturing',
        'has_opted_in_capturing',
        'has_opted_out_capturing',
        'isFeatureEnabled',
        'reloadFeatureFlags',
      ]

      methods.forEach((method) => setMethod(target, method))

      target.people = target.people || []
      const peopleMethods = ['set', 'set_once', 'unset', 'increment', 'append', 'union', 'track_charge', 'clear_charges', 'delete_user']
      peopleMethods.forEach((method) => setMethod(target.people, method))

      const script = doc.createElement('script')
      script.type = 'text/javascript'
      script.async = true
      script.src = `${(config.api_host as string).replace('.i.posthog.com', '-assets.i.posthog.com')}/static/array.js`
      const firstScript = doc.getElementsByTagName('script')[0]
      if (firstScript?.parentNode) {
        firstScript.parentNode.insertBefore(script, firstScript)
      } else {
        doc.head.appendChild(script)
      }

      base._i.push([token, config, name])
    }

    base.__SV = 1
  })(document, w.posthog || [])
}

function initPosthog() {
  if (typeof window === 'undefined' || !POSTHOG_KEY) return
  if (window.__innungsappPosthogInitialized) return

  ensurePosthogSnippetLoaded()

  window.posthog?.init?.(POSTHOG_KEY, {
    api_host: POSTHOG_HOST,
    defaults: '2026-01-30',
    autocapture: false,
    capture_pageview: false,
    respect_dnt: true,
  })

  window.__innungsappPosthogInitialized = true
}

if (typeof window !== 'undefined' && POSTHOG_KEY) {
  const consent = window.localStorage.getItem(COOKIE_CONSENT_KEY)
  if (consent === 'accepted') {
    initPosthog()
  }

  window.addEventListener(COOKIE_CONSENT_EVENT, initPosthog)
}
