// Get API base from injected env.js or fallback to /api relative path
const getApiBase = () => {
  if (typeof window !== "undefined" && window.__ENV__ && window.__ENV__.API_BASE) {
    return window.__ENV__.API_BASE;
  }
  return "/api";
};

const API_BASE = getApiBase();

export async function register(username, email, password, firstName, lastName, displayName) {
  const res = await fetch(`${API_BASE}/auth/register`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ 
      username, 
      email, 
      password,
      first_name: firstName,
      last_name: lastName,
      display_name: displayName
    }),
  });
  if (!res.ok) {
    const error = await res.json();
    throw new Error(error.detail || "Failed to register");
  }
  return res.json();
}

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

export async function getMe(token) {
  const res = await fetch(`${API_BASE}/auth/me`, {
    headers: {
      Authorization: `Bearer ${token}`,
    },
  });
  if (!res.ok) {
    const error = new Error("Failed to get user info");
    error.status = res.status;
    throw error;
  }
  return res.json();
}

export async function requestPasswordChangeCode(token) {
  const res = await fetch(`${API_BASE}/auth/request-password-change-code`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${token}`,
    },
  });
  if (!res.ok) {
    const error = await res.json();
    throw new Error(error.detail || "Failed to send verification code");
  }
  return res.json();
}

export async function changePassword(verificationCode, currentPassword, newPassword, token) {
  const res = await fetch(`${API_BASE}/auth/change-password`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    },
    body: JSON.stringify({
      verification_code: verificationCode,
      current_password: currentPassword,
      new_password: newPassword,
    }),
  });
  if (!res.ok) {
    const error = await res.json();
    throw new Error(error.detail || "Failed to change password");
  }
  return res.json();
}

// Auth helpers
export function saveToken(token) {
  localStorage.setItem("auth_token", token);
}

export function getToken() {
  return localStorage.getItem("auth_token");
}

export function removeToken() {
  localStorage.removeItem("auth_token");
}
