const API_BASE = window.location.origin + window.location.pathname.replace(/\/panel\/.*$/, '');

const Auth = {
    getAccessToken: () => localStorage.getItem('access_token'),
    getRefreshToken: () => localStorage.getItem('refresh_token'),
    getUsuario: () => JSON.parse(localStorage.getItem('usuario') || 'null'),
    setSession: (data) => {
        localStorage.setItem('access_token', data.access_token);
        localStorage.setItem('refresh_token', data.refresh_token);
        localStorage.setItem('usuario', JSON.stringify(data.usuario));
    },
    clear: () => {
        localStorage.removeItem('access_token');
        localStorage.removeItem('refresh_token');
        localStorage.removeItem('usuario');
    },
    requireLogin: () => {
        if (!Auth.getAccessToken()) {
            window.location.href = 'login.html';
        }
    },
};

async function apiFetch(path, options = {}) {
    const headers = options.headers || {};
    const token = Auth.getAccessToken();
    if (token) headers['Authorization'] = 'Bearer ' + token;

    let body = options.body;
    if (body && typeof body === 'object' && !(body instanceof URLSearchParams)) {
        const params = new URLSearchParams();
        Object.entries(body).forEach(([k, v]) => params.append(k, v));
        body = params;
    }

    let response = await fetch(API_BASE + path, { ...options, headers, body });

    if (response.status === 401 && Auth.getRefreshToken()) {
        const refreshed = await fetch(API_BASE + '/auth/refresh', {
            method: 'POST',
            body: new URLSearchParams({ refresh_token: Auth.getRefreshToken() }),
        });
        if (refreshed.ok) {
            const data = await refreshed.json();
            localStorage.setItem('access_token', data.access_token);
            headers['Authorization'] = 'Bearer ' + data.access_token;
            response = await fetch(API_BASE + path, { ...options, headers, body });
        } else {
            Auth.clear();
            window.location.href = 'login.html';
            throw new Error('Sesión expirada');
        }
    }

    const json = await response.json().catch(() => ({}));
    if (!response.ok) {
        throw new Error(json.error || 'Error en la solicitud');
    }
    return json;
}
