/**
 * PostHog Funnel Configurations
 *
 * This file defines the 4 critical conversion funnels for PostHog.
 * Use these configurations to create funnels in the PostHog dashboard.
 */

export interface FunnelStep {
  event: string;
  name: string;
  description: string;
}

export interface FunnelConfig {
  id: string;
  name: string;
  description: string;
  steps: FunnelStep[];
  estimatedConversionRate?: string;
  insights: string[];
}

// ============================================================================
// FUNNEL 1: Visitor → Lead
// ============================================================================

export const visitorToLeadFunnel: FunnelConfig = {
  id: 'visitor_to_lead',
  name: 'Visitor → Lead',
  description: 'Tracks conversion from anonymous website visitors to identified leads',
  steps: [
    {
      event: 'page_view',
      name: 'Page View',
      description: 'User visits any page on the website',
    },
    {
      event: 'lead_form_viewed',
      name: 'Form Viewed',
      description: 'User views contact form, demo form, or newsletter signup',
    },
    {
      event: 'lead_form_submitted',
      name: 'Form Submitted',
      description: 'User submits the form with their information',
    },
    {
      event: 'lead_created',
      name: 'Lead Created',
      description: 'Lead successfully created in database',
    },
  ],
  estimatedConversionRate: '2-5%',
  insights: [
    'Track which pages drive the most leads',
    'Identify form abandonment points',
    'Measure effectiveness of CTAs',
    'Compare conversion rates by traffic source',
  ],
};

// ============================================================================
// FUNNEL 2: Lead → Trial
// ============================================================================

export const leadToTrialFunnel: FunnelConfig = {
  id: 'lead_to_trial',
  name: 'Lead → Trial',
  description: 'Tracks lead conversion to trial user with verified email',
  steps: [
    {
      event: 'signup_started',
      name: 'Signup Started',
      description: 'User clicks signup and begins registration',
    },
    {
      event: 'email_verified',
      name: 'Email Verified',
      description: 'User verifies their email via OTP',
    },
    {
      event: 'trial_started',
      name: 'Trial Started',
      description: 'User completes onboarding and starts trial',
    },
  ],
  estimatedConversionRate: '40-60%',
  insights: [
    'Measure email verification completion rate',
    'Track signup method effectiveness (email vs Google)',
    'Identify onboarding drop-off points',
    'Monitor trial activation time',
  ],
};

// ============================================================================
// FUNNEL 3: Trial → Paid
// ============================================================================

export const trialToPaidFunnel: FunnelConfig = {
  id: 'trial_to_paid',
  name: 'Trial → Paid',
  description: 'Tracks conversion from trial users to paying customers',
  steps: [
    {
      event: 'trial_started',
      name: 'Trial Started',
      description: 'User begins their trial period',
    },
    {
      event: 'checkout_initiated',
      name: 'Checkout Initiated',
      description: 'User clicks upgrade and enters checkout',
    },
    {
      event: 'subscription_created',
      name: 'Subscription Created',
      description: 'Stripe subscription successfully created',
    },
    {
      event: 'first_payment',
      name: 'First Payment',
      description: 'First payment successfully processed',
    },
  ],
  estimatedConversionRate: '15-25%',
  insights: [
    'Monitor trial-to-paid conversion by package tier',
    'Track checkout abandonment rates',
    'Measure impact of trial length on conversion',
    'Identify optimal upgrade timing',
  ],
};

// ============================================================================
// FUNNEL 4: Feature Usage
// ============================================================================

export const featureUsageFunnel: FunnelConfig = {
  id: 'feature_usage',
  name: 'Feature Usage',
  description: 'Tracks user engagement with key platform features',
  steps: [
    {
      event: 'dashboard_viewed',
      name: 'Dashboard Viewed',
      description: 'User accesses their dashboard',
    },
    {
      event: 'feature_clicked',
      name: 'Feature Clicked',
      description: 'User clicks on a specific feature',
    },
    {
      event: 'feature_completed',
      name: 'Feature Completed',
      description: 'User successfully completes a feature action',
    },
    {
      event: 'goal_achieved',
      name: 'Goal Achieved',
      description: 'User achieves a meaningful outcome',
    },
  ],
  estimatedConversionRate: '30-50%',
  insights: [
    'Identify most and least used features',
    'Measure feature adoption rates',
    'Track feature completion time',
    'Discover usage patterns by package tier',
  ],
};

// ============================================================================
// All Funnels
// ============================================================================

export const allFunnels: FunnelConfig[] = [
  visitorToLeadFunnel,
  leadToTrialFunnel,
  trialToPaidFunnel,
  featureUsageFunnel,
];

// ============================================================================
// Custom Events for Tracking
// ============================================================================

export const customEvents = {
  // Visitor → Lead
  page_view: 'Page viewed by visitor',
  lead_form_viewed: 'Lead form displayed to user',
  lead_form_submitted: 'Lead form submitted',
  lead_created: 'Lead successfully created',

  // Lead → Trial
  signup_started: 'User began signup process',
  email_verified: 'Email verification completed',
  trial_started: 'Trial account activated',

  // Trial → Paid
  checkout_initiated: 'User entered checkout flow',
  subscription_created: 'Stripe subscription created',
  first_payment: 'First payment processed',

  // Feature Usage
  dashboard_viewed: 'User accessed dashboard',
  feature_clicked: 'Feature interaction started',
  feature_completed: 'Feature action completed',
  goal_achieved: 'User goal accomplished',

  // Additional Events
  button_clicked: 'Button or CTA clicked',
  form_error: 'Form validation error',
  search_performed: 'Search query executed',
  integration_connected: 'Third-party integration linked',
  workflow_created: 'Workflow automation created',
  workflow_executed: 'Workflow automation ran',
};

// ============================================================================
// Dashboard Configuration
// ============================================================================

export interface DashboardConfig {
  name: string;
  description: string;
  widgets: {
    type: string;
    title: string;
    config: Record<string, unknown>;
  }[];
}

export const conversionDashboard: DashboardConfig = {
  name: 'Mawidi Conversion Analytics',
  description: 'Comprehensive view of all conversion funnels and key metrics',
  widgets: [
    // Funnel Widgets
    {
      type: 'funnel',
      title: 'Visitor → Lead Funnel',
      config: {
        funnelId: 'visitor_to_lead',
        steps: visitorToLeadFunnel.steps.map((s) => s.event),
        timeWindow: '30d',
      },
    },
    {
      type: 'funnel',
      title: 'Lead → Trial Funnel',
      config: {
        funnelId: 'lead_to_trial',
        steps: leadToTrialFunnel.steps.map((s) => s.event),
        timeWindow: '30d',
      },
    },
    {
      type: 'funnel',
      title: 'Trial → Paid Funnel',
      config: {
        funnelId: 'trial_to_paid',
        steps: trialToPaidFunnel.steps.map((s) => s.event),
        timeWindow: '30d',
      },
    },
    {
      type: 'funnel',
      title: 'Feature Usage Funnel',
      config: {
        funnelId: 'feature_usage',
        steps: featureUsageFunnel.steps.map((s) => s.event),
        timeWindow: '7d',
      },
    },

    // Trend Widgets
    {
      type: 'trend',
      title: 'Daily Signups',
      config: {
        events: ['signup_started', 'trial_started'],
        interval: 'day',
        timeWindow: '30d',
      },
    },
    {
      type: 'trend',
      title: 'Subscription Conversions',
      config: {
        events: ['subscription_created', 'first_payment'],
        interval: 'day',
        timeWindow: '30d',
      },
    },

    // Insight Widgets
    {
      type: 'insight',
      title: 'Top Converting Pages',
      config: {
        event: 'lead_created',
        groupBy: 'page',
        timeWindow: '30d',
        limit: 10,
      },
    },
    {
      type: 'insight',
      title: 'Most Used Features',
      config: {
        event: 'feature_completed',
        groupBy: 'feature_name',
        timeWindow: '7d',
        limit: 10,
      },
    },
  ],
};

// ============================================================================
// Helper: Generate PostHog Funnel JSON
// ============================================================================

export function generateFunnelJSON(funnel: FunnelConfig) {
  return {
    name: funnel.name,
    description: funnel.description,
    filters: {
      events: funnel.steps.map((step, index) => ({
        id: step.event,
        name: step.event,
        type: 'events',
        order: index,
      })),
    },
    interval: 'day',
  };
}

// ============================================================================
// Export Instructions for PostHog Setup
// ============================================================================

export const setupInstructions = `
# PostHog Funnel Setup Instructions

## Prerequisites
1. PostHog account (cloud or self-hosted)
2. NEXT_PUBLIC_POSTHOG_KEY and NEXT_PUBLIC_POSTHOG_HOST configured in .env

## Creating Funnels in PostHog

### Method 1: Manual Creation (Recommended for learning)

1. Log into PostHog → Insights → New Insight → Funnel
2. For each funnel below, add the steps in order:

**Funnel 1: Visitor → Lead**
- Step 1: page_view
- Step 2: lead_form_viewed
- Step 3: lead_form_submitted
- Step 4: lead_created

**Funnel 2: Lead → Trial**
- Step 1: signup_started
- Step 2: email_verified
- Step 3: trial_started

**Funnel 3: Trial → Paid**
- Step 1: trial_started
- Step 2: checkout_initiated
- Step 3: subscription_created
- Step 4: first_payment

**Funnel 4: Feature Usage**
- Step 1: dashboard_viewed
- Step 2: feature_clicked
- Step 3: feature_completed
- Step 4: goal_achieved

3. Save each funnel to your dashboard

### Method 2: API Creation (Advanced)

Use the PostHog API to programmatically create funnels:

\`\`\`bash
# Export funnel configurations
node -e "const f = require('./lib/posthog-funnels'); console.log(JSON.stringify(f.generateFunnelJSON(f.visitorToLeadFunnel), null, 2))"

# Create via API
curl -X POST https://app.posthog.com/api/projects/YOUR_PROJECT_ID/insights/ \\
  -H "Authorization: Bearer YOUR_API_KEY" \\
  -H "Content-Type: application/json" \\
  -d @funnel.json
\`\`\`

## Creating Dashboard

1. PostHog → Dashboards → New Dashboard
2. Name: "Mawidi Conversion Analytics"
3. Add the 4 funnels created above
4. Add additional insights:
   - Trends: Daily signups, conversions
   - Tables: Top pages, features
   - Retention: User cohorts

## Testing Events

1. Run app in development: npm run dev
2. Open browser console
3. Perform actions (view forms, signup, etc.)
4. Check PostHog Live Events to verify tracking

## Verification

✓ All 4 funnels created
✓ Events flowing into PostHog
✓ Dashboard shows real data
✓ Conversion rates calculated

## Next Steps

- Set up alerts for low conversion rates
- Create retention cohorts
- Implement A/B testing with feature flags
- Add session recordings for drop-off analysis
`;
