// frontend/src/services/api.js const getBackendHost = () => { const host = window.location.hostname || 'localhost'; return window.location.protocol === 'https:' ? host : `${host}:8000`; }; export const API_BASE = `${window.location.protocol}//${getBackendHost()}/api`; export const WS_URL = `${window.location.protocol === 'https:' ? 'wss:' : 'ws:'}//${getBackendHost()}/api/ws`; export const getToken = () => localStorage.getItem('volleyToken'); const api = { request: async (method, url, data = null, isFormData = false) => { const headers = {}; const token = getToken(); if (token) headers['Authorization'] = `Bearer ${token}`; if (!isFormData) headers['Content-Type'] = 'application/json'; const opts = { method, headers }; if (data) opts.body = isFormData ? data : JSON.stringify(data); // Ensure clean URL concatenation const baseUrl = API_BASE.replace(/\/$/, ''); const endpoint = url.startsWith('/') ? url : `/${url}`; const res = await fetch(`${baseUrl}${endpoint}`, opts); if (!res.ok) { if (res.status === 401) { localStorage.removeItem('volleyToken'); if (window.location.pathname !== '/login') { window.location.href = '/login'; } } const errorData = await res.json().catch(() => ({ detail: 'An error occurred' })); throw errorData; } return res.json(); }, get: (url) => api.request('GET', url), post: (url, data) => api.request('POST', url, data), postForm: (url, data) => api.request('POST', url, data, true), put: (url, data) => api.request('PUT', url, data), patch: (url, data) => api.request('PATCH', url, data), delete: (url) => api.request('DELETE', url) }; export default api;