import posthog from "posthog-js";

let initialized = false;

export function initAnalytics() {
  if (
    typeof window !== "undefined" &&
    process.env.NEXT_PUBLIC_POSTHOG_KEY &&
    !initialized
  ) {
    posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY, {
      api_host:
        process.env.NEXT_PUBLIC_POSTHOG_HOST ||
        "https://analytics.88oakapps.com",
      capture_pageview: true,
      capture_pageleave: true,
      person_profiles: "never",
    });
    initialized = true;
  }
}

export function trackEvent(
  event: string,
  properties?: Record<string, unknown>
) {
  if (initialized) {
    posthog.capture(event, properties);
  }
}

export function trackScreen(screenName: string) {
  if (initialized) {
    posthog.capture("$pageview", { $current_url: screenName });
  }
}

export function resetAnalytics() {
  if (initialized) {
    posthog.reset();
  }
}

// ---------------------------------------------------------------------------
// Event names — match iOS/KMM AnalyticsEvents for cross-platform consistency
// ---------------------------------------------------------------------------

export const AnalyticsEvents = {
  // Auth
  USER_REGISTERED: "user_registered",
  USER_SIGNED_IN: "user_signed_in",

  // Residences
  RESIDENCE_CREATED: "residence_created",
  RESIDENCE_LIMIT_REACHED: "residence_limit_reached",
  RESIDENCE_SHARED: "residence_shared",

  // Tasks
  TASK_CREATED: "task_created",

  // Contractors
  CONTRACTOR_CREATED: "contractor_created",
  CONTRACTOR_PAYWALL_SHOWN: "contractor_paywall_shown",

  // Documents
  DOCUMENT_CREATED: "document_created",
  DOCUMENTS_PAYWALL_SHOWN: "documents_paywall_shown",

  // Sharing
  SHARE_RESIDENCE_PAYWALL_SHOWN: "share_residence_paywall_shown",

  // Settings
  THEME_CHANGED: "theme_changed",

  // Errors
  ERROR_OCCURRED: "error_occurred",
} as const;
