'use client'
import posthog from 'posthog-js'
import { PostHogProvider as PHProvider } from 'posthog-js/react'
import { useEffect } from 'react'
import PostHogPageView from './PostHogPageView'

export function PostHogProvider({ children }: { children: React.ReactNode }) {
    useEffect(() => {
        const posthogKey = process.env.NEXT_PUBLIC_POSTHOG_KEY
        if (typeof window !== 'undefined' && !posthog.__loaded && posthogKey) {
            posthog.init(posthogKey, {
                api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST || 'https://us.i.posthog.com',
                capture_pageview: false,
                capture_pageleave: true,
                persistence: 'localStorage+cookie',
                opt_out_capturing_by_default: true,
                debug: process.env.NODE_ENV === 'development',
            })
        }
    }, [])

    return <PHProvider client={posthog}>
        <PostHogPageView />
        {children}
    </PHProvider>
}
