import api from './api';

export interface AnalyticsData {
  users: {
    total: number;
    new_this_week: number;
  };
  events: {
    total: number;
    upcoming: number;
  };
  articles: {
    total: number;
    published: number;
  };
}

export interface AnalyticsOverview {
  total_page_views: number;
  unique_visitors: number;
  total_articles: number;
  published_articles: number;
  page_views_today: number;
  page_views_week: number;
  unique_visitors_week: number;
}

export interface PageStats {
  page_path: string;
  page_name: string;
  view_count: number;
  unique_visitors: number;
}

export interface TopInteraction {
  page: string;
  element: string;
  count: number;
}

export const getAnalytics = async (): Promise<AnalyticsData> => {
  const response = await api.get('/admin/analytics');
  return response.data;
};

export const getAnalyticsOverview = async (): Promise<AnalyticsOverview> => {
  const response = await api.get('/admin/analytics/overview');
  return response.data;
};

export const getTopPages = async (limit: number = 10): Promise<PageStats[]> => {
  const response = await api.get('/admin/analytics/top-pages', {
    params: { limit }
  });
  return response.data;
};

export const getTopArticles = async (limit: number = 10): Promise<any[]> => {
  const response = await api.get('/admin/analytics/top-articles', {
    params: { limit }
  });
  return response.data;
};

export const getTopInteractions = async (days: number = 30, limit: number = 10): Promise<{ items: TopInteraction[] }> => {
  const response = await api.get('/admin/analytics/top-interactions', {
    params: { days, limit }
  });
  return response.data;
};

// Track event - public endpoint
export const trackEvent = async (eventData: {
  event_type: string;
  page?: string;
  page_path?: string;
  page_name?: string;
  element?: string;
  data?: Record<string, any>;
}): Promise<{ ok: boolean }> => {
  const response = await api.post('/analytics/track', eventData);
  return response.data;
};
