export const API_BASE =
  process.env.NEXT_PUBLIC_API_BASE_URL ?? "";

export function getCookie(name: string): string | null {
  if (typeof document === "undefined") return null;
  const match = document.cookie.match(
    new RegExp(
      "(^| )" + name.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&") + "=([^;]+)"
    )
  );
  return match ? decodeURIComponent(match[2]) : null;
}

export function getToken(): string | null {
  if (typeof window === "undefined") return null;

  const ls = localStorage.getItem("ballistic_auth_token");
  if (ls && ls.trim().length > 0) return ls;

  const ck = getCookie("bb_access_token");
  if (ck && ck.trim().length > 0) return ck;

  return null;
}

export function qs(params: Record<string, any>) {
  const sp = new URLSearchParams();
  Object.entries(params).forEach(([k, v]) => {
    if (v === undefined || v === null || v === "") return;
    sp.set(k, String(v));
  });
  return sp.toString();
}