/**
 * PostHog Analytics Provider
 *
 * Provides client-side analytics with heatmaps, session recordings, and feature flags
 *
 * Features:
 * - Heatmaps for user interaction tracking
 * - Session recordings with PII masking
 * - Custom event tracking
 * - Feature flags
 * - A/B testing
 * - Conditional recording for high-value sessions
 * - Privacy-first configuration
 */

import posthog from 'posthog-js';

export const initPostHog = () => {
  if (typeof window === 'undefined') return;

  const apiKey = process.env.NEXT_PUBLIC_POSTHOG_KEY;
  const apiHost = process.env.NEXT_PUBLIC_POSTHOG_HOST || 'https://app.posthog.com';

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

  // Initialize PostHog with heatmap and session recording configuration
  posthog.init(apiKey, {
    api_host: apiHost,

    // Heatmap Configuration
    enable_heatmaps: true, // Enable click and scroll heatmaps

    // Session Recording Configuration with PII Masking
    enable_recording_console_log: false, // Disable console logs to prevent PII leakage
    session_recording: {
      // Don't record cross-origin iframes for security
      recordCrossOriginIframes: false,

      // Mask all text inputs by default for privacy
      maskAllInputs: true,

      // Mask specific input types
      maskInputOptions: {
        password: true,
        email: true,
      },

      // CSS selectors for elements to mask
      maskTextSelector: 'input[type="email"], input[type="password"], input[type="tel"], input[name*="phone"], input[name*="email"], input[name*="card"], input[name*="credit"], input[name*="cvv"], input[name*="ssn"], input[name*="passport"], input[name*="national"], input[name*="id"], [data-sensitive], [data-private], [data-pii], .sensitive-data, .private-info, .pii-field, .user-email, .phone-number, .credit-card, .staff-email, .customer-email, .patient-name, .stripe-element, .payment-info, .billing-info, .personal-id, .tax-id, .social-security',

      // Custom masking function for additional privacy
      maskInputFn: (text: string, element?: Element | null) => {
        if (!element) return text;

        // Check if element or parent has sensitive data attributes
        if (
          element.hasAttribute('data-sensitive') ||
          element.hasAttribute('data-private') ||
          element.hasAttribute('data-pii') ||
          element.closest('[data-sensitive]') ||
          element.closest('[data-private]') ||
          element.closest('[data-pii]')
        ) {
          return '***MASKED***';
        }

        // Check for sensitive input types
        const inputType = element.getAttribute('type')?.toLowerCase();
        if (
          inputType === 'password' ||
          inputType === 'email' ||
          inputType === 'tel'
        ) {
          return '***MASKED***';
        }

        // Check for sensitive field names
        const name = element.getAttribute('name')?.toLowerCase() || '';
        const id = element.getAttribute('id')?.toLowerCase() || '';
        const sensitiveName = ['email', 'phone', 'password', 'card', 'cvv', 'ssn', 'passport', 'otp', 'code'];
        if (sensitiveName.some(s => name.includes(s) || id.includes(s))) {
          return '***MASKED***';
        }

        return text;
      },
    },

    // Autocapture Configuration
    autocapture: true,

    // Privacy Settings - GDPR/CCPA compliant
    mask_all_text: false, // Use selective masking via maskTextSelector
    mask_all_element_attributes: false,
    respect_dnt: true, // Respect Do Not Track

    // Performance and Privacy
    loaded: (ph) => {
      // Set up conditional session recording based on user value
      conditionallyStartRecording(ph as any);

      if (process.env.NODE_ENV === 'development') {
        console.log('PostHog initialized with PII masking enabled');
      }
    },
  });

  return posthog;
};

/**
 * Conditionally start session recording for high-value sessions
 *
 * Recording triggers:
 * - User is authenticated
 * - User is on checkout/payment flow
 * - User submitted a demo booking
 * - User is staff member
 * - Error occurred (for debugging)
 * - 10% sample rate for regular sessions
 */
function conditionallyStartRecording(posthogInstance: typeof posthog) {
  // Check if we should record this session
  const shouldRecord =
    isHighValueSession() ||
    Math.random() < 0.1; // 10% sample rate for regular sessions

  if (shouldRecord) {
    posthogInstance.startSessionRecording();
  }
}

/**
 * Determine if current session is high-value
 */
function isHighValueSession(): boolean {
  // Check URL patterns for high-value pages
  const path = window.location.pathname;
  const highValuePaths = [
    '/checkout',
    '/payment',
    '/signup',
    '/onboarding',
    '/staff',
    '/demo',
    '/billing',
    '/subscribe',
  ];

  return highValuePaths.some(p => path.includes(p));
}

/**
 * Manually trigger session recording for important user flows
 */
export const startSessionRecording = () => {
  if (typeof window === 'undefined') return;
  posthog.startSessionRecording();
};

/**
 * Stop session recording (privacy control)
 */
export const stopSessionRecording = () => {
  if (typeof window === 'undefined') return;
  posthog.stopSessionRecording();
};

/**
 * Track custom events
 */
export const trackEvent = (eventName: string, properties?: Record<string, unknown>) => {
  if (typeof window === 'undefined') return;
  posthog.capture(eventName, properties);
};

/**
 * Track high-value events that should trigger recording
 *
 * Use this for important business events like:
 * - Signup completed
 * - Payment submitted
 * - Demo booked
 * - Important form submissions
 * - Critical errors
 */
export const trackHighValueEvent = (eventName: string, properties?: Record<string, unknown>) => {
  if (typeof window === 'undefined') return;

  // Start recording for this session
  startSessionRecording();

  // Track the event with high_value flag
  trackEvent(eventName, {
    ...properties,
    high_value: true,
  });
};

/**
 * Identify user for personalized tracking
 */
export const identifyUser = (userId: string, properties?: Record<string, unknown>) => {
  if (typeof window === 'undefined') return;
  posthog.identify(userId, properties);
};

/**
 * Track page view with custom properties
 */
export const trackPageView = (pageName: string, properties?: Record<string, unknown>) => {
  if (typeof window === 'undefined') return;
  posthog.capture('$pageview', {
    page: pageName,
    ...properties,
  });
};

/**
 * Enable/disable heatmaps dynamically
 */
export const toggleHeatmaps = (enabled: boolean) => {
  if (typeof window === 'undefined') return;

  if (enabled) {
    posthog.startSessionRecording();
  } else {
    posthog.stopSessionRecording();
  }
};

/**
 * Reset user session (on logout)
 */
export const resetSession = () => {
  if (typeof window === 'undefined') return;
  posthog.reset();
};

export default posthog;
