import api from './api';

export type Match = { id: number; home?: string; away?: string; date?: string; score?: string };
export type Standing = { team: string; played: number; won: number; draw: number; lost: number; points: number };
export type Player = {
  id: number;
  first_name: string;
  last_name: string;
  position?: string;
  jersey_number?: number;
  image_url?: string;
  is_active?: boolean;
  // Extended detail fields (optional on public endpoint)
  nationality?: string;
  date_of_birth?: string;
  height?: number;
  weight?: number;
  email?: string;
  phone?: string;
  team_id?: number;
};
export type Sponsor = { id: number; name: string; logo_url?: string; website_url?: string; tier?: string; display_order?: number };
export type Category = { id?: number; name: string; slug?: string; url?: string; children?: Category[] };

export async function getMatches() {
  const res = await api.get<Match[] | { data: Match[] }>('/matches');
  return Array.isArray(res.data) ? res.data : res.data.data;
}

export async function getStandings() {
  const res = await api.get<Standing[] | { data: Standing[] }>('/standings');
  return Array.isArray(res.data) ? res.data : res.data.data;
}

export async function getPlayers() {
  const res = await api.get<Player[] | { data?: Player[]; items?: Player[] }>('/players');
  if (Array.isArray(res.data)) return res.data as Player[];
  const d = res.data as any;
  return (d?.data || d?.items || []) as Player[];
}

export async function getPlayer(id: number | string) {
  const res = await api.get<Player>(`/players/${id}`);
  return res.data;
}

export async function getSponsors() {
  const res = await api.get<Sponsor[] | { data: Sponsor[] }>('/sponsors');
  return Array.isArray(res.data) ? res.data : res.data.data;
}

export async function sendContact(payload: { name: string; email: string; subject: string; message: string; source?: string }) {
  const res = await api.post('/contact', payload);
  return res.data;
}

export async function subscribeToNewsletter(email: string, preferences?: Record<string, boolean> ) {
  const payload: any = { email };
  try {
    // Provide backend with the correct site origin for preference/unsubscribe links
    const origin = window?.location?.origin;
    if (origin) (payload as any).site_base_url = origin;
  } catch {}
  if (preferences) payload.preferences = preferences;
  const res = await api.post('/newsletter/subscribe', payload);
  return res.data;
}

export async function getCategories() {
  const res = await api.get<Category[] | { data: Category[] }>('/categories');
  return Array.isArray(res.data) ? res.data : res.data.data;
}
