import { useState, useEffect } from 'react';
import { createPortal } from 'react-dom';
import './RandomBackdrop.css';

const RANDBG_JSON =
  'https://randbg.api.smyhub.com/api/random?format=json&mode=auto';

type RandomBgResponse = {
  url?: string;
};

/** 挂到 body，避免与 .app 内 filter/层叠上下文叠在一起盖住卡片 */
export const RandomBackdrop = () => {
  const [imageUrl, setImageUrl] = useState<string | null>(null);

  useEffect(() => {
    let cancelled = false;
    void fetch(RANDBG_JSON)
      .then((r) => {
        if (!r.ok) throw new Error(String(r.status));
        return r.json() as Promise<RandomBgResponse>;
      })
      .then((data) => {
        const u = data?.url;
        if (!cancelled && typeof u === 'string' && u.length > 0) {
          setImageUrl(u);
        }
      })
      .catch(() => {
        /* 保持 fallback 底色 */
      });
    return () => {
      cancelled = true;
    };
  }, []);

  return createPortal(
    <div className="random-backdrop" aria-hidden>
      {!imageUrl && <div className="random-backdrop__fallback" />}
      {imageUrl && (
        <div
          className="random-backdrop__image"
          style={{ backgroundImage: `url(${imageUrl})` }}
        />
      )}
    </div>,
    document.body
  );
};
