import { apiUrl } from "../auth/session.js";

export function resolveTeamLogoUrl(stored) {
  if (stored == null) return "";
  const s = String(stored).trim();
  if (!s) return "";

  if (/^https?:\/\/img\.sofascore\.com\//i.test(s)) {
    let m = /\/normal\/(\d+)\.png/i.exec(s);
    if (m) return apiUrl(`team_logo_proxy.php?id=${encodeURIComponent(m[1])}`);
    m = /\/team\/(\d+)\/image/i.exec(s);
    if (m) return apiUrl(`team_logo_proxy.php?id=${encodeURIComponent(m[1])}`);
  }

  if (s.includes("team_logo_proxy.php")) {
    try {
      const u = s.startsWith("http") ? new URL(s) : new URL(s, window.location.origin);
      const qs = u.search || "";
      if (qs) return apiUrl(`team_logo_proxy.php${qs.startsWith("?") ? qs : `?${qs}`}`);
    } catch {

    }
  }

  if (s.startsWith("/api/team_logo_proxy.php")) {
    const q = s.indexOf("?");
    return apiUrl(q >= 0 ? `team_logo_proxy.php${s.slice(q)}` : "team_logo_proxy.php");
  }

  return s;
}
