import { useEffect, useState } from "react";

const FALLBACK_API_BASE =
  process.env.NEXT_PUBLIC_API_BASE_URL?.replace(/\/$/, "") ??
  "http://127.0.0.1:3001";

function isLoopbackUrl(value: string) {
  return /^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/i.test(value);
}

function detectBrowserApiBase() {
  if (typeof window === "undefined") {
    return FALLBACK_API_BASE;
  }

  const protocol = window.location.protocol === "https:" ? "https:" : "http:";
  const hostname = window.location.hostname || "127.0.0.1";
  const host = window.location.host || `${hostname}:3000`;
  const envBase = process.env.NEXT_PUBLIC_API_BASE_URL?.replace(/\/$/, "");

  // When accessed through Nginx or another reverse proxy, prefer same-origin.
  // Only use NEXT_PUBLIC_API_BASE_URL in browser when it points to a real
  // remote address rather than localhost/127.0.0.1.
  if (envBase && !isLoopbackUrl(envBase)) {
    return envBase;
  }

  // Default to same-origin and let Nginx/Next rewrite /api/* to backend.
  // This avoids hard-coding :3001 when accessed by domain + custom port.
  return `${protocol}//${host}`;
}

export function useResolvedApiBase() {
  const [apiBase, setApiBase] = useState(() =>
    typeof window === "undefined" ? FALLBACK_API_BASE : detectBrowserApiBase(),
  );

  useEffect(() => {
    setApiBase(detectBrowserApiBase());
  }, []);

  return apiBase;
}

export function readBackendUnavailableMessage(apiBase?: string) {
  return `暂时无法连接后端服务，请确认 ${apiBase ?? FALLBACK_API_BASE} 已启动。`;
}
