"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 { isDemoPath } from "@/lib/demo/demo-route"
import { useDemoThemeStore } from "@/lib/demo/demo-theme-store"
import { useMailSettingsStore } from "@/lib/stores/mail-settings-store"
import { isMailAppPath } from "@/lib/suite/mail-route"
import type { MailThemeMode } from "@/lib/mail-settings/types"

function resolveAppliedThemeMode(
  pathname: string | null,
  mailThemeMode: MailThemeMode,
  demoThemeMode: MailThemeMode,
): MailThemeMode {
  if (isDemoPath(pathname)) return demoThemeMode
  return mailThemeMode
}

/** Applique thème clair/sombre/système et fond décoratif sur le document. */
export function MailThemeApplier() {
  const pathname = usePathname()
  const mailThemeMode = useMailSettingsStore((s) => s.themeMode)
  const demoThemeMode = useDemoThemeStore((s) => s.themeMode)
  const appliedThemeMode = resolveAppliedThemeMode(
    pathname,
    mailThemeMode,
    demoThemeMode,
  )
  const backgroundId = useMailSettingsStore((s) => s.backgroundId)
  const { theme, setTheme } = useTheme()

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

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

  return null
}
