export const API_BASE_URL = "http://127.0.0.1:9000/";
export const BASE_URL = "http://127.0.0.1:9000";
export const API_URL = "https://backend.openthatpack.com/api/";
export const GAMES_BASE_URL = "https://api.sportsgameodds.com/v2";
export const X_API_KEY = "e6180f8a51963f3c8e694dd1ed62bba1";
// B2BINPAY `
export const B2BINPAY_BASE_URL = "https://v3.api-sandbox.b2binpay.com/";
export const B2BINPAY_ACCESS_TOKEN = "";
export const B2BINPAY_WALLET_ID = "393";
export const SESSION_SECRET = "dftghnjmk876yhnjmkoW4drERF5tfgDQ";
export const LOCAL_APP_URL = "http://localhost:3000/";

// ✅ 1) Non-JSON response test (should logout)
const nonJsonRes = new Response("<html>not json</html>", {
  status: 200,
  headers: { "Content-Type": "text/html" },
});

// ✅ 2) Not OK JSON test (should logout)
const notOkJsonRes = new Response(JSON.stringify({ message: "Unauthorized" }), {
  status: 401,
  headers: { "Content-Type": "application/json" },
});

// logout function
export async function forceLogout() {
  await fetch("/api/auth/logout", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ f: 1 }),
  }).then(() => {
    window.location.href = "/";
  });
}

export const parseJsonOrLogout = async (res) => {
  let data;

  try {
    data = await res.json();
    // forceLogout();
  } catch {
    // forceLogout();

    throw new Error("Invalid server response");
  }

  if (!res.ok) {
    // forceLogout();
    throw new Error(data?.message || data?.error || "Request failed");
  }

  return data;
};

export const sendRequest = async (option, callback) => {
  let url = BASE_URL + "/api/" + option.action;
  let method = option?.method || "POST";
  const is_token = option?.token ? true : false;

  let headers = {
    "Content-Type": "application/json",
    Accept: "*/*",
    "User-Agent": "Thunder Client (https://www.thunderclient.com)",
  };
  if (is_token) {
    headers["Authorization"] = `Bearer ${option.token}`;
  }

  let h = option?.header || [];
  h.forEach(function (i) {
    headers[i.name] = i.value;
  });

  let body = option?.body || {};

  let opt = null;
  if (method === "POST") {
    opt = {
      method: method,
      headers: headers,
      body: JSON.stringify(body),
    };
  } else {
    opt = {
      method: method,
      headers: headers,
    };
  }

  const handle = async () => {
    try {
      const response = await fetch(url, opt);
      const responseData = await response.json();
      if (response.ok) {
        callback(responseData);
      } else {
        callback({ resp: "error", message: "Something is wrong." });
      }
    } catch (error) {
      callback({ resp: "error", message: error });
      // forceLogout();
    }
  };
  await handle();
};

export function formatNumber(num) {
  if (num >= 1_000_000) {
    return (num / 1_000_000).toFixed(num % 1_000_000 === 0 ? 0 : 1) + "M";
  } else if (num >= 1_000) {
    return (num / 1_000).toFixed(num % 1000 === 0 ? 0 : 1) + "K";
  } else {
    return num.toString();
  }
}
export const IMAGE_BASE = "/cards";

export const getFullImageUrl = (img) => {
  if (!img) return "/placeholder.png";
  if (img.startsWith("http")) return img;
  return `${IMAGE_BASE}/${img.replace(/^\//, "")}`;
};
