import React, { useEffect, useState } from "react";
import { RAND_BG_API_ORIGIN } from "../config";

/**
 * 固定全视口随机背景：拉取 randbg JSON 后铺图，高斯模糊强度为 UI 参考半径的 20%（见 CSS 变量）。
 */
export default function RandomSiteBackground() {
  const [url, setUrl] = useState("");

  useEffect(() => {
    let cancelled = false;
    const load = async () => {
      try {
        const endpoint = `${RAND_BG_API_ORIGIN}/api/random?format=json&mode=auto`;
        const res = await fetch(endpoint, { credentials: "omit" });
        if (!res.ok) return;
        const data = await res.json().catch(() => ({}));
        const next = typeof data.url === "string" ? data.url.trim() : "";
        if (!cancelled && next) setUrl(next);
      } catch {
        /* 失败时仅保留 body 纯色底 */
      }
    };
    load();
    return () => { cancelled = true; };
  }, []);

  if (!url) return null;

  return (
    <div className="app-rand-bg" aria-hidden>
      <img src={url} alt="" className="app-rand-bg__img" decoding="async" />
      <div className="app-rand-bg__veil" />
    </div>
  );
}
