import { useEffect, useState } from "react";

const GEO_API = "https://geoip.api.smyhub.com/api";

function formatGeo(g: Record<string, string> | null): string {
  if (!g || typeof g !== "object") return "";
  const parts: string[] = [];
  if (g.countryName) parts.push(g.countryName);
  if (g.regionName) parts.push(g.regionName);
  if (g.cityName) parts.push(g.cityName);
  return parts.join(" ");
}

export function GeoFooter() {
  const [text, setText] = useState("正在获取访问信息…");

  useEffect(() => {
    fetch(GEO_API, { credentials: "omit", cache: "no-store" })
      .then((r) => {
        if (!r.ok) throw new Error("http " + r.status);
        return r.json() as Promise<{ ip?: string; geo?: Record<string, string> }>;
      })
      .then((data) => {
        const ip = data && data.ip ? String(data.ip) : "—";
        let loc = formatGeo(data.geo || null);
        if (!loc) loc = "未知位置";
        setText(`您的访问 IP：${ip} · ${loc}`);
      })
      .catch(() => setText("无法获取访问位置信息"));
  }, []);

  return (
    <p className="site-footer-geo" id="site-footer-geo" aria-live="polite">
      {text}
    </p>
  );
}
