'use client';

import { useEffect, useState, useRef } from 'react';
import { usePathname, useSearchParams } from 'next/navigation';
import posthog from 'posthog-js';

import { Suspense } from 'react';

export function PostHogPageView() {
  const pathname = usePathname();
  const searchParams = useSearchParams();

  useEffect(() => {
    const cookieConsent = localStorage.getItem('cookieConsent');
    if (cookieConsent === 'accepted' && pathname) {
      // If posthog is loaded, capture immediately
      if ((posthog as any)._loaded) {
        let url = window.origin + pathname;
        if (searchParams && searchParams.toString()) {
          url = url + `?${searchParams.toString()}`;
        }

        posthog.capture('$pageview', {
          $current_url: url,
        });
      } else {
        // If not loaded yet, wait for it
        posthog.onFeatureFlags(() => {
          let url = window.origin + pathname;
          if (searchParams && searchParams.toString()) {
            url = url + `?${searchParams.toString()}`;
          }
          posthog.capture('$pageview', {
            $current_url: url,
          });
        });
      }
    }
  }, [pathname, searchParams]);

  return null;
}

export function PostHogProvider({ children }: { children: React.ReactNode }) {
  useEffect(() => {
    const cookieConsent = localStorage.getItem('cookieConsent');

    if (cookieConsent === 'accepted') {
      const apiKey = process.env.NEXT_PUBLIC_POSTHOG_KEY;
      const apiHost = process.env.NEXT_PUBLIC_POSTHOG_HOST;

      if (!apiKey) {
        console.warn('PostHog API key not configured');
        return;
      }

      if (!(posthog as any)._loaded) {
        posthog.init(apiKey, {
          api_host: apiHost || 'https://us.i.posthog.com',
          person_profiles: 'identified_only',
          capture_pageview: false,
          capture_pageleave: true,
          autocapture: true,
          respect_dnt: true,
          opt_out_capturing_by_default: false,
        });

        if (process.env.NODE_ENV === 'development') {
          posthog.debug();
        }
      }
    }
  }, []);

  return (
    <>
      <Suspense fallback={null}>
        <PostHogPageView />
      </Suspense>
      {children}
    </>
  );
}

/**
 * Helper function to identify user after login
 */
export function identifyUser(userId: string, traits?: Record<string, any>) {
  const cookieConsent = localStorage.getItem('cookieConsent');
  if (cookieConsent === 'accepted' && (posthog as any)._loaded) {
    posthog.identify(userId, traits);
  }
}

/**
 * Helper function to track custom events
 */
export function trackEvent(eventName: string, properties?: Record<string, any>) {
  const cookieConsent = localStorage.getItem('cookieConsent');
  if (cookieConsent === 'accepted' && (posthog as any)._loaded) {
    posthog.capture(eventName, properties);
  }
}

/**
 * Helper function to reset user on logout
 */
export function resetUser() {
  const cookieConsent = localStorage.getItem('cookieConsent');
  if (cookieConsent === 'accepted' && (posthog as any)._loaded) {
    posthog.reset();
  }
}
