/**
 * PostHog Analytics Tracker
 *
 * Implements 4 critical conversion funnels:
 * 1. Visitor → Lead (Landing → Contact/Demo)
 * 2. Lead → Trial (Signup → Email Verified → Trial Started)
 * 3. Trial → Paid (Trial Started → Subscription Created → First Payment)
 * 4. Feature Usage (Dashboard Views → Feature Interactions → Goals Completed)
 */

import { posthog } from 'posthog-js';

// NOTE: Do not import logger here - this file runs on client-side only
// and logger uses server-only modules (async_hooks via correlation-id)

// ============================================================================
// PostHog Initialization (Client-side only)
// ============================================================================

export function 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) {
    // Use console.warn for client-side logging
    console.warn('[PostHog] API key not configured');
    return;
  }

  posthog.init(apiKey, {
    api_host: apiHost,
    loaded: (posthog) => {
      if (process.env.NODE_ENV === 'development') {
        posthog.opt_out_capturing(); // Disable in dev
      }
    },
    capture_pageview: false, // We'll manually track pageviews
    autocapture: true,

    // ============================================================================
    // HEATMAPS CONFIGURATION - Enabled for top 5 pages
    // ============================================================================
    enable_heatmaps: true, // Enable click and scroll heatmaps

    // ============================================================================
    // SESSION RECORDING CONFIGURATION
    // ============================================================================
    session_recording: {
      // Record cross-origin iframes (e.g., embedded payment forms)
      recordCrossOriginIframes: true,

      // Mask all text inputs by default for privacy (GDPR/CCPA compliance)
      maskAllInputs: true,

      // Mask specific input types
      maskInputOptions: {
        password: true,
        email: true,
        color: false,
        date: false,
        'datetime-local': false,
        month: false,
        number: false,
        range: false,
        search: false,
        tel: true,
        text: true,
        time: false,
        url: false,
        week: false,
        textarea: true,
        select: false,
      },

      // CSS selectors for elements to mask (PII protection)
      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*="otp"], input[name*="code"], [data-sensitive], [data-private], [data-pii], .sensitive-data, .private-info, .pii-field, .user-email, .phone-number, .credit-card, .stripe-element, .payment-info, .billing-info',
    },

    // Privacy settings
    respect_dnt: true, // Respect Do Not Track header
  });
}

// ============================================================================
// FUNNEL 1: Visitor → Lead
// Events: page_view → lead_form_viewed → lead_form_submitted → lead_created
// ============================================================================

export function trackPageView(page: string, properties?: Record<string, unknown>) {
  if (typeof window === 'undefined') return;

  posthog.capture('page_view', {
    page,
    page_title: document.title,
    ...properties,
  });
}

export function trackLeadFormViewed(formType: 'contact' | 'demo' | 'newsletter') {
  if (typeof window === 'undefined') return;

  posthog.capture('lead_form_viewed', {
    form_type: formType,
    page: window.location.pathname,
  });
}

export function trackLeadFormSubmitted(
  formType: 'contact' | 'demo' | 'newsletter',
  properties?: Record<string, unknown>
) {
  if (typeof window === 'undefined') return;

  posthog.capture('lead_form_submitted', {
    form_type: formType,
    page: window.location.pathname,
    ...properties,
  });
}

export function trackLeadCreated(
  leadType: 'contact' | 'demo' | 'newsletter',
  properties?: Record<string, unknown>
) {
  if (typeof window === 'undefined') return;

  posthog.capture('lead_created', {
    lead_type: leadType,
    ...properties,
  });
}

// ============================================================================
// FUNNEL 2: Lead → Trial
// Events: signup_started → email_verified → trial_started
// ============================================================================

export function trackSignupStarted(method: 'email' | 'google' | 'oauth') {
  if (typeof window === 'undefined') return;

  posthog.capture('signup_started', {
    signup_method: method,
    page: window.location.pathname,
  });
}

export function trackEmailVerified(userId: string) {
  if (typeof window === 'undefined') return;

  posthog.capture('email_verified', {
    user_id: userId,
  });

  // Identify user in PostHog
  posthog.identify(userId);
}

export function trackTrialStarted(
  userId: string,
  packageTier: string,
  properties?: Record<string, unknown>
) {
  if (typeof window === 'undefined') return;

  posthog.capture('trial_started', {
    user_id: userId,
    package_tier: packageTier,
    ...properties,
  });

  // Set user properties
  posthog.people.set({
    package_tier: packageTier,
    trial_started_at: new Date().toISOString(),
  });
}

// ============================================================================
// FUNNEL 3: Trial → Paid
// Events: trial_started → checkout_initiated → subscription_created → first_payment
// ============================================================================

export function trackCheckoutInitiated(
  packageTier: string,
  billingCycle: 'monthly' | 'annual',
  amount: number
) {
  if (typeof window === 'undefined') return;

  posthog.capture('checkout_initiated', {
    package_tier: packageTier,
    billing_cycle: billingCycle,
    amount,
    currency: 'USD',
  });
}

export function trackSubscriptionCreated(
  userId: string,
  packageTier: string,
  billingCycle: 'monthly' | 'annual',
  amount: number
) {
  if (typeof window === 'undefined') return;

  posthog.capture('subscription_created', {
    user_id: userId,
    package_tier: packageTier,
    billing_cycle: billingCycle,
    amount,
    currency: 'USD',
  });

  // Update user properties
  posthog.people.set({
    package_tier: packageTier,
    billing_cycle: billingCycle,
    subscription_status: 'active',
    converted_at: new Date().toISOString(),
  });
}

export function trackFirstPayment(
  userId: string,
  amount: number,
  packageTier: string
) {
  if (typeof window === 'undefined') return;

  posthog.capture('first_payment', {
    user_id: userId,
    amount,
    currency: 'USD',
    package_tier: packageTier,
  });

  // Update user properties
  posthog.people.set({
    first_payment_at: new Date().toISOString(),
    lifetime_value: amount,
  });
}

// ============================================================================
// FUNNEL 4: Feature Usage
// Events: dashboard_viewed → feature_clicked → feature_completed → goal_achieved
// ============================================================================

export function trackDashboardViewed(userId: string, tab?: string) {
  if (typeof window === 'undefined') return;

  posthog.capture('dashboard_viewed', {
    user_id: userId,
    tab: tab || 'overview',
  });
}

export function trackFeatureClicked(
  featureName: string,
  properties?: Record<string, unknown>
) {
  if (typeof window === 'undefined') return;

  posthog.capture('feature_clicked', {
    feature_name: featureName,
    page: window.location.pathname,
    ...properties,
  });
}

export function trackFeatureCompleted(
  featureName: string,
  properties?: Record<string, unknown>
) {
  if (typeof window === 'undefined') return;

  posthog.capture('feature_completed', {
    feature_name: featureName,
    ...properties,
  });
}

export function trackGoalAchieved(
  goalName: string,
  properties?: Record<string, unknown>
) {
  if (typeof window === 'undefined') return;

  posthog.capture('goal_achieved', {
    goal_name: goalName,
    ...properties,
  });
}

// ============================================================================
// Additional Tracking Events
// ============================================================================

export function trackButtonClick(
  buttonName: string,
  location: string,
  properties?: Record<string, unknown>
) {
  if (typeof window === 'undefined') return;

  posthog.capture('button_clicked', {
    button_name: buttonName,
    location,
    page: window.location.pathname,
    ...properties,
  });
}

export function trackFormError(
  formType: string,
  errorMessage: string,
  field?: string
) {
  if (typeof window === 'undefined') return;

  posthog.capture('form_error', {
    form_type: formType,
    error_message: errorMessage,
    field,
    page: window.location.pathname,
  });
}

export function trackSearchPerformed(
  searchTerm: string,
  resultsCount: number,
  location: string
) {
  if (typeof window === 'undefined') return;

  posthog.capture('search_performed', {
    search_term: searchTerm,
    results_count: resultsCount,
    location,
  });
}

export function trackIntegrationConnected(
  integrationType: string,
  userId: string
) {
  if (typeof window === 'undefined') return;

  posthog.capture('integration_connected', {
    integration_type: integrationType,
    user_id: userId,
  });

  // Update user properties
  posthog.people.set({
    [`integration_${integrationType}`]: true,
  });
}

export function trackWorkflowCreated(
  userId: string,
  workflowType: string,
  properties?: Record<string, unknown>
) {
  if (typeof window === 'undefined') return;

  posthog.capture('workflow_created', {
    user_id: userId,
    workflow_type: workflowType,
    ...properties,
  });
}

export function trackWorkflowExecuted(
  userId: string,
  workflowId: string,
  success: boolean,
  properties?: Record<string, unknown>
) {
  if (typeof window === 'undefined') return;

  posthog.capture('workflow_executed', {
    user_id: userId,
    workflow_id: workflowId,
    success,
    ...properties,
  });
}

// ============================================================================
// User Identification & Properties
// ============================================================================

export function identifyUser(
  userId: string,
  properties?: Record<string, unknown>
) {
  if (typeof window === 'undefined') return;

  posthog.identify(userId, properties);
}

export function setUserProperties(properties: Record<string, unknown>) {
  if (typeof window === 'undefined') return;

  posthog.people.set(properties);
}

export function resetUser() {
  if (typeof window === 'undefined') return;

  posthog.reset();
}

// ============================================================================
// Group Analytics (for organizations)
// ============================================================================

export function identifyOrganization(
  organizationId: string,
  properties?: Record<string, unknown>
) {
  if (typeof window === 'undefined') return;

  posthog.group('organization', organizationId, properties);
}

// ============================================================================
// Feature Flags
// ============================================================================

export function isFeatureEnabled(featureName: string): boolean {
  if (typeof window === 'undefined') return false;

  return posthog.isFeatureEnabled(featureName) ?? false;
}

export function getFeatureFlagPayload(featureName: string): unknown {
  if (typeof window === 'undefined') return null;

  return posthog.getFeatureFlagPayload(featureName);
}

// ============================================================================
// Funnel Helper - Track complete funnel step
// ============================================================================

export function trackFunnelStep(
  funnelName: 'visitor_to_lead' | 'lead_to_trial' | 'trial_to_paid' | 'feature_usage',
  stepName: string,
  properties?: Record<string, unknown>
) {
  if (typeof window === 'undefined') return;

  posthog.capture(`${funnelName}_${stepName}`, {
    funnel: funnelName,
    step: stepName,
    ...properties,
  });
}
