"use client";

import { usePatternBackground } from "@/components/background/PatternBackgroundProvider";
import { THEME_BG_ELEMENT_ID } from "@/lib/helpers/themeCache";
import { useLayoutEffect } from "react";

const THEME_BG_IMG_ID = "cached-theme-bg-img";
const THEME_BG_OVERLAY_ID = "cached-theme-bg-overlay";

export default function AppBackground() {
  const { isPattern, backgroundStyle, isCustomImage, customImageSettings } =
    usePatternBackground();

  useLayoutEffect(() => {
    if (!isPattern && !isCustomImage) {
      document.getElementById(THEME_BG_ELEMENT_ID)?.remove();
      return;
    }

    let element = document.getElementById(THEME_BG_ELEMENT_ID);
    if (!element) {
      element = document.createElement("div");
      element.id = THEME_BG_ELEMENT_ID;
      element.setAttribute("aria-hidden", "true");
      element.style.position = "fixed";
      element.style.inset = "0";
      element.style.pointerEvents = "none";
      element.style.zIndex = "0";
      document.body.appendChild(element);
    }

    if (isPattern) {
      element.style.overflow = "";
      document.getElementById(THEME_BG_IMG_ID)?.remove();
      document.getElementById(THEME_BG_OVERLAY_ID)?.remove();
      Object.assign(element.style, backgroundStyle as Record<string, string>);
      return;
    }

    if (isCustomImage && customImageSettings) {
      const { bgUrl, bgBlur, bgOpacity, bgOverlay } = customImageSettings;

      element.style.backgroundColor = "";
      element.style.backgroundImage = "";
      element.style.overflow = "hidden";

      let imgLayer = document.getElementById(THEME_BG_IMG_ID);
      if (!imgLayer) {
        imgLayer = document.createElement("div");
        imgLayer.id = THEME_BG_IMG_ID;
        imgLayer.style.position = "absolute";
        imgLayer.style.inset = "-40px";
        imgLayer.style.backgroundSize = "cover";
        imgLayer.style.backgroundPosition = "center";
        imgLayer.style.backgroundRepeat = "no-repeat";
        element.appendChild(imgLayer);
      }

      imgLayer.style.backgroundImage = `url("${bgUrl}")`;
      imgLayer.style.filter = bgBlur ? `blur(${bgBlur}px)` : "";
      imgLayer.style.opacity =
        bgOpacity != null ? String(bgOpacity / 100) : "1";

      let overlayLayer = document.getElementById(THEME_BG_OVERLAY_ID);
      if (!overlayLayer) {
        overlayLayer = document.createElement("div");
        overlayLayer.id = THEME_BG_OVERLAY_ID;
        overlayLayer.style.position = "absolute";
        overlayLayer.style.inset = "0";
        element.appendChild(overlayLayer);
      }

      const overlayOpacity =
        bgOverlay != null ? Number(bgOverlay) / 100 : 0;
      overlayLayer.style.backgroundColor =
        overlayOpacity > 0 ? `rgba(0,0,0,${overlayOpacity})` : "";
    }
  }, [backgroundStyle, isPattern, isCustomImage, customImageSettings]);

  return null;
}
