const API_URL = import.meta.env.VITE_API_URL || '/api'

function getHeaders() {
  const token = localStorage.getItem('bhb-token')
  return {
    'Content-Type': 'application/json',
    ...(token ? { 'Authorization': `Bearer ${token}` } : {})
  }
}

export async function login(username, password) {
  const res = await fetch(`${API_URL}/auth/login`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ username, password })
  })
  if (!res.ok) throw new Error((await res.json()).error)
  return res.json()
}

export async function register(username, password) {
  const res = await fetch(`${API_URL}/auth/register`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ username, password })
  })
  if (!res.ok) throw new Error((await res.json()).error)
  return res.json()
}

export async function getMe() {
  const res = await fetch(`${API_URL}/auth/me`, { headers: getHeaders() })
  if (!res.ok) throw new Error('Not logged in')
  return res.json()
}

export async function fetchState() {
  const res = await fetch(`${API_URL}/state`)
  if (!res.ok) throw new Error('Failed to fetch state')
  return res.json()
}

export async function saveMember(member) {
  const res = await fetch(`${API_URL}/state/member`, {
    method: 'POST',
    headers: getHeaders(),
    body: JSON.stringify(member)
  })
  if (!res.ok) throw new Error((await res.json()).error)
  return res.json()
}

export async function moveMember(id, team_slot, type) {
  const res = await fetch(`${API_URL}/state/member/move`, {
    method: 'POST',
    headers: getHeaders(),
    body: JSON.stringify({ id, team_slot, type })
  })
  if (!res.ok) throw new Error((await res.json()).error)
  return res.json()
}

export async function deleteMember(id) {
  const res = await fetch(`${API_URL}/state/member/${id}`, {
    method: 'DELETE',
    headers: getHeaders()
  })
  if (!res.ok) throw new Error((await res.json()).error)
  return res.json()
}

export async function syncState(stateData) {
  const res = await fetch(`${API_URL}/state/sync`, {
    method: 'POST',
    headers: getHeaders(),
    body: JSON.stringify(stateData)
  })
  if (!res.ok) throw new Error((await res.json()).error)
  return res.json()
}

export async function getSaves() {
  const res = await fetch(`${API_URL}/saves`)
  if (!res.ok) throw new Error('Failed to fetch saves')
  return res.json()
}

export async function saveSlotData(slotIndex, state_json) {
  const res = await fetch(`${API_URL}/saves`, {
    method: 'POST',
    headers: getHeaders(),
    body: JSON.stringify({ slotIndex, state_json })
  })
  if (!res.ok) throw new Error((await res.json()).error)
  return res.json()
}

export async function getUsers() {
  const res = await fetch(`${API_URL}/users`, { headers: getHeaders() })
  if (!res.ok) throw new Error((await res.json()).error)
  return res.json()
}

export async function setRole(userId, role) {
  const res = await fetch(`${API_URL}/users/${userId}/role`, {
    method: 'POST',
    headers: getHeaders(),
    body: JSON.stringify({ role })
  })
  if (!res.ok) throw new Error((await res.json()).error)
  return res.json()
}

export async function saveMemberSkills(memberId, skills) {
  const res = await fetch(`${API_URL}/state/skills`, {
    method: 'POST',
    headers: getHeaders(),
    body: JSON.stringify({ memberId, skills })
  })
  if (!res.ok) throw new Error((await res.json()).error)
  return res.json()
}
