const API_BASE = import.meta.env.VITE_API_URL || '';

export function getToken() {
  return localStorage.getItem('admin_token');
}

export function setToken(token) {
  localStorage.setItem('admin_token', token);
}

export function clearToken() {
  localStorage.removeItem('admin_token');
}

async function apiFetch(path, options = {}) {
  const headers = { ...options.headers };
  if (!(options.body instanceof FormData)) {
    headers['Content-Type'] = 'application/json';
  }
  const token = getToken();
  if (token) headers.Authorization = `Bearer ${token}`;

  const res = await fetch(`${API_BASE}${path}`, { ...options, headers });
  const data = await res.json().catch(() => ({}));
  if (!res.ok) throw new Error(data.error || 'Request failed');
  return data;
}

export const adminApi = {
  login: (username, password) =>
    apiFetch('/api/auth/login', { method: 'POST', body: JSON.stringify({ username, password }) }),

  me: () => apiFetch('/api/auth/me'),

  getContent: () => apiFetch('/api/content'),

  updateSection: (section, data) =>
    apiFetch(`/api/content/${section}`, { method: 'PUT', body: JSON.stringify(data) }),

  changePassword: (currentPassword, newPassword) =>
    apiFetch('/api/auth/password', { method: 'PUT', body: JSON.stringify({ currentPassword, newPassword }) }),

  upload: async (file) => {
    const form = new FormData();
    form.append('file', file);
    return apiFetch('/api/upload', { method: 'POST', body: form });
  },
};
