export async function login(email: string, password: string): Promise<{ token: string }> {
  const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
  const res = await fetch('/api/v1/tenant/login', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'X-CSRF-TOKEN': csrfToken || '',
    },
    body: JSON.stringify({ email, password }),
  });
  if (!res.ok) throw new Error('Login failed');
  return res.json();
}

export async function getEvents(): Promise<any[]> {
  const token = localStorage.getItem('ta_token') || '';
  const res = await fetch('/api/v1/tenant/events', {
    headers: { Authorization: `Bearer ${token}` },
  });
  if (!res.ok) throw new Error('Failed to load events');
  const json = await res.json();
  return json.data ?? [];
}

export async function createEvent(payload: { name: string; slug: string; date?: string; is_active?: boolean }): Promise<number> {
  const token = localStorage.getItem('ta_token') || '';
  const res = await fetch('/api/v1/tenant/events', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
    body: JSON.stringify(payload),
  });
  if (!res.ok) throw new Error('Failed to create event');
  const json = await res.json();
  return json.id;
}

export async function updateEvent(id: number, payload: Partial<{ name: string; slug: string; date?: string; is_active?: boolean }>): Promise<void> {
  const token = localStorage.getItem('ta_token') || '';
  const res = await fetch(`/api/v1/tenant/events/${id}`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
    body: JSON.stringify(payload),
  });
  if (!res.ok) throw new Error('Failed to update event');
}

export async function getEventPhotos(id: number): Promise<any[]> {
  const token = localStorage.getItem('ta_token') || '';
  const res = await fetch(`/api/v1/tenant/events/${id}/photos`, { headers: { Authorization: `Bearer ${token}` } });
  if (!res.ok) throw new Error('Failed to load photos');
  const json = await res.json();
  return json.data ?? [];
}

export async function featurePhoto(id: number) {
  const token = localStorage.getItem('ta_token') || '';
  await fetch(`/api/v1/tenant/photos/${id}/feature`, { method: 'POST', headers: { Authorization: `Bearer ${token}` } });
}

export async function unfeaturePhoto(id: number) {
  const token = localStorage.getItem('ta_token') || '';
  await fetch(`/api/v1/tenant/photos/${id}/unfeature`, { method: 'POST', headers: { Authorization: `Bearer ${token}` } });
}

export async function getEvent(id: number): Promise<any> {
  const token = localStorage.getItem('ta_token') || '';
  const res = await fetch(`/api/v1/tenant/events/${id}`, { headers: { Authorization: `Bearer ${token}` } });
  if (!res.ok) throw new Error('Failed to load event');
  return res.json();
}

export async function toggleEvent(id: number): Promise<boolean> {
  const token = localStorage.getItem('ta_token') || '';
  const res = await fetch(`/api/v1/tenant/events/${id}/toggle`, { method: 'POST', headers: { Authorization: `Bearer ${token}` } });
  if (!res.ok) throw new Error('Failed to toggle');
  const json = await res.json();
  return !!json.is_active;
}

export async function getEventStats(id: number): Promise<{ total: number; featured: number; likes: number }> {
  const token = localStorage.getItem('ta_token') || '';
  const res = await fetch(`/api/v1/tenant/events/${id}/stats`, { headers: { Authorization: `Bearer ${token}` } });
  if (!res.ok) throw new Error('Failed to load stats');
  return res.json();
}

export async function createInviteLink(id: number): Promise<string> {
  const token = localStorage.getItem('ta_token') || '';
  const res = await fetch(`/api/v1/tenant/events/${id}/invites`, { method: 'POST', headers: { Authorization: `Bearer ${token}` } });
  if (!res.ok) throw new Error('Failed to create invite');
  const json = await res.json();
  return json.link as string;
}

export async function deletePhoto(id: number) {
  const token = localStorage.getItem('ta_token') || '';
  await fetch(`/api/v1/tenant/photos/${id}`, { method: 'DELETE', headers: { Authorization: `Bearer ${token}` } });
}
