import styles from "./background.module.css";
import { useEffect, useRef, useState } from "react";

const Background = ({ children, className }) => {

    const circlesRef = useRef([]);
    const [theme, setTheme] = useState("light");

  const getRandomTranslation = () => {
    const randomX = Math.floor(Math.random() * 100) - 30; 
    const randomY = Math.floor(Math.random() * 100) - 30;
    return { x: randomX, y: randomY };
  };

  useEffect(() => {
    circlesRef.current.forEach((circle) => {
      if (circle) {
        const { x, y } = getRandomTranslation();
        circle.style.setProperty('--random-x', `${x}px`);
        circle.style.setProperty('--random-y', `${y}px`);
      }
    });
  }, []);

    useEffect(() => {
        const updateTheme = () => {
            setTheme(localStorage.getItem("theme") || "light");
        };

        updateTheme(); // Initial load

        window.addEventListener("theme-changed", updateTheme);

        return () => {
            window.removeEventListener("theme-changed", updateTheme);
        };
    }, []);


    return (
    <div className={`${styles.backgroundContainer} ${className || ''} ${theme === "light" ? styles.backgroundLight : styles.backgroundDark}`}>
      <div
        ref={(el) => (circlesRef.current[0] = el)}
        className={`${styles["circle"]} ${styles["circle-1"]}`}
        style={{ "--random-x": "0px", "--random-y": "0px" }}
      ></div>
      <div
        ref={(el) => (circlesRef.current[1] = el)}
        className={`${styles["circle"]} ${styles["circle-2"]}`}
        style={{ "--random-x": "0px", "--random-y": "0px" }}
      ></div>
      <div
        ref={(el) => (circlesRef.current[2] = el)}
        className={`${styles["circle"]} ${styles["circle-3"]}`}
        style={{ "--random-x": "0px", "--random-y": "0px" }}
      ></div>
      <div
        ref={(el) => (circlesRef.current[3] = el)}
        className={`${styles["circle"]} ${styles["circle-4"]}`}
        style={{ "--random-x": "0px", "--random-y": "0px" }}
      ></div>
      <div
        ref={(el) => (circlesRef.current[4] = el)}
        className={`${styles["circle"]} ${styles["circle-5"]}`}
        style={{ "--random-x": "0px", "--random-y": "0px" }}
      ></div>
      {children}
    </div>
  );
};

export default Background;
