// Defensive handling: some env consumers or docker-compose YAML authors may
// accidentally include literal quotes when setting env vars (for example,
// `VITE_API_BASE=""`). That results in the string `""` being present at
// runtime and ends up URL-encoded as `%22%22` in fetches. Normalize here so
// an accidental quoted-empty value becomes an empty string.
const candidateEnvVars = [import.meta.env.VITE_API_BASE, import.meta.env.VITE_BASEPATH, import.meta.env.PUBLIC_URL];
let rawEnvApiBase = "";
for (const candidate of candidateEnvVars) {
  if (typeof candidate === "string" && candidate.trim() !== "") {
    rawEnvApiBase = candidate;
    break;
  }
}

let envApiBase = typeof rawEnvApiBase === "string" ? rawEnvApiBase.trim() : "";

// If someone set the literal value '""' or "''", treat it as empty.
if (envApiBase === '""' || envApiBase === "''") {
  envApiBase = "";
}

// Remove surrounding single or double quotes if present.
if (
  (envApiBase.startsWith('"') && envApiBase.endsWith('"')) ||
  (envApiBase.startsWith("'") && envApiBase.endsWith("'"))
) {
  envApiBase = envApiBase.slice(1, -1);
}

const publicBase = import.meta.env.BASE_URL || "";

// Normalize base: treat '/' as empty, and strip any trailing slash so
// constructing `${base}/api/...` never produces a protocol-relative
// URL like `//api/...` which the browser resolves to `https://api/...`.
let baseCandidate = envApiBase || publicBase || "";
if (baseCandidate === "/") {
  baseCandidate = "";
}
// Remove trailing slash if present (but keep leading slash for path bases).
if (baseCandidate.length > 1 && baseCandidate.endsWith("/")) {
  baseCandidate = baseCandidate.replace(/\/+$/, "");
}

// Runtime safeguard: when the app is opened at a URL that does not include
// the configured base path (for example, dev server serving at `/` while
// VITE_BASEPATH is `/ketr.ketran`), React Router's <Router basename="...">
// will refuse to render because the current pathname doesn't start with the
// basename. In that situation throw an error!
try {
  if (typeof window !== "undefined" && baseCandidate) {
    const pathname = window.location && window.location.pathname ? window.location.pathname : "";
    if (!(pathname === baseCandidate || pathname.startsWith(baseCandidate + "/"))) {
      // Mismatch: FAIL!
      throw Error(`Configured base '${baseCandidate}' does not match current pathname '${pathname}'`);
    }
  }
} catch (e) {
  /* ignore errors in environments without window */
}
const base = baseCandidate;
// Assets are served from different locations in dev vs production:
// - In both dev and production, bundled assets (JS, CSS, audio, etc.) are under '/assets'
// - Images are under '/gfx'
// To make development smooth, the assetsPath is set to the base path, and
// code uses `${assetsPath}/assets/...` for bundled assets and `${assetsPath}/gfx/...` for images.
// In dev, Vite's strip-basepath plugin handles serving from the correct locations.
// In production, static files are served from the build directory.
const assetsPath = base;
const gamesPath = `${base}`;

const ws_base: string = `${window.location.protocol === "https:" ? "wss" : "ws"}://${
  window.location.host
}${base}/api/v1/games/ws`;

export { base, ws_base, assetsPath, gamesPath };
