"use client";

import { useEffect } from "react";

interface BackgroundSettings {
  type: string;
  customImageUrl?: string;
}

export function BackgroundProvider() {
  useEffect(() => {
    const applyBackground = () => {
      try {
        const pageBackground = document.querySelector(
          ".page-background",
        ) as HTMLElement;
        if (!pageBackground) return;

        const stored = localStorage.getItem("background-settings");
        const settings: BackgroundSettings = stored
          ? JSON.parse(stored)
          : { type: "default" };

        // Retirer toutes les classes de fond
        pageBackground.classList.remove(
          "bg-default",
          "bg-gradient-blue",
          "bg-gradient-purple",
          "bg-gradient-green",
          "bg-gradient-orange",
          "bg-solid-light",
          "bg-solid-dark",
          "bg-custom-image",
        );

        const root = document.documentElement;

        if (settings.type === "custom-image" && settings.customImageUrl) {
          pageBackground.classList.add("bg-custom-image");
          root.style.setProperty(
            "--custom-background-image",
            `url(${settings.customImageUrl})`,
          );
        } else {
          pageBackground.classList.add(`bg-${settings.type || "default"}`);
          root.style.removeProperty("--custom-background-image");
        }
      } catch (error) {
        console.error("Error applying background:", error);
      }
    };

    // Appliquer immédiatement
    applyBackground();

    // Observer pour les changements de DOM (si le page-background est ajouté plus tard)
    const observer = new MutationObserver(() => {
      applyBackground();
    });

    observer.observe(document.body, {
      childList: true,
      subtree: true,
    });

    // Écouter les changements dans localStorage (autres onglets)
    const handleStorageChange = (e: StorageEvent) => {
      if (e.key === "background-settings") {
        applyBackground();
      }
    };

    // Écouter les événements personnalisés (même onglet)
    const handleBackgroundChanged = () => {
      applyBackground();
    };

    window.addEventListener("storage", handleStorageChange);
    window.addEventListener("background-changed", handleBackgroundChanged);

    return () => {
      observer.disconnect();
      window.removeEventListener("storage", handleStorageChange);
      window.removeEventListener("background-changed", handleBackgroundChanged);
    };
  }, []);

  return null;
}
