import React, { useEffect } from "react";
import { useThree } from "@react-three/fiber";
import * as THREE from "three";
import { useStore } from "../store/store.ts";

const textureLoader = new THREE.TextureLoader();

const SceneBackgroundInner: React.FC = () => {
  const backdropUrl = useStore((state) => state.backdropUrl);
  const { scene } = useThree();

  useEffect(() => {
    if (backdropUrl) {
      textureLoader.load(backdropUrl, (texture) => {
        texture.colorSpace = THREE.SRGBColorSpace;
        scene.background = texture;
      });
    } else {
      scene.background = new THREE.Color(0x4a4a4a);
    }

    return () => {
      if (scene.background instanceof THREE.Texture) {
        scene.background.dispose();
      }
    };
  }, [backdropUrl, scene]);

  return null;
};

export const SceneBackground = React.memo(SceneBackgroundInner);
SceneBackground.displayName = "SceneBackground";
