/**
 * Error Breadcrumb Tracking
 * Captures user actions before errors occur for better debugging
 */

export interface Breadcrumb {
  timestamp: string;
  category: 'navigation' | 'user_action' | 'api_call' | 'state_change';
  message: string;
  level: 'info' | 'warning' | 'error';
  data?: Record<string, any>;
}

class BreadcrumbManager {
  private breadcrumbs: Breadcrumb[] = [];
  private readonly MAX_BREADCRUMBS = 10;

  add(breadcrumb: Omit<Breadcrumb, 'timestamp'>): void {
    const newBreadcrumb: Breadcrumb = {
      ...breadcrumb,
      timestamp: new Date().toISOString(),
    };

    this.breadcrumbs.push(newBreadcrumb);
    
    // Keep only last 10 breadcrumbs
    if (this.breadcrumbs.length > this.MAX_BREADCRUMBS) {
      this.breadcrumbs.shift();
    }
  }

  getAll(): Breadcrumb[] {
    return [...this.breadcrumbs];
  }

  clear(): void {
    this.breadcrumbs = [];
  }
}

export const breadcrumbManager = new BreadcrumbManager();

// Helper functions for common breadcrumb types
export const breadcrumb = {
  navigation: (to: string, from?: string) => {
    breadcrumbManager.add({
      category: 'navigation',
      message: `Navigated to ${to}`,
      level: 'info',
      data: { to, from },
    });
  },

  userAction: (action: string, component: string, data?: Record<string, any>) => {
    breadcrumbManager.add({
      category: 'user_action',
      message: `User ${action} in ${component}`,
      level: 'info',
      data,
    });
  },

  apiCall: (endpoint: string, method: string, status?: number) => {
    breadcrumbManager.add({
      category: 'api_call',
      message: `API ${method} ${endpoint}`,
      level: status && status >= 400 ? 'error' : 'info',
      data: { endpoint, method, status },
    });
  },

  stateChange: (description: string, data?: Record<string, any>) => {
    breadcrumbManager.add({
      category: 'state_change',
      message: description,
      level: 'info',
      data,
    });
  },
};
