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

export function setToken(token, username) {
  localStorage.setItem('catan_token', token);
  localStorage.setItem('catan_user', username);
}

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

export function getUsername() {
  return localStorage.getItem('catan_user');
}

export async function apiFetch(path, options = {}) {
  const headers = options.headers || {};
  const token = getToken();
  if (token) {
    headers.Authorization = `Bearer ${token}`;
  }
  const response = await fetch(path, { ...options, headers });
  const data = await response.json().catch(() => ({}));
  if (!response.ok) {
    throw new Error(data.detail || 'Request failed');
  }
  return data;
}

export function wsUrl(path) {
  const proto = window.location.protocol === 'https:' ? 'wss' : 'ws';
  const token = getToken();
  return `${proto}://${window.location.host}${path}?token=${token}`;
}
