/**
 * Experiment Types
 *
 * Type definitions for the A/B testing and experiment tracking system.
 */

// ============================================================================
// Experiment Types
// ============================================================================

export type ExperimentType = 'homepage' | 'pricing' | 'demo_flow' | 'package' | 'feature' | 'email';
export type ExperimentStatus = 'draft' | 'running' | 'paused' | 'completed';

export interface ExperimentVariant {
  id: string;
  name: string;
  description?: string;
  trafficPercent: number;
  conversions: number;
  visitors: number;
  conversionRate: number;
  revenue?: number;
}

export interface SignificanceResult {
  confident: boolean;       // > 95% confidence
  confidenceLevel: number;  // 0-100
  sampleSize: number;
  requiredSample: number;
  zScore?: number;
  pValue?: number;
}

export interface Experiment {
  id: string;
  name: string;
  description: string;
  type: ExperimentType;
  status: ExperimentStatus;
  variants: ExperimentVariant[];
  winner: string | null;      // Variant ID of winner
  startedAt: string | null;
  endedAt: string | null;
  createdAt: string;
  updatedAt: string;
  createdBy: string;
  significance: SignificanceResult;
  targetMetric: string;       // e.g., 'signup', 'demo_booking', 'purchase'
  minimumSampleSize: number;
}

export interface ExperimentFilters {
  status?: ExperimentStatus | 'all';
  type?: ExperimentType | 'all';
  search?: string;
  page?: number;
  limit?: number;
}

export interface ExperimentMetrics {
  totalExperiments: number;
  activeExperiments: number;
  completedExperiments: number;
  averageLift: number;        // Average improvement from winning variants
  totalConversions: number;
  experimentsWithWinner: number;
}

// ============================================================================
// Create/Update Requests
// ============================================================================

export interface CreateExperimentRequest {
  name: string;
  description: string;
  type: ExperimentType;
  variants: Array<{
    name: string;
    description?: string;
    trafficPercent: number;
  }>;
  targetMetric: string;
  minimumSampleSize?: number;
}

export interface UpdateExperimentRequest {
  id: string;
  status?: ExperimentStatus;
  winner?: string;
  variants?: Array<{
    id: string;
    trafficPercent: number;
  }>;
}

// ============================================================================
// Experiment Event Tracking
// ============================================================================

export interface ExperimentEvent {
  experimentId: string;
  variantId: string;
  userId?: string;
  sessionId: string;
  eventType: 'view' | 'conversion';
  metadata?: Record<string, unknown>;
  createdAt: string;
}

export interface VariantAssignment {
  experimentId: string;
  variantId: string;
  userId?: string;
  sessionId: string;
  assignedAt: string;
}

// ============================================================================
// Attribution Types
// ============================================================================

export type AttributionSource = 'organic' | 'paid' | 'referral' | 'direct' | 'blog' | 'email' | 'social';
export type AttributionModel = 'first_touch' | 'last_touch' | 'linear';

export interface SourceAttribution {
  source: AttributionSource;
  visitors: number;
  demos: number;
  conversions: number;
  revenue: number;
  conversionRate: number;
  costPerAcquisition?: number;
}

export interface BlogAttribution {
  postSlug: string;
  postTitle: string;
  views: number;
  demos: number;
  conversions: number;
  revenue: number;
  conversionRate: number;
}

export interface Attribution {
  period: {
    start: string;
    end: string;
  };
  model: AttributionModel;
  sources: SourceAttribution[];
  blogAttribution: BlogAttribution[];
  topConvertingContent: Array<{
    url: string;
    title: string;
    conversionRate: number;
    revenue: number;
    conversions: number;
  }>;
  totals: {
    visitors: number;
    demos: number;
    conversions: number;
    revenue: number;
    overallConversionRate: number;
  };
}

export interface AttributionFilters {
  startDate?: string;
  endDate?: string;
  model?: AttributionModel;
  sources?: AttributionSource[];
}

// ============================================================================
// Leaderboard Types
// ============================================================================

export type LeaderboardPeriod = 'week' | 'month' | 'quarter' | 'year';
export type TrendDirection = 'up' | 'down' | 'same';

export interface RepMetrics {
  demosHandled: number;
  demosConfirmed: number;
  demoToCloseRate: number;   // Percentage
  avgResponseTimeMinutes: number;
  expansionWins: number;
  revenue: number;
  ticketsResolved: number;
  avgTicketResolutionHours: number;
  customerSatisfaction?: number;
}

export interface LeaderboardEntry {
  id: string;
  name: string;
  email: string;
  avatar?: string;
  role: string;
  metrics: RepMetrics;
  rank: number;
  previousRank: number;
  trend: TrendDirection;
  rankChange: number;        // Positive = improved
}

export interface Leaderboard {
  period: LeaderboardPeriod;
  periodStart: string;
  periodEnd: string;
  previousPeriodStart: string;
  previousPeriodEnd: string;
  entries: LeaderboardEntry[];
  totals: {
    totalDemos: number;
    totalConversions: number;
    totalRevenue: number;
    avgResponseTime: number;
    avgTicketResolution: number;
  };
}

export interface LeaderboardFilters {
  period?: LeaderboardPeriod;
  sortBy?: keyof RepMetrics;
  sortOrder?: 'asc' | 'desc';
  limit?: number;
}
