import { useEffect, useState } from "react";

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

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";
  return `${protocol}//${hostname}:3001`;
}

export function useResolvedApiBase() {
  const [apiBase, setApiBase] = useState(FALLBACK_API_BASE);

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

  return apiBase;
}

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