import { useState, useEffect } from 'react';

const RANDOM_BG_API =
  'https://randbg.api.smyhub.com/api/random?format=json';

/** 高斯模糊强度：10%（相对参考最大模糊半径，便于以后微调） */
const BLUR_PERCENT = 10;
const BLUR_REFERENCE_PX = 24;

export default function RandomBackdrop({ children }) {
  const [imageUrl, setImageUrl] = useState(null);

  useEffect(() => {
    let cancelled = false;
    (async () => {
      try {
        const res = await fetch(RANDOM_BG_API);
        const data = await res.json();
        const url = data?.url;
        if (!cancelled && typeof url === 'string' && url.length > 0) {
          setImageUrl(url);
        }
      } catch {
        /* 失败时仅用遮罩渐变，不阻塞页面 */
      }
    })();
    return () => {
      cancelled = true;
    };
  }, []);

  const blurPx = (BLUR_REFERENCE_PX * BLUR_PERCENT) / 100;

  return (
    <div className="relative min-h-screen">
      <div
        className="fixed inset-0 z-0 overflow-hidden pointer-events-none"
        aria-hidden
      >
        {imageUrl ? (
          <div
            className="absolute inset-0 bg-cover bg-center bg-no-repeat"
            style={{
              backgroundImage: `url(${imageUrl})`,
              filter: `blur(${blurPx}px)`,
              transform: 'scale(1.08)',
            }}
          />
        ) : null}
        {/* 浅色罩层：保证前景可读，并保留原站绿色系氛围 */}
        <div className="absolute inset-0 bg-gradient-to-br from-emerald-50/82 via-green-50/78 to-teal-50/82" />
      </div>

      <div className="relative z-10 min-h-screen">{children}</div>
    </div>
  );
}
