/**
 * Action Tracker
 *
 * Centralized tracking functions that:
 * 1. Record actions to the error context ring buffer
 * 2. Send events to PostHog for analytics
 *
 * Use these functions instead of direct PostHog calls
 * to ensure actions are captured for error debugging
 */

import { posthog } from "posthog-js";
import { recordAction } from "./error-context";

// ============================================================================
// Types
// ============================================================================

export interface TrackingData {
  [key: string]: unknown;
}

// ============================================================================
// Click Tracking
// ============================================================================

/**
 * Tracks a button or element click
 * @param name - Identifier for the click (e.g., "signup_cta", "pricing_toggle")
 * @param location - Where on the page (e.g., "header", "hero", "footer")
 * @param data - Additional context
 */
export function trackClick(
  name: string,
  location?: string,
  data?: TrackingData,
): void {
  if (typeof window === "undefined") return;

  // Record to error context
  recordAction(`click:${name}`, {
    component: name,
    location,
    data,
  });

  // Send to PostHog
  posthog.capture("user_action", {
    action_type: "click",
    action_name: name,
    action_location: location,
    page: window.location.pathname,
    page_url: window.location.href,
    ...data,
  });
}

// ============================================================================
// Form Tracking
// ============================================================================

/**
 * Tracks a form submission
 * @param formName - Identifier for the form (e.g., "checkout_form", "contact_form")
 * @param location - Where on the page
 * @param data - Form context (not actual form data for privacy)
 */
export function trackFormSubmit(
  formName: string,
  location?: string,
  data?: TrackingData,
): void {
  if (typeof window === "undefined") return;

  // Record to error context
  recordAction(`submit:${formName}`, {
    component: formName,
    location,
    data,
  });

  // Send to PostHog
  posthog.capture("user_action", {
    action_type: "form_submit",
    action_name: formName,
    action_location: location,
    page: window.location.pathname,
    page_url: window.location.href,
    ...data,
  });
}

/**
 * Tracks form field focus (useful for understanding where users abandon forms)
 * @param formName - Form identifier
 * @param fieldName - Field that was focused
 */
export function trackFormFocus(formName: string, fieldName: string): void {
  if (typeof window === "undefined") return;

  // Record to error context
  recordAction(`focus:${formName}/${fieldName}`, {
    component: formName,
    data: { field: fieldName },
  });

  // Don't send to PostHog to avoid noise - this is mainly for error context
}

// ============================================================================
// Navigation Tracking
// ============================================================================

/**
 * Tracks navigation events (beyond automatic page views)
 * @param destination - Where the user is going
 * @param source - Where they came from
 * @param data - Additional context
 */
export function trackNavigation(
  destination: string,
  source?: string,
  data?: TrackingData,
): void {
  if (typeof window === "undefined") return;

  // Record to error context
  recordAction(`navigate:${destination}`, {
    location: source,
    data,
  });

  // Send to PostHog
  posthog.capture("user_action", {
    action_type: "navigation",
    action_name: destination,
    action_location: source,
    from_page: source || window.location.pathname,
    ...data,
  });
}

// ============================================================================
// Modal/Dialog Tracking
// ============================================================================

/**
 * Tracks modal open events
 * @param modalName - Modal identifier
 * @param trigger - What triggered the modal
 */
export function trackModalOpen(modalName: string, trigger?: string): void {
  if (typeof window === "undefined") return;

  // Record to error context
  recordAction(`modal_open:${modalName}`, {
    component: modalName,
    data: { trigger },
  });

  // Send to PostHog
  posthog.capture("user_action", {
    action_type: "modal_open",
    action_name: modalName,
    trigger,
    page: window.location.pathname,
  });
}

/**
 * Tracks modal close events
 * @param modalName - Modal identifier
 * @param reason - Why it was closed (e.g., "submit", "cancel", "escape")
 */
export function trackModalClose(modalName: string, reason?: string): void {
  if (typeof window === "undefined") return;

  // Record to error context
  recordAction(`modal_close:${modalName}`, {
    component: modalName,
    data: { reason },
  });

  // Send to PostHog
  posthog.capture("user_action", {
    action_type: "modal_close",
    action_name: modalName,
    close_reason: reason,
    page: window.location.pathname,
  });
}

// ============================================================================
// Tab/Section Tracking
// ============================================================================

/**
 * Tracks tab or section changes
 * @param tabName - Tab identifier
 * @param location - Component location
 */
export function trackTabChange(tabName: string, location?: string): void {
  if (typeof window === "undefined") return;

  // Record to error context
  recordAction(`tab:${tabName}`, {
    component: tabName,
    location,
  });

  // Send to PostHog
  posthog.capture("user_action", {
    action_type: "tab_change",
    action_name: tabName,
    action_location: location,
    page: window.location.pathname,
  });
}

// ============================================================================
// Error Tracking
// ============================================================================

/**
 * Tracks user-facing errors (API errors, validation errors, etc.)
 * @param errorType - Type of error
 * @param message - Error message (sanitized, no PII)
 * @param context - Where the error occurred
 */
export function trackError(
  errorType: string,
  message: string,
  context?: string,
): void {
  if (typeof window === "undefined") return;

  // Record to error context
  recordAction(`error:${errorType}`, {
    location: context,
    data: { message },
  });

  // Send to PostHog
  posthog.capture("user_action", {
    action_type: "error",
    action_name: errorType,
    error_message: message,
    error_context: context,
    page: window.location.pathname,
  });
}

// ============================================================================
// Generic Action Tracking
// ============================================================================

/**
 * Tracks any custom action
 * @param actionType - Type of action (e.g., "toggle", "expand", "copy")
 * @param actionName - Specific action identifier
 * @param location - Where on the page
 * @param data - Additional context
 */
export function trackAction(
  actionType: string,
  actionName: string,
  location?: string,
  data?: TrackingData,
): void {
  if (typeof window === "undefined") return;

  // Record to error context
  recordAction(`${actionType}:${actionName}`, {
    component: actionName,
    location,
    data,
  });

  // Send to PostHog
  posthog.capture("user_action", {
    action_type: actionType,
    action_name: actionName,
    action_location: location,
    page: window.location.pathname,
    ...data,
  });
}
