const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "::1"]);

function canUseWindow(): boolean {
  return typeof window !== "undefined";
}

function rewriteLocalhostUrl(rawUrl: string): string {
  if (!canUseWindow()) return rawUrl;

  try {
    const parsed = new URL(rawUrl);
    if (!LOCAL_HOSTS.has(parsed.hostname)) return rawUrl;
    parsed.hostname = window.location.hostname;
    return parsed.toString();
  } catch {
    return rawUrl;
  }
}

export function getReachableApiBaseUrl(apiBaseUrl?: string): string {
  const configured = (apiBaseUrl || "").trim();

  if (!configured) {
    return canUseWindow() ? window.location.origin : "";
  }

  if (/^https?:\/\//i.test(configured)) {
    return rewriteLocalhostUrl(configured).replace(/\/+$/, "");
  }

  if (canUseWindow()) {
    try {
      return new URL(configured, window.location.origin).toString().replace(/\/+$/, "");
    } catch {
      return configured.replace(/\/+$/, "");
    }
  }

  return configured.replace(/\/+$/, "");
}

export function toReachableAbsoluteUrl(value?: string, apiBaseUrl?: string): string {
  if (!value) return "";
  let raw = value.trim();
  if (!raw) return "";

  if (/^(data:|blob:)/i.test(raw)) return raw;
  if (/^https?:\/\//i.test(raw)) return rewriteLocalhostUrl(raw);

  // Normalize Windows-style paths and common upload path variants.
  raw = raw.replace(/\\/g, "/");
  raw = raw.replace(/^\.\/+/, "");
  raw = raw.replace(/^public\/uploads\//i, "/uploads/");
  raw = raw.replace(/^\/?uploads\//i, "/api/uploads/");
  if (/^uploads\//i.test(raw)) {
    raw = `/${raw}`;
  }

  const base = getReachableApiBaseUrl(apiBaseUrl);
  if (!base) return raw;

  try {
    return new URL(raw, `${base}/`).toString();
  } catch {
    return `${base}${raw.startsWith("/") ? "" : "/"}${raw}`;
  }
}
