"use client"

import { useEffect } from "react"
import { usePathname } from "next/navigation"
import { useTheme } from "next-themes"
import {
  applyMailBackgroundDom,
  clearMailBackgroundDom,
} from "@/lib/mail-settings/mail-background-dom"
import { useClientThemeStore } from "@/lib/stores/client-theme-store"
import { useMailSettingsStore } from "@/lib/stores/mail-settings-store"
import { isMailAppPath } from "@/lib/suite/mail-route"

/** Applique thème clair/sombre/système (client) et fond décoratif mail. */
export function ClientThemeApplier() {
  const pathname = usePathname()
  const themeMode = useClientThemeStore((s) => s.themeMode)
  const backgroundId = useMailSettingsStore((s) => s.backgroundId)
  const { theme, setTheme } = useTheme()

  useEffect(() => {
    if (!theme || theme === themeMode) return
    setTheme(themeMode)
  }, [themeMode, theme, setTheme])

  useEffect(() => {
    if (!isMailAppPath(pathname)) {
      clearMailBackgroundDom()
      return
    }
    applyMailBackgroundDom(backgroundId)
    return () => clearMailBackgroundDom()
  }, [backgroundId, pathname])

  return null
}
