"use client";

const isLocalHostname = (hostname: string) =>
  hostname === "127.0.0.1" || hostname === "localhost" || hostname === "host.docker.internal";

const base64UrlEncodeUtf8 = (input: string) => {
  const bytes = new TextEncoder().encode(input);
  let binary = "";
  bytes.forEach((b) => {
    binary += String.fromCharCode(b);
  });
  const b64 = btoa(binary);
  return b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
};

/**
 * 将“仅本机可达”的 URL（例如 http://127.0.0.1:3210/api/storage/...）转换为浏览器可访问的地址。
 *
 * - 本地访问（页面本身是 localhost/127）时不改写
 * - 外网访问时，若目标是 localhost/127/host.docker.internal，则改为走 /api/onlyoffice/proxy 由 Next 服务端回源
 */
export const toBrowserAccessibleUrl = (rawUrl: string | null | undefined): string | null => {
  const input = String(rawUrl ?? "").trim();
  if (!input) return rawUrl ?? null;
  if (typeof window === "undefined") return input;

  try {
    if (input.startsWith("/api/onlyoffice/proxy")) return input;
    const pageHost = window.location.hostname;
    if (isLocalHostname(pageHost)) return input;

    const u = new URL(input);
    if (!isLocalHostname(u.hostname)) return input;

    const proxy = new URL("/api/onlyoffice/proxy", window.location.origin);
    proxy.searchParams.set("u", base64UrlEncodeUtf8(input));
    return proxy.toString();
  } catch {
    return input;
  }
};

