"use client"

import { useEffect } from "react"
import { useTheme } from "next-themes"
import {
  mailBackgroundStyle,
  normalizeMailBackgroundId,
} from "@/lib/mail-settings/constants"
import { useMailSettingsStore } from "@/lib/stores/mail-settings-store"

function applyMailBackground(backgroundId: string) {
  const html = document.documentElement
  const normalized = normalizeMailBackgroundId(backgroundId)
  const { background, fallbackColor } = mailBackgroundStyle(normalized)

  if (normalized === "none" || background === "none") {
    delete html.dataset.mailBackground
    html.style.removeProperty("--mail-bg-layer")
    html.style.removeProperty("--mail-bg-fallback")
    return
  }

  html.dataset.mailBackground = normalized
  html.style.setProperty("--mail-bg-layer", background)
  html.style.setProperty("--mail-bg-fallback", fallbackColor)
}

/** Applique thème clair/sombre/système et fond décoratif sur le document. */
export function MailThemeApplier() {
  const themeMode = useMailSettingsStore((s) => s.themeMode)
  const backgroundId = useMailSettingsStore((s) => s.backgroundId)
  const { setTheme } = useTheme()

  useEffect(() => {
    setTheme(themeMode)
  }, [themeMode, setTheme])

  useEffect(() => {
    applyMailBackground(backgroundId)
  }, [backgroundId])

  return null
}
