/**
 * PostHog Analytics Wrapper
 * Provides type-safe analytics tracking with privacy controls
 */

import posthog from "posthog-js";
import { logger } from "@/lib/logger";

export interface PostHogConfig {
  apiKey: string;
  apiHost?: string;
  options?: {
    autocapture?: boolean;
    capture_pageview?: boolean;
    capture_pageleave?: boolean;
    persistence?: "localStorage" | "cookie" | "memory";
    disable_session_recording?: boolean;
    enable_heatmaps?: boolean;
  };
}

export interface UserProperties {
  email?: string;
  name?: string;
  organizationId?: string;
  role?: string;
  package?: string;
  locale?: string;
}

export interface EventProperties {
  [key: string]: string | number | boolean | null | undefined;
}

class PostHogClient {
  private initialized = false;
  private enabled = false;

  /**
   * Initialize PostHog with configuration
   */
  init(config: PostHogConfig): void {
    if (typeof window === "undefined") {
      return;
    }

    if (this.initialized) {
      logger.warn("PostHog already initialized");
      return;
    }

    try {
      posthog.init(config.apiKey, {
        api_host: config.apiHost || "https://app.posthog.com",
        autocapture: config.options?.autocapture ?? false,
        capture_pageview: config.options?.capture_pageview ?? false,
        capture_pageleave: config.options?.capture_pageleave ?? true,
        persistence: config.options?.persistence ?? "localStorage",
        disable_session_recording:
          config.options?.disable_session_recording ?? true,

        // ============================================================================
        // HEATMAPS CONFIGURATION - Enabled for top 5 pages
        // ============================================================================
        enable_heatmaps: config.options?.enable_heatmaps ?? true,

        // Session recording with privacy controls
        session_recording: {
          maskAllInputs: true,
          maskInputOptions: {
            password: true,
            email: true,
            tel: true,
          },
        },

        loaded: (posthog) => {
          if (process.env.NODE_ENV === "development") {
            posthog.debug();
          }
        },
      });

      this.initialized = true;
      this.enabled = true;
    } catch (error) {
      logger.error("Failed to initialize PostHog", error);
      this.enabled = false;
    }
  }

  /**
   * Identify user with properties
   */
  identify(userId: string, properties?: UserProperties): void {
    if (!this.canTrack()) return;

    try {
      posthog.identify(userId, properties);
    } catch (error) {
      logger.error("PostHog identify error", error);
    }
  }

  /**
   * Track custom event
   */
  capture(eventName: string, properties?: EventProperties): void {
    if (!this.canTrack()) return;

    try {
      posthog.capture(eventName, properties);
    } catch (error) {
      logger.error("PostHog capture error", error);
    }
  }

  /**
   * Track page view
   */
  capturePageview(properties?: EventProperties): void {
    if (!this.canTrack()) return;

    try {
      posthog.capture("$pageview", properties);
    } catch (error) {
      logger.error("PostHog pageview error", error);
    }
  }

  /**
   * Reset user identity (on logout)
   */
  reset(): void {
    if (!this.canTrack()) return;

    try {
      posthog.reset();
    } catch (error) {
      logger.error("PostHog reset error", error);
    }
  }

  /**
   * Set user properties without identifying
   */
  setPersonProperties(properties: UserProperties): void {
    if (!this.canTrack()) return;

    try {
      posthog.people.set(properties);
    } catch (error) {
      logger.error("PostHog set properties error", error);
    }
  }

  /**
   * Get feature flag value
   */
  getFeatureFlag(key: string): string | boolean | undefined {
    if (!this.canTrack()) return undefined;

    try {
      return posthog.getFeatureFlag(key);
    } catch (error) {
      logger.error("PostHog feature flag error", error);
      return undefined;
    }
  }

  /**
   * Check if feature flag is enabled
   */
  isFeatureEnabled(key: string): boolean {
    if (!this.canTrack()) return false;

    try {
      return posthog.isFeatureEnabled(key) ?? false;
    } catch (error) {
      logger.error("PostHog feature flag error", error);
      return false;
    }
  }

  /**
   * Opt user out of tracking
   */
  optOut(): void {
    if (!this.initialized) return;

    try {
      posthog.opt_out_capturing();
      this.enabled = false;
    } catch (error) {
      logger.error("PostHog opt-out error", error);
    }
  }

  /**
   * Opt user in to tracking
   */
  optIn(): void {
    if (!this.initialized) return;

    try {
      posthog.opt_in_capturing();
      this.enabled = true;
    } catch (error) {
      logger.error("PostHog opt-in error", error);
    }
  }

  /**
   * Check if tracking is allowed
   */
  private canTrack(): boolean {
    if (typeof window === "undefined") return false;
    if (!this.initialized) {
      logger.warn("PostHog not initialized");
      return false;
    }
    if (!this.enabled) return false;
    return true;
  }

  /**
   * Get PostHog instance for advanced usage
   */
  getInstance() {
    return posthog;
  }
}

// Export singleton instance
export const analytics = new PostHogClient();

// Convenience functions
export const trackEvent = (name: string, properties?: EventProperties) =>
  analytics.capture(name, properties);

export const trackPageView = (properties?: EventProperties) =>
  analytics.capturePageview(properties);

export const identifyUser = (userId: string, properties?: UserProperties) =>
  analytics.identify(userId, properties);

export const resetUser = () => analytics.reset();
