/**
 * PostHog Heatmaps Configuration
 *
 * Specialized configuration for heatmap tracking on top 5 pages:
 * 1. Homepage (/) - Landing page interactions
 * 2. Pricing (/pricing) - Package selection, pricing comparisons
 * 3. Features (/features) - Feature exploration
 * 4. Dashboard (/dashboard) - User engagement patterns
 * 5. Signup (/signup) - Conversion funnel optimization
 *
 * Insights to track:
 * - Click heatmaps: Where users click most frequently
 * - Scroll heatmaps: How far users scroll down pages
 * - Rage clicks: Areas of user frustration
 * - Dead clicks: Non-interactive elements users try to click
 */

import { posthog } from 'posthog-js';

/**
 * Priority pages for heatmap tracking
 */
export const HEATMAP_PAGES = {
  homepage: {
    path: '/',
    name: 'Homepage',
    insights: [
      'CTA button clicks (Book Demo, Get Started)',
      'Hero section engagement',
      'Feature card interactions',
      'Social proof scroll depth',
      'Footer link clicks',
    ],
  },
  pricing: {
    path: '/pricing',
    name: 'Pricing Page',
    insights: [
      'Package tier selection (Tier 1-5)',
      'Monthly vs Annual toggle',
      'Feature comparison scroll',
      'CTA button placement effectiveness',
      'FAQ expansion clicks',
    ],
  },
  features: {
    path: '/features',
    name: 'Features Page',
    insights: [
      'Feature card clicks',
      'Tab navigation usage',
      'Video/demo engagement',
      'Integration section interest',
      'Comparison table interactions',
    ],
  },
  dashboard: {
    path: '/dashboard',
    name: 'User Dashboard',
    insights: [
      'Navigation menu clicks',
      'Widget interactions',
      'Feature discovery patterns',
      'Settings access frequency',
      'Help/support clicks',
    ],
  },
  signup: {
    path: '/signup',
    name: 'Signup Page',
    insights: [
      'Form field interaction order',
      'Google OAuth vs Email signup',
      'Error message appearance',
      'Terms acceptance scroll',
      'Form abandonment points',
    ],
  },
} as const;

export type HeatmapPage = keyof typeof HEATMAP_PAGES;

/**
 * Check if current page should track heatmaps
 */
export function isHeatmapPage(pathname: string): boolean {
  // Remove language prefix (en, ar) and trailing slash
  const cleanPath = pathname
    .replace(/^\/(en|ar)/, '')
    .replace(/\/$/, '') || '/';

  return Object.values(HEATMAP_PAGES).some(
    (page) => cleanPath === page.path || cleanPath.startsWith(page.path)
  );
}

/**
 * Get heatmap page config for current path
 */
export function getHeatmapPageConfig(pathname: string) {
  const cleanPath = pathname
    .replace(/^\/(en|ar)/, '')
    .replace(/\/$/, '') || '/';

  for (const [key, config] of Object.entries(HEATMAP_PAGES)) {
    if (cleanPath === config.path || cleanPath.startsWith(config.path)) {
      return { key: key as HeatmapPage, ...config };
    }
  }

  return null;
}

/**
 * Track custom heatmap event
 */
export function trackHeatmapEvent(
  eventName: string,
  pageKey: HeatmapPage,
  properties?: Record<string, unknown>
) {
  if (typeof window === 'undefined') return;

  posthog.capture(`heatmap_${eventName}`, {
    page: HEATMAP_PAGES[pageKey].name,
    page_path: HEATMAP_PAGES[pageKey].path,
    ...properties,
  });
}

/**
 * Track rage click (multiple rapid clicks on same element)
 */
export function trackRageClick(element: string, pageKey: HeatmapPage) {
  trackHeatmapEvent('rage_click', pageKey, {
    element,
    timestamp: new Date().toISOString(),
  });
}

/**
 * Track dead click (click on non-interactive element)
 */
export function trackDeadClick(element: string, pageKey: HeatmapPage) {
  trackHeatmapEvent('dead_click', pageKey, {
    element,
    timestamp: new Date().toISOString(),
  });
}

/**
 * Track scroll depth milestones
 */
export function trackScrollDepth(
  depth: number,
  pageKey: HeatmapPage,
  maxScroll: number
) {
  trackHeatmapEvent('scroll_depth', pageKey, {
    depth_percentage: depth,
    max_scroll: maxScroll,
    timestamp: new Date().toISOString(),
  });
}

/**
 * Track time spent on page
 */
export function trackTimeOnPage(seconds: number, pageKey: HeatmapPage) {
  trackHeatmapEvent('time_on_page', pageKey, {
    seconds,
    minutes: (seconds / 60).toFixed(2),
    timestamp: new Date().toISOString(),
  });
}

/**
 * Heatmap Insights Summary
 *
 * Expected insights after data collection:
 *
 * 1. HOMEPAGE:
 *    - Which CTA performs better (primary vs secondary)
 *    - Optimal hero section design
 *    - Most engaging features
 *    - Scroll depth patterns
 *
 * 2. PRICING:
 *    - Most popular tier selection
 *    - Monthly vs Annual preference
 *    - Feature comparison usage
 *    - Price point concerns (FAQ clicks)
 *
 * 3. FEATURES:
 *    - Most interesting features
 *    - Tab vs scroll preference
 *    - Integration interest
 *    - Content engagement depth
 *
 * 4. DASHBOARD:
 *    - Most used features
 *    - Navigation patterns
 *    - Feature discovery flow
 *    - Help/support triggers
 *
 * 5. SIGNUP:
 *    - Form completion rate by field
 *    - OAuth vs email preference
 *    - Error points
 *    - Abandonment triggers
 */
