function buildUrl(baseUrl, path, query) {
    const trimmedBaseUrl = (baseUrl ?? '').replace(/\/+$/, '');
    const trimmedPath = `/${String(path ?? '').replace(/^\/+/, '')}`;
    const url = new URL(`${trimmedBaseUrl}${trimmedPath}`, window.location.origin);

    if (query) {
        Object.entries(query).forEach(([key, value]) => {
            if (value === undefined || value === null || value === '') return;
            url.searchParams.set(key, String(value));
        });
    }

    return url;
}

export function getApiBaseUrl() {
    return (import.meta.env.VITE_API_BASE_URL ?? '').trim();
}

export function getAuthToken() {
    return localStorage.getItem('super_token') || localStorage.getItem('token') || '';
}

export async function requestJson(path, { method = 'GET', query, body, headers } = {}) {
    const url = buildUrl(getApiBaseUrl(), path, query);
    const token = getAuthToken();
    const authHeaderValue = token ? (token.startsWith('Bearer ') ? token : `Bearer ${token}`) : '';

    const response = await fetch(url.toString(), {
        method,
        headers: {
            ...(body ? { 'Content-Type': 'application/json' } : {}),
            ...(authHeaderValue ? { Authorization: authHeaderValue } : {}),
            ...(headers ?? {})
        },
        body: body ? JSON.stringify(body) : undefined
    });

    const contentType = response.headers.get('content-type') ?? '';
    const isJson = contentType.toLowerCase().includes('application/json');
    const payload = isJson ? await response.json().catch(() => null) : await response.text().catch(() => '');

    if (!response.ok) {
        const message = typeof payload === 'string' ? payload : payload?.message || payload?.error || response.statusText;
        const error = new Error(message || `Request failed: ${response.status}`);
        error.status = response.status;
        error.payload = payload;
        throw error;
    }

    return payload;
}
