async function apiFetch(url: string, options?: RequestInit) {
  const res = await fetch(url, { credentials: 'include', ...options });
  const json = await res.json().catch(() => ({}));
  if (!res.ok) throw new Error(json.error || `Request failed: ${res.status}`);
  return json;
}

export type DashboardPeriod = 'today' | '7days' | 'month' | 'lifetime';

export interface DashboardStats {
  orders: Record<string, string>;
  bookings: Record<string, string>;
  customers: Record<string, string>;
  conversations: Record<string, string>;
  revenue: Record<string, string>;
}

export interface HourlyPoint {
  hour: string;
  orders: number;
  reservations: number;
}

export interface ChannelPoint {
  day: string;
  voice: number;
  chat: number;
}

export interface DashboardResponse {
  stats: DashboardStats;
  hourly: HourlyPoint[];
  channels: ChannelPoint[];
}

export async function getAnalyticsDashboard(params: Record<string, string> = {}): Promise<DashboardResponse> {
  const qs = new URLSearchParams(params).toString();
  return apiFetch(`/api/analytics/dashboard${qs ? '?' + qs : ''}`);
}

export async function getAnalyticsOrders(params: Record<string, string> = {}) {
  const qs = new URLSearchParams(params).toString();
  return apiFetch(`/api/analytics/orders${qs ? '?' + qs : ''}`);
}

export async function getAnalyticsRevenue(params: Record<string, string> = {}) {
  const qs = new URLSearchParams(params).toString();
  return apiFetch(`/api/analytics/revenue${qs ? '?' + qs : ''}`);
}
