// API Client - Connects Frontend (React/Zustand) to PHP Backend
// For app: Change this to your server URL
// For website: Uses /api (relative path)

// DETECT if running as native app or in browser
const isNativeApp = typeof (window as any).Capacitor !== 'undefined' && (window as any).Capacitor?.isNativePlatform?.();

// ===== YOUR SERVER URL =====
const SERVER_URL = 'https://sandboxapp.helpforsociety.in/api';
// ============================

// Use full URL for both website and native app
const BASE_URL = SERVER_URL;

// For development/testing - fallback to demo mode if server not available
const USE_DEMO_MODE = false; // Set to true to test without server

// Get auth token from localStorage
function getToken(): string | null {
  return localStorage.getItem('skatepro_token');
}

// Generic fetch wrapper
async function fetchApi(endpoint: string, options: RequestInit = {}) {
  const url = `${BASE_URL}/${endpoint}`;
  const headers: Record<string, string> = {
    'Content-Type': 'application/json',
    ...((options.headers as Record<string, string>) || {}),
  };

  const token = getToken();
  if (token) {
    headers['Authorization'] = `Bearer ${token}`;
  }

  try {
    const response = await fetch(url, {
      ...options,
      headers,
    });

    if (!response.ok) {
      const error = await response.json().catch(() => ({ error: `HTTP ${response.status}` }));
      throw new Error(error.error || `HTTP ${response.status}`);
    }

    return response.json();
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : 'Network error';
    throw new Error(message);
  }
}

// ============ AUTH API ============
export const authApi = {
  login: (username: string, password: string) =>
    fetchApi('auth.php', {
      method: 'POST',
      body: JSON.stringify({ username, password }),
    }),
};

// ============ STUDENTS API ============
export const studentsApi = {
  getAll: (filters?: { search?: string; batch?: string; status?: string }) => {
    const params = new URLSearchParams();
    if (filters?.search) params.append('search', filters.search);
    if (filters?.batch) params.append('batch', filters.batch);
    if (filters?.status) params.append('status', filters.status);
    const q = params.toString();
    return fetchApi(`students.php${q ? '?' + q : ''}`);
  },

  getById: (id: number) =>
    fetchApi(`students.php?id=${id}`),

  create: (data: Record<string, unknown>) =>
    fetchApi('students.php', {
      method: 'POST',
      body: JSON.stringify(data),
    }),

  update: (id: number, data: Record<string, unknown>) =>
    fetchApi(`students.php?id=${id}`, {
      method: 'PUT',
      body: JSON.stringify({ ...data, id }),
    }),

  delete: (id: number) =>
    fetchApi(`students.php?id=${id}`, {
      method: 'DELETE',
    }),
};

// ============ TIMING API ============
export const timingApi = {
  getAll: (studentId?: string, distance?: string) => {
    const params = new URLSearchParams();
    if (studentId) params.append('studentId', studentId);
    if (distance && distance !== 'All') params.append('distance', distance);
    const q = params.toString();
    return fetchApi(`timing.php${q ? '?' + q : ''}`);
  },

  create: (data: Record<string, unknown>) =>
    fetchApi('timing.php', {
      method: 'POST',
      body: JSON.stringify(data),
    }),
};

// ============ ATTENDANCE API ============
export const attendanceApi = {
  getByDate: (date: string) =>
    fetchApi(`attendance.php?date=${date}`),

  getByStudent: (studentId: number) =>
    fetchApi(`attendance.php?studentId=${studentId}`),

  mark: (data: Record<string, unknown>) =>
    fetchApi('attendance.php', {
      method: 'POST',
      body: JSON.stringify(data),
    }),
};

// ============ FEES API ============
export const feesApi = {
  getReceipts: () =>
    fetchApi('fees.php?receipts=1'),

  getDue: () =>
    fetchApi('fees.php?due=1'),

  recordPayment: (data: Record<string, unknown>) =>
    fetchApi('fees.php', {
      method: 'POST',
      body: JSON.stringify(data),
    }),
};

// ============ SPRINT RACES API ============
export const sprintRacesApi = {
  getAll: () =>
    fetchApi('sprint_races.php'),

  getByStudent: (studentId: number) =>
    fetchApi(`sprint_races.php?studentId=${studentId}`),

  create: (data: Record<string, unknown>) =>
    fetchApi('sprint_races.php', {
      method: 'POST',
      body: JSON.stringify({ ...data, action: 'create' }),
    }),

  saveRound: (data: Record<string, unknown>) =>
    fetchApi('sprint_races.php', {
      method: 'POST',
      body: JSON.stringify({ ...data, action: 'saveRound' }),
    }),

  delete: (id: number) =>
    fetchApi(`sprint_races.php?id=${id}`, {
      method: 'DELETE',
    }),
};

// ============ COACHES API ============
export const coachesApi = {
  getAll: () => fetchApi('coaches.php'),

  create: (data: Record<string, unknown>) =>
    fetchApi('coaches.php', {
      method: 'POST',
      body: JSON.stringify(data),
    }),

  delete: (id: number) =>
    fetchApi(`coaches.php?id=${id}`, {
      method: 'DELETE',
    }),
};

// ============ EQUIPMENT API ============
export const equipmentApi = {
  getAll: () =>
    fetchApi('equipment.php'),

  add: (data: Record<string, unknown>) =>
    fetchApi('equipment.php', {
      method: 'POST',
      body: JSON.stringify(data),
    }),

  buy: (data: Record<string, unknown>) =>
    fetchApi('equipment.php', {
      method: 'POST',
      body: JSON.stringify({ ...data, action: 'buy' }),
    }),

  sell: (data: Record<string, unknown>) =>
    fetchApi('equipment.php', {
      method: 'POST',
      body: JSON.stringify({ ...data, action: 'sell' }),
    }),
};

// Export config for other parts of app
export { BASE_URL, SERVER_URL, isNativeApp };
