import React, { useEffect, useState } from 'react';

const RANDOM_BG_JSON = 'https://randbg.api.smyhub.com/api/random?format=json&mode=auto';
const SESSION_KEY = 'infogenie_randbg_url';
const BG_GAUSSIAN_BLUR = 'calc(40px * 0.1)';

const RandomSiteBackground = () => {
  const [url, setUrl] = useState(() => {
    try {
      return sessionStorage.getItem(SESSION_KEY) || '';
    } catch {
      return '';
    }
  });

  useEffect(() => {
    let cancelled = false;

    const apply = (next) => {
      if (cancelled || !next) return;
      try {
        sessionStorage.setItem(SESSION_KEY, next);
      } catch { /* ignore */ }
      setUrl(next);
    };

    if (url) return undefined;

    (async () => {
      try {
        const res = await fetch(RANDOM_BG_JSON);
        if (!res.ok) return;
        const data = await res.json();
        const next = typeof data?.url === 'string' ? data.url : '';
        apply(next);
      } catch { /* 失败时仅显示 FallbackGradient */ }
    })();

    return () => { cancelled = true; };
  }, [url]);

  return (
    <div aria-hidden className="fixed inset-0 z-0 pointer-events-none overflow-hidden">
      <div className="absolute inset-0 bg-gradient-to-br from-[#a8e6cf] via-[#dcedc1] to-[#ffd3a5]" />
      <div
        className="absolute -top-6 -right-6 -bottom-6 -left-6 bg-cover bg-center transition-opacity duration-[450ms] ease-[ease]"
        style={{
          backgroundImage: url ? `url(${url})` : 'none',
          filter: `blur(${BG_GAUSSIAN_BLUR})`,
          transform: 'scale(1.04)',
          opacity: url ? 1 : 0,
        }}
      />
    </div>
  );
};

export default RandomSiteBackground;
