"use client"

import { useEffect, useRef } from "react"
import { useCurrentUser } from "@/lib/api/hooks/use-current-user"
import { useMailSettingsStore } from "@/lib/stores/mail-settings-store"
import type { MailThemeMode } from "@/lib/mail-settings/types"

/** Applique le thème organisationnel imposé sur le store mail partagé. */
export function AgendaOrgPolicySync() {
  const { data: user } = useCurrentUser()
  const appliedRef = useRef<MailThemeMode | null>(null)

  const enforceOrgTheme = user?.org_agenda?.enforce_org_theme ?? false
  const orgThemeMode = user?.org_agenda?.default_theme_mode

  useEffect(() => {
    if (!enforceOrgTheme || !orgThemeMode) return
    if (appliedRef.current === orgThemeMode) return

    const current = useMailSettingsStore.getState().themeMode
    if (current !== orgThemeMode) {
      useMailSettingsStore.getState().setThemeMode(orgThemeMode)
    }
    appliedRef.current = orgThemeMode
  }, [enforceOrgTheme, orgThemeMode])

  return null
}
