"use client"

import { useEffect } from "react"
import { useComposeActions } from "@/lib/compose-context"
import { takePendingCompose } from "@/lib/agenda/agenda-mail-compose"

/**
 * Récupère un brouillon déposé par une autre app de la suite (ex. Agenda →
 * « Envoyer un email aux invités ») et ouvre la fenêtre de composition.
 */
export function PendingComposeBridge() {
  const { openComposeWithInitial } = useComposeActions()

  useEffect(() => {
    const pending = takePendingCompose()
    if (!pending || pending.to.length === 0) return
    openComposeWithInitial({
      to: pending.to,
      subject: pending.subject ?? "",
      bodyHtml: pending.bodyText
        ? `<p>${pending.bodyText.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/\n/g, "<br/>")}</p>`
        : undefined,
      focusBodyOnMount: true,
    })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  return null
}
